How to use an android service to hold a server communication? - Java for Android App Development

Hi,
I´m new here and hope you can help me.
I wrote a service for an android app.
The service should keep on a server communication with an TCP Server.
I have to use this kind of solution!
If I start the app, the service is called. I get an connection with the run()-Method (I checked it with an boolean).
But now I can´t receive and send any messanges between server and android device.
Here is the code, may it helps:
Activity:
Code:
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import com.example.obdii.OBDService.connectSocket;
public class Werkstatt_Client extends Activity {
//Variablen initalisieren
private ListView mList;
private ArrayList arrayList;
private MyCustomAdapter mAdapter;
private OBDService mTcpClient;
static String ip;
public String message;
TextView nachricht;
//SERVICE
private OBDService hallo;
private ServiceConnection serviceconntection = new ServiceConnection(){
//EDITED PART
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
hallo = ((OBDService.LocalBinder)service).getService();
}
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
hallo = null;
}
};
private void doBindService() {
bindService(new Intent(Werkstatt_Client.this, OBDService.class), serviceconntection, Context.BIND_AUTO_CREATE);
}
private void doUnbindService() {
hallo.onDestroy();
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Layout ansprechen
setContentView(R.layout.activity_werkstatt__client);
//Variablen initalisieren
arrayList = new ArrayList();
final EditText eingabe = (EditText) findViewById(R.id.TfNachricht);
Button send = (Button)findViewById(R.id.BtnSenden);
//Einfügen des eigenen ListViews mit dem Namen list_item
//(Stellt den Verlauf besser dar)
mList = (ListView)findViewById(R.id.chatlist);
mAdapter = new MyCustomAdapter(this, arrayList);
mList.setAdapter(mAdapter);
/* //Binding the activity to the service to perform client-server operations
//start service on create
startService(new Intent(Werkstatt_Client.this,OBDService.class));
doBindService();*/
//OnClickListener für den Button Senden
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
message = eingabe.getText().toString();
//Nachricht zum Verlauf hinzufügen
arrayList.add("Kunde: " + message);
//Nachricht an Server senden
OBDService oc = new OBDService();
connectSocket ic = oc.new connectSocket();
if(ic.k = false){
System.out.println("ICH KANN NICHT SENDEN");
//}
if (ic.k = true) {
//System.out.println(message);
oc.sendMessage(message);
}
//aktualisiert die ListView bei neuen Nachrichten
mAdapter.notifyDataSetChanged();
eingabe.setText("");
}
}
});
}
/**Diese Methode liest die IP aus dem
* dafür vorgesehenen Textfeld aus und
* übergibt sie der Klasse TCPClient*/
public void ipsetzen (View view){
EditText IP = (EditText)findViewById(R.id.TfIP);
ip = (IP.getText().toString());
Intent ir=new Intent(this, OBDService.class);
ir.putExtra("data", ip);
this.startService(ir);
// Verbindung mit dem Server aufbauen
new connectTask().execute("");
}
/**Diese Methode äffnet einen TCPClient
* (Asynchroner Task)*/
public class connectTask extends AsyncTask<String,String,OBDService> {
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
//Empfangene Nachrichten vom Server im Verlauf hinzufügen
arrayList.add("Werkstatt: " + values[0]);
//Erkennt, dass die Daten sich geändert haben (Nachricht) und fügt sie in einer neuen Zeile hinzu
mAdapter.notifyDataSetChanged();
//Sting aus dem Verlauf abrufen
String werkstattanfrage = values[0].toString();
//Ausgabe zum Debuggen
System.out.println(werkstattanfrage);
//Relevante Zeichen aus String auslesen
}
@Override
protected OBDService doInBackground(String... arg0) {
// TODO Auto-generated method stub
return null;
}
}
public void quittung(View view){
nachricht=(TextView)findViewById(R.id.TfNachricht);
nachricht.setText("Anweisung ausgefuehrt");
}
}
Here is the service:
Code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class OBDService extends Service {
public static String SERVERIP; //Hier muss die IP stehen
public static final int SERVERPORT = 8888;
PrintWriter out;
BufferedReader in;
Socket socket;
InetAddress serverAddr;
private boolean mRun = false;
private String serverMessage;
private OnMessageReceived mMessageListener = null;
public String message;
private final IBinder mylocalbinder = new LocalBinder();
TCPClient mTcpClient = new TCPClient(null);
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
Log.e("","Client hat sich verbunden");
return mylocalbinder;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
Log.e("","OnCreat");
super.onCreate();
}
/**Diese Methode Sendet eingetippte Nachrichten
* Server
*/
public void sendMessage(String message){
if(out == null){
System.out.println(message + " ICH KANN NICHT GESENDET WERDEN");
}
if (out != null && !out.checkError()) {
out.println(message);
System.out.println(message + "ICH BIN DER SERVICE");
//Sicherstellen, dass die gesammte Nachricht erfasst wird
out.flush();
}
}
@Override
public int onStartCommand(Intent intent,int flags, int startId){
super.onStartCommand(intent, flags, startId);
sendMessage(message);
System.out.println("I am in on start");
SERVERIP= (String) intent.getExtras().get("data");
// Toast.makeText(this,"Service created ...", Toast.LENGTH_LONG).show();
Runnable connect = new connectSocket();
new Thread(connect).start();
return START_STICKY;
}
class connectSocket implements Runnable {
boolean k;
/**Diese Methode handhabt die gesendeten
* und empfangenen Nachrichten*/
public void run() {
mRun = true;
try {
//IP-Adresse des Servers übergeben
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
//Sicherheitsausgabe an den Server senden
Log.e("TCP Client", "Kunde: Connecting...");
//Öffnet einen Socket, um eine Verbindung mit dem Server herzustellen
Socket socket = new Socket(serverAddr, SERVERPORT);
try {
//Sendet die Nachricht zum Server
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
//Sicherheitsausgabe an den Server
Log.e("TCP Client", "Kunde: Sent.");
Log.e("TCP Client", "Kunde: Done.");
//Empfange Nachrichen vom Server
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//Der Client achtet auf eingehende Nachrichten vom Server
while (mRun) {
serverMessage = in.readLine();
if (serverMessage != null && mMessageListener != null) {
//Ruft die Methode messageReveives von der MainActivity auf
mMessageListener.messageReceived(serverMessage);
}
serverMessage = null;
}
Log.e("RESPONSE FROM SERVER", "Werkstattserver: Received Message: '" + serverMessage + "'");
} catch (Exception e){
//Sicherheitsausgabe an den Server zum Debuggen
Log.e("TCP", "Werkstattserver: Error");
socket.close();
//Dieser Block wird ausgeführt, wenn ein Error aufgetreten ist
}
} catch (Exception e) {
//Sicherheitsausgabe an den Server zum Debuggen
Log.e("TCP", "Kunde: Error", e);
}
}
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
try {
socket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
socket = null;
}
@Override
public void onRebind(Intent intent) {
// TODO Auto-generated method stub
super.onRebind(intent);
}
@Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
return super.onUnbind(intent);
}
public void test(){
Log.e("", "test");
}
public class LocalBinder extends Binder{
public LocalBinder(){
Log.e("", "Binder erzeugt");
}
public OBDService getService(){
return OBDService.this;
}
}
//Zugriff auf die Main Activity (übergabge der Nachrichten)
public interface OnMessageReceived {
public void messageReceived(String message);
}
}
If I try it only with my TCPClient Class, the connection runs. May I call a method wrong?!

Related

[Q] help on eclipse app

Hi guys,
First of all i`m completly noob on this so don`t be much hard with me
ok. i`m trying to develop a simple app just to run 4 simple command to install another app but for now the only thing that i can get to work was asking for su permissions...
can someone help me with this?
Thks a lot
HTML:
try {
runtime.exec("su -c busybox mount -o rw,remount /system");
runtime.exec("cp /sdcard/gscript/xrecovery.sh /data/local/tmp/xrecovery.sh");
runtime.exec("chmod 777 /data/local/tmp/xrecovery.sh");
runtime.exec("/data/local/tmp/xrecovery.sh");
runtime.exec("reboot");
}
catch (IOException e) {
e.printStackTrace();
do not think anyone has the knowledge to help me: .- (
My intention is to create a simple program that installs a file which is in sh sdcard,
"sdcard / gscript / xrecovery.sh"
until now could only be granted access to the root but do not know where and what command should I put to run that sh file...
is that no one can / want help?
thks
HTML:
import java.io.DataOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class xRecovery extends Activity {
Button app_name;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app_name = (Button)findViewById(R.id.TextView01);
xRecovery.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {;
}
});
setContentView(R.layout.main);
try {
Runtime.getRuntime().exec("/sdcard/gscript/xrecovery.sh");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
Process process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
{
os.writeBytes("mount -o rw,remount -t yaffs2 /dev/block/mtdblock03 /system\n" +
"exit \n");
os.flush();
process.waitFor();
}
Runtime.getRuntime().exec("/sdcard/gscript/xrecovery.sh");
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected String[] getPackageResourcePath(String string) {
// TODO Auto-generated method stub
return null;
}
private static void setOnClickListener(OnClickListener onClickListener) {
// TODO Auto-generated method stub
}
}
You should be able to execute a .sh file by using:
Code:
sh xrecovery.sh
spolfliet said:
You should be able to execute a .sh file by using:
Code:
sh xrecovery.sh
Click to expand...
Click to collapse
Without sdcard path! ?
And where should i put?
Thks; )
Sent from my AOSP on Xperia (US) using XDA App
Of course you need to specify the path (it cannot guess where your script is, unless you add it to your PATH). So I guess the following should work for you:
Code:
Runtime.getRuntime().exec("sh /sdcard/gscript/xrecovery.sh");
Unfortunely i cant make this work UK sure that im putting the command Sony the wrong place. I've allready try put Sony a different pplaces but never work: (
Thks anyway; )
Sent from my AOSP on Xperia (US) using XDA App
really need help!
here is my complete code for what i want to do
HTML:
package com.rendeiro2005.xRecovery;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class xRecovery extends Activity {
Button INSTALL;
Button REMOVE;
AlertDialog.Builder builder;
AlertDialog Alert;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try
{
Process process = Runtime.getRuntime().exec("su");
DataOutputStream outputStream = new DataOutputStream(process.getOutputStream());
DataInputStream inputStream = new DataInputStream(process.getInputStream());
outputStream.writeBytes("\n");
outputStream.flush();
outputStream.writeBytes("exit\n");
outputStream.flush();
process.waitFor();
process.waitFor();
if (process.exitValue() != 255) {
toastMessage("root");
}
else {
toastMessage("not root");
}
}
catch (IOException e)
{
try {
throw new Exception(e);
} catch (Exception e1) {
e1.printStackTrace();
}
}
catch (InterruptedException e)
{
try {
throw new Exception(e);
} catch (Exception e1) {
e1.printStackTrace();
}
}
INSTALL = (Button)findViewById(R.id.Button01);
REMOVE = (Button)findViewById(R.id.Button02);
builder = new AlertDialog.Builder(this);
builder.setMessage("Do you want to install xRecovery?");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
Runtime.getRuntime().exec("sh /sdcard/gscript/xrecovery.sh");
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),
"Done",
Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
Alert = builder.create();
INSTALL.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Alert.show();
}
});
REMOVE.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
}
});
}
private void toastMessage(String string) {
}
}
i haven`t donne the uninstall part.
the problem here is everything work as it should exept the "sh" doesn`t do anything.
can anyone help me with this? i`m just trying to understand how the process works
thks a lot

[Q] Shoutcast ICY to Http (Eclair compatible)

Hi.
I'm currently working on a wakeup-app (alarm) that plays your favorite radio-station via shoutcast-stream.
It looked really easy:
Code:
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(PATH_TO_FILE);
mp.prepare();
mp.start();
Then I found out Eclair doesn't support shoutcast's ICY protocol. Grmbl.
So for 2.1 (and earlier versions) it is required to handle the shoutcast-stream seperatly and pass it to MediaPlayer via http.
I even found an example:
http://code.google.com/p/npr-android-app/source/browse/trunk/Npr/src/org/npr/android/news/StreamProxy.java
Problem is that it's all a bit too advanced for me, so I was wondering if anyone has a really simple example of how to do this?
Something like:
"Add 'this file' to your project (where 'this file' would be a class similarly to StreamProxy) and then add this to your application:"
Code:
StreamProxy sp = new StreamProxy();
sp.setDataSource( SHOUTCAST_URL );
MediaPlayer mp = new MediaPlayer();
mp.setDataSource( sp.getProxyUrl );
mp.prepare();
mp.start();
(Pardon my english
fixed!
Will post how I did it soon.
Here's the app:
http://android.rejh.nl/fmalarm
Just got reminded by someone that I never posted the solution. Here goes:
Code:
// Streamurl
String streamUrl = "[Path-to-audio-stream-or-file]";
// Prepare Proxy (for Android 2.1 en lower (sdk<8))
sdkVersion = 0;
try { sdkVersion = Integer.parseInt(Build.VERSION.SDK); } // Note: Build.VERSION.SDK is deprecated..
catch (NumberFormatException e) {}
if (sdkVersion<8) {
if (proxy==null) {
try {
proxy = new StreamProxy();
proxy.init();
proxy.start();
streamUrl = String.format("http://127.0.0.1:%d/%s", proxy.getPort(), url);
} catch(IllegalStateException e) { Log.e(LOGTAG," -> IllStateException: "+e, e); }
}
}
// Create mediaplayer and set stream (proxied if needed)
mp = new MediaPlayer();
mp.setDataSource(streamUrl);
UPDATE!! Forgot the StreamProxy code
Code:
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Minor changes by REJH Gadellaa 2010/2011
package org.npr.android.news;
import android.util.Log;
import org.apache.http.Header;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.ParseException;
import org.apache.http.ProtocolVersion;
import org.apache.http.RequestLine;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionOperator;
import org.apache.http.conn.OperatedClientConnection;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.impl.conn.DefaultClientConnectionOperator;
import org.apache.http.impl.conn.DefaultResponseParser;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.io.HttpMessageParser;
import org.apache.http.io.SessionInputBuffer;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicLineParser;
import org.apache.http.message.ParserCursor;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.CharArrayBuffer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.StringTokenizer;
public class StreamProxy implements Runnable {
private static final String LOG_TAG = "FMA2Proxy";
private int port = 5050;
public int getPort() {
return port;
}
private boolean isRunning = true;
private ServerSocket socket;
private Thread thread;
public void init() {
try {
socket = new ServerSocket(port, 0, InetAddress.getByAddress(new byte[] {127,0,0,1}));
socket.setSoTimeout(5000);
port = socket.getLocalPort();
Log.d(LOG_TAG, "port " + port + " obtained");
} catch (UnknownHostException e) {
Log.e(LOG_TAG, "Error initializing server", e);
} catch (IOException e) {
Log.e(LOG_TAG, "Error initializing server", e);
}
}
public void start() {
if (socket == null) {
throw new IllegalStateException("Cannot start proxy; it has not been initialized.");
}
thread = new Thread(this);
thread.start();
}
public void stop() {
isRunning = false;
if (thread == null) {
throw new IllegalStateException("Cannot stop proxy; it has not been started.");
}
if (socket!=null) { try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
thread.interrupt();
try {
thread.join(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// @Override
public void run() {
Log.d(LOG_TAG, "running");
while (isRunning) {
try {
Socket client = socket.accept();
if (client == null) {
continue;
}
Log.d(LOG_TAG, "client connected");
HttpRequest request = readRequest(client);
processRequest(request, client);
} catch (SocketTimeoutException e) {
// Do nothing
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to client", e);
}
}
Log.d(LOG_TAG, "Proxy interrupted. Shutting down.");
}
private HttpRequest readRequest(Socket client) {
HttpRequest request = null;
InputStream is;
String firstLine;
try {
is = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
firstLine = reader.readLine();
} catch (IOException e) {
Log.e(LOG_TAG, "Error parsing request", e);
return request;
}
if (firstLine == null) {
Log.i(LOG_TAG, "Proxy client closed connection without a request.");
return request;
}
StringTokenizer st = new StringTokenizer(firstLine);
String method = st.nextToken();
String uri = st.nextToken();
Log.d(LOG_TAG, uri);
String realUri = uri.substring(1);
Log.d(LOG_TAG, realUri);
request = new BasicHttpRequest(method, realUri);
return request;
}
private HttpResponse download(String url) {
DefaultHttpClient seed = new DefaultHttpClient();
SchemeRegistry registry = new SchemeRegistry();
registry.register(
new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
SingleClientConnManager mgr = new MyClientConnManager(seed.getParams(),
registry);
DefaultHttpClient http = new DefaultHttpClient(mgr, seed.getParams());
HttpGet method = new HttpGet(url);
HttpResponse response = null;
try {
Log.d(LOG_TAG, "starting download");
response = http.execute(method);
Log.d(LOG_TAG, "downloaded");
} catch (ClientProtocolException e) {
Log.e(LOG_TAG, "Error downloading", e);
} catch (IOException e) {
Log.e(LOG_TAG, "Error downloading", e);
}
return response;
}
private void processRequest(HttpRequest request, Socket client)
throws IllegalStateException, IOException {
if (request == null) {
return;
}
Log.d(LOG_TAG, "processing");
String url = request.getRequestLine().getUri();
HttpResponse realResponse = download(url);
if (realResponse == null) {
return;
}
Log.d(LOG_TAG, "downloading...");
InputStream data = realResponse.getEntity().getContent();
StatusLine line = realResponse.getStatusLine();
HttpResponse response = new BasicHttpResponse(line);
response.setHeaders(realResponse.getAllHeaders());
Log.d(LOG_TAG, "reading headers");
StringBuilder httpString = new StringBuilder();
httpString.append(response.getStatusLine().toString());
httpString.append("\n");
for (Header h : response.getAllHeaders()) {
httpString.append(h.getName()).append(": ").append(h.getValue()).append(
"\n");
}
httpString.append("\n");
Log.d(LOG_TAG, "headers done");
try {
byte[] buffer = httpString.toString().getBytes();
int readBytes = -1;
Log.d(LOG_TAG, "writing to client");
client.getOutputStream().write(buffer, 0, buffer.length);
// Start streaming content.
byte[] buff = new byte[1024 * 50];
while (isRunning && (readBytes = data.read(buff, 0, buff.length)) != -1) {
client.getOutputStream().write(buff, 0, readBytes);
}
} catch (Exception e) {
Log.e("", e.getMessage(), e);
} finally {
if (data != null) {
data.close();
}
client.close();
}
}
private class IcyLineParser extends BasicLineParser {
private static final String ICY_PROTOCOL_NAME = "ICY";
private IcyLineParser() {
super();
}
@Override
public boolean hasProtocolVersion(CharArrayBuffer buffer,
ParserCursor cursor) {
boolean superFound = super.hasProtocolVersion(buffer, cursor);
if (superFound) {
return true;
}
int index = cursor.getPos();
final int protolength = ICY_PROTOCOL_NAME.length();
if (buffer.length() < protolength)
return false; // not long enough for "HTTP/1.1"
if (index < 0) {
// end of line, no tolerance for trailing whitespace
// this works only for single-digit major and minor version
index = buffer.length() - protolength;
} else if (index == 0) {
// beginning of line, tolerate leading whitespace
while ((index < buffer.length()) &&
HTTP.isWhitespace(buffer.charAt(index))) {
index++;
}
} // else within line, don't tolerate whitespace
if (index + protolength > buffer.length())
return false;
return buffer.substring(index, index + protolength).equals(ICY_PROTOCOL_NAME);
}
@Override
public Header parseHeader(CharArrayBuffer buffer) throws ParseException {
return super.parseHeader(buffer);
}
@Override
public ProtocolVersion parseProtocolVersion(CharArrayBuffer buffer,
ParserCursor cursor) throws ParseException {
if (buffer == null) {
throw new IllegalArgumentException("Char array buffer may not be null");
}
if (cursor == null) {
throw new IllegalArgumentException("Parser cursor may not be null");
}
final int protolength = ICY_PROTOCOL_NAME.length();
int indexFrom = cursor.getPos();
int indexTo = cursor.getUpperBound();
skipWhitespace(buffer, cursor);
int i = cursor.getPos();
// long enough for "HTTP/1.1"?
if (i + protolength + 4 > indexTo) {
throw new ParseException
("Not a valid protocol version: " +
buffer.substring(indexFrom, indexTo));
}
// check the protocol name and slash
if (!buffer.substring(i, i + protolength).equals(ICY_PROTOCOL_NAME)) {
return super.parseProtocolVersion(buffer, cursor);
}
cursor.updatePos(i + protolength);
return createProtocolVersion(1, 0);
}
@Override
public RequestLine parseRequestLine(CharArrayBuffer buffer,
ParserCursor cursor) throws ParseException {
return super.parseRequestLine(buffer, cursor);
}
@Override
public StatusLine parseStatusLine(CharArrayBuffer buffer,
ParserCursor cursor) throws ParseException {
StatusLine superLine = super.parseStatusLine(buffer, cursor);
return superLine;
}
}
class MyClientConnection extends DefaultClientConnection {
@Override
protected HttpMessageParser createResponseParser(
final SessionInputBuffer buffer,
final HttpResponseFactory responseFactory, final HttpParams params) {
return new DefaultResponseParser(buffer, new IcyLineParser(),
responseFactory, params);
}
}
class MyClientConnectionOperator extends DefaultClientConnectionOperator {
public MyClientConnectionOperator(final SchemeRegistry sr) {
super(sr);
}
@Override
public OperatedClientConnection createConnection() {
return new MyClientConnection();
}
}
class MyClientConnManager extends SingleClientConnManager {
private MyClientConnManager(HttpParams params, SchemeRegistry schreg) {
super(params, schreg);
}
@Override
protected ClientConnectionOperator createConnectionOperator(
final SchemeRegistry sr) {
return new MyClientConnectionOperator(sr);
}
}
}

[NEWBIE] App is crashing, Please Help....

Code:
package com.example.dolaog;
import android.location.GpsStatus.Listener;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.os.Handler;
public class MainActivity extends Activity implements OnClickListener {
Button b, b2, b3;
View a;
ProgressDialog d;
Handler handler;
Thread t = new Thread() {
public void run() {
// TODO Auto-generated method stub
try {
sleep(5000);
handler.post(new Runnable() {
public void run() {
d.dismiss();
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
protected void onCreate(Bundle savedInstanceState) {
handler = new Handler();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
b3 = (Button) findViewById(R.id.button3);
b2 = (Button) findViewById(R.id.button2);
b.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
}
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.button1:
showDialog(0);
break;
case R.id.button2:
d = ProgressDialog.show(this, "Initialising", " Please wait...",
true);
t.start();
break;
case R.id.button3:
showDialog(1);
d.setProgress(0);
new Thread(new Runnable() {
public void run() {
for (int i = 1; i <= 15; i++) {
try {
// ---simulate doing something lengthy---
Thread.sleep(1000);
// ---update the dialog---
d.incrementProgressBy((int) (100 / 15));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
d.dismiss();
}
}).start();
break;
}
}
protected Dialog onCreateDialog(int g) {
Builder b = new AlertDialog.Builder(this);
switch (g) {
case 0:
b.setIcon(R.drawable.ic_launcher);
b.setTitle("From Crazyandroidgalaxy, please hit me !!");
b.setPositiveButton("asd", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),
"I am Tanmay aka Crazyandroidgalaxy admin!",
Toast.LENGTH_LONG).show();
}
});
return b.create();
case 1:
d.setIcon(R.drawable.ic_launcher);
d.setTitle("Downloading");
d.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
d.setButton(DialogInterface.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
Toast.makeText(getBaseContext(), "OK clicked",
Toast.LENGTH_SHORT).show();
}
});
d.setButton(DialogInterface.BUTTON_NEGATIVE, "cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
Toast.makeText(getBaseContext(), "cancel clicked",
Toast.LENGTH_SHORT).show();
}
});
return d;
}
return null;
}
}
________________
Obviously, the above code is not working. The app is crashing, when i click the b3 button...
Please help me out!
Thanks in advance...
Please read this to help yourself: [GUIDE] Debugging apps
At least read this for posting your problem on XDA: http://forum.xda-developers.com/showpost.php?p=42601921&postcount=9
---------- Post added at 01:24 PM ---------- Previous post was at 12:51 PM ----------
You cannot modify the UI/ dismiss a dialog from another thread.
Use a Handler and its post method.
However, please read the debugging thread. After reading that, you would have easily figured out what is wrong.
nikwen said:
Please read this to help yourself: [GUIDE] Debugging apps
At least read this for posting your problem on XDA: http://forum.xda-developers.com/showpost.php?p=42601921&postcount=9
---------- Post added at 01:24 PM ---------- Previous post was at 12:51 PM ----------
You cannot modify the UI/ dismiss a dialog from another thread.
Use a Handler and its post method.
However, please read the debugging thread. After reading that, you would have easily figured out what is wrong.
Click to expand...
Click to collapse
Oh! thanks. I completely forgot about the last correction you made, in my code

[Q] rmtp / mms player

hi friends
i can't play rtmp or mss protocol in android project (just audio live stream )
my code :
Code:
package sample.media.player;
import java.io.IOException;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
public class SampleMediaPlayerActivity extends Activity implements OnErrorListener, OnPreparedListener {
private MediaPlayer player;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
player.setDataSource("rtmp://199.103.63.202/live&file=irib3"); // rtmp link
player.setOnErrorListener(this);
player.setOnPreparedListener(this);
player.prepareAsync();
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (IllegalStateException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
[user=439709]@override[/user]
public void onDestroy() {
super.onDestroy();
player.release();
player = null;
}
[user=439709]@override[/user]
public void onPrepared(MediaPlayer play) {
play.start();
}
[user=439709]@override[/user]
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
return false;
}
}
please help me / thanks:good:
Is it crashing or does it do nothing? Logcat?
LogCat:
Level : E
PID : 222
Application : Simple.Media.Player
Tag : MediaPlayer
Text : Error(1,-1)
help me plzzzzzzzzzzzz
nobodyyyyyy ????
takname said:
LogCat:
Level : E
PID : 222
Application : Simple.Media.Player
Tag : MediaPlayer
Text : Error(1,-1)
Click to expand...
Click to collapse
There should be more log code which is important. In every case there should be an Exception which is thrown.
I just found this library: http://www.aftek.com/afteklab/aftek-RTMP-library.shtml
Might be helpful.
(Both formats are not natively supported by the Android platform: http://developer.android.com/guide/appendix/media-formats.html)

No Empty constructor ? cant seem to figure out.

so i have been working on an app for a while now but now my code is crashing due to no empty constructor.
but i have no more idea how i should fix this.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Code:
package com.spacewizz.powersavelauncher;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class ChooserAppsSettings extends LinearLayout {
private static final int CAPACITY = 6;
private static final String KEY_LIST[] = { "1", "2", "3", "4", "5", "6"};
private static final String HENABLED_KEY = "com.spacewizz.powersavelauncher.HENABLED";
private static final String KEY_APPNAME_KEY[] = {
"com.spacewizz.powersavelauncher.APP1", "com.spacewizz.powersavelauncher.APP2",
"com.spacewizz.powersavelauncher.APP3", "com.spacewizz.powersavelauncher.APP4",
"com.spacewizz.powersavelauncher.APP5", "com.spacewizz.powersavelauncher.APP6"};
private static final String KEY_INTENTNAME_KEY[] = {
"com.spacewizz.powersavelauncher.INTENT1", "com.spacewizz.powersavelauncher.INTENT2",
"com.spacewizz.powersavelauncher.INTENT3", "com.spacewizz.powersavelauncher.INTENT4",
"com.spacewizz.powersavelauncher.INTENT5", "com.spacewizz.powersavelauncher.INTENT6"};
private static final String KEY_SETTINGS = "com.spacewizz.powersavelauncher.SETTINGS";
private static final String VIEW_MODE_KEY = "com.spacewizz.powersavelauncher.VIEW_MODE_KEY";
private static final String KEY_APPNAME[] = { "ZAPP1", "ZAPP2", "ZAPP3", "ZAPP4", "ZAPP5", "ZAPP6" };
private static final String HORIZONTAL_KEY = "com.spacewizz.powersavelauncher.HORIZONTAL";
private static final String KEY_APPINTENT[] = { "XAPP1", "XAPP2", "XAPP3", "XAPP4", "XAPP5", "XAPP6" };
private static final String KEY_INTENT_ACTION[] = { "IAPP1", "IAPP2",
"IAPP3", "IAPP4", "IAPP5", "IAPP6" };
private ArrayList<String> INSTALLED_PACKAGE = new ArrayList<String>();
private ArrayList<String> APP_NAME = new ArrayList<String>();
private ArrayList<Intent> LAUNCH_ACTIVITY = new ArrayList<Intent>();
private ArrayList<Drawable> APP_ICONS = new ArrayList<Drawable>();
private ArrayList<String> APPS_SHORTCUT = new ArrayList<String>(CAPACITY);
private ArrayAdapter<String> APPS_SHORTCUT_ADAPTER;
private String OPTIONS[] = { "Remove shortcut" };
private String APP_NAMES[] = new String[CAPACITY];
private String OLD_LIST_NAME, NEW_LIST_NAME, INTENT;
private String MODES[] = { "Icon + Label", "Icon only", "Label only",
"Icon + Label (Vertical)" };
Intent mIntent;
boolean horizontal, henabled;
SharedPreferences sp;
ArrayAdapter<String> mSpinnerAdapter;
SharedPreferences.Editor spe;
private Spinner VIEW_MODES;
private ListView APPSLISTVIEW;
private TextView ViewSettingsLabel, AppsListLabel;
private CheckBox HorizontalScroll;
private Context mContext;
int mSpinnerPos;
private LinearLayout THESETTINGS;
private Button mSettings, mDoneSettings;
private ProgressDialog dialog;
private ScrollView mSettingsView;
private Dialog mSettingsDialog;
private WindowManager.LayoutParams WMLP;
public ChooserAppsSettings(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
this.mContext = context;
dialog = new ProgressDialog(mContext);
dialog.setTitle("Please wait...");
dialog.setMessage("Loading installed applications...");
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
henabled = getCBState();
setOrientation(LinearLayout.VERTICAL);
setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
LinearLayout.LayoutParams TVLP = new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
TVLP.gravity = Gravity.CENTER_VERTICAL;
mSpinnerPos = getSpinnerPos();
mSettings = new Button(mContext);
mSettings.setText("Settings");
mSettings.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
mDoneSettings = new Button(mContext);
mDoneSettings.setText("Done!");
mDoneSettings.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
THESETTINGS = new LinearLayout(mContext);
THESETTINGS.setOrientation(LinearLayout.VERTICAL);
THESETTINGS.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
mSettingsView = new ScrollView(mContext);
mSettingsView.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
VIEW_MODES = new Spinner(mContext);
VIEW_MODES.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
mSpinnerAdapter = new ArrayAdapter<String>(mContext,
android.R.layout.simple_spinner_item, MODES);
mSpinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
VIEW_MODES.setAdapter(mSpinnerAdapter);
VIEW_MODES.setSelection(mSpinnerPos);
LinearLayout.LayoutParams ColorLL = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, 50);
ColorLL.bottomMargin = 30;
ColorLL.topMargin = 20;
ColorLL.leftMargin = 50;
ColorLL.rightMargin = 50;
ViewSettingsLabel = new TextView(mContext);
AppsListLabel = new TextView(mContext);
ViewSettingsLabel.setLayoutParams(TVLP);
AppsListLabel.setLayoutParams(TVLP);
ViewSettingsLabel.setText("Display Options");
AppsListLabel.setText("App Shortcuts List: ");
ViewSettingsLabel.setBackgroundResource(android.R.drawable.title_bar);
AppsListLabel.setBackgroundResource(android.R.drawable.title_bar);
ViewSettingsLabel.setGravity(Gravity.CENTER);
HorizontalScroll = new CheckBox(mContext);
HorizontalScroll.setLayoutParams(TVLP);
HorizontalScroll.setText("Horizontal Scroll (Icon only)");
HorizontalScroll.setEnabled(horizontal);
HorizontalScroll.setChecked(henabled);
APPSLISTVIEW = new ListView(mContext);
APPSLISTVIEW.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
addView(APPSLISTVIEW);
mSettingsDialog = new Dialog(mContext);
mSettingsDialog.setTitle("Settings");
mSettingsDialog.requestWindowFeature(Window.FEATURE_LEFT_ICON);
mSettingsDialog.setContentView(mSettingsView);
mSettingsDialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
android.R.drawable.ic_menu_manage);
WMLP = new WindowManager.LayoutParams();
WMLP.copyFrom(mSettingsDialog.getWindow().getAttributes());
WMLP.width = WindowManager.LayoutParams.MATCH_PARENT;
WMLP.height = WindowManager.LayoutParams.WRAP_CONTENT;
for (int i = 1; i <= CAPACITY; i++) {
APPS_SHORTCUT.add("Application " + String.valueOf(i));
}
APPS_SHORTCUT_ADAPTER = new ArrayAdapter<String>(context,
android.R.layout.simple_list_item_1, APPS_SHORTCUT);
dialog.show();
preloadInstalledApplications Preload = new preloadInstalledApplications();
Preload.execute(02, 23, 1997);
setHorizontalScrollListener();
//setViewModeOnItemSelectedListener();
setAppListViewOnClickListener();
setApplistViewOnLongClickListener();
//setmSettingsOnClickListener();
//setmDoneSettingsOnClickListener();
loadList();
refreshList();
}
private boolean getCBState() {
sp = PreferenceManager.getDefaultSharedPreferences(mContext);
return sp.getBoolean(HENABLED_KEY, false);
}
private void saveCBState(boolean state) {
openSPE();
spe.putBoolean(HENABLED_KEY, state);
commitSPE();
}
private boolean getHorizontal() {
sp = PreferenceManager.getDefaultSharedPreferences(mContext);
return sp.getBoolean(HORIZONTAL_KEY, false);
}
private void setHorizontalScrollListener() {
// TODO Auto-generated method stub
HorizontalScroll
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if (HorizontalScroll.isChecked()) {
saveCBState(HorizontalScroll.isChecked());
} else {
saveCBState(HorizontalScroll.isChecked());
}
}
});
}
private void setmDoneSettingsOnClickListener() {
// TODO Auto-generated method stub
mDoneSettings.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mSettingsDialog.isShowing()) {
mSettingsDialog.dismiss();
}
}
});
}
private void setmSettingsOnClickListener() {
// TODO Auto-generated method stub
mSettings.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mSettingsDialog.show();
mSettingsDialog.getWindow().setAttributes(WMLP);
}
});
}
private void setViewModeOnItemSelectedListener() {
// TODO Auto-generated method stub
VIEW_MODES.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
mSpinnerPos = arg2;
int MODE = mSpinnerPos;
VIEW_MODES.setSelection(mSpinnerPos);
saveSpinnerPos(mSpinnerPos);
if (mSpinnerPos == 1) {
horizontal = true;
henabled = HorizontalScroll.isChecked();
if (henabled) {
MODE = 100;
} else {
MODE = mSpinnerPos;
}
} else {
horizontal = false;
henabled = false;
}
sendViewModeSettings(MODE);
HorizontalScroll.setEnabled(horizontal);
openSPE();
spe.putBoolean(HORIZONTAL_KEY, horizontal);
commitSPE();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
VIEW_MODES.setSelection(mSpinnerPos);
}
});
}
private void saveSpinnerPos(int pos) {
sp = PreferenceManager.getDefaultSharedPreferences(getContext());
spe = sp.edit();
spe.putInt(VIEW_MODE_KEY, pos);
spe.commit();
}
private int getSpinnerPos() {
sp = PreferenceManager.getDefaultSharedPreferences(getContext());
return sp.getInt(VIEW_MODE_KEY, 0);
}
private void sendViewModeSettings(int mode) {
mIntent = new Intent();
mIntent.setAction(KEY_SETTINGS);
mIntent.putExtra(VIEW_MODE_KEY, mode);
mContext.sendBroadcast(mIntent);
}
private void setApplistViewOnLongClickListener() {
// TODO Auto-generated method stub
APPSLISTVIEW.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
final int arg2, long arg3) {
// TODO Auto-generated method stub
final ListAdapter OPTIONSMENU = new ArrayAdapter<String>(
mContext, android.R.layout.simple_list_item_1, OPTIONS);
new AlertDialog.Builder(mContext)
.setTitle("Options")
.setIcon(android.R.drawable.ic_dialog_info)
.setAdapter(OPTIONSMENU,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
switch (which) {
case 0:
String NEW_ITEM = "Application "
+ String.valueOf(arg2 + 1)
+ " (Not on SystemUI)";
APPS_SHORTCUT.remove(arg2);
APPS_SHORTCUT.add(arg2, NEW_ITEM);
sendDeleteCommand(arg2);
APP_NAMES[arg2] = APPS_SHORTCUT
.get(arg2);
saveList(arg2);
refreshList();
break;
}
}
}).show();
return false;
}
});
}
private void setAppListViewOnClickListener() {
// TODO Auto-generated method stub
APPSLISTVIEW.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
final int arg2, long arg3) {
// TODO Auto-generated method stub
final ListAdapter ADAPTER = new ArrayAdapter<String>(mContext,
android.R.layout.simple_list_item_1, APP_NAME);
new AlertDialog.Builder(mContext)
.setTitle("Select Application")
.setIcon(android.R.drawable.ic_dialog_alert)
.setAdapter(ADAPTER,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Toast.makeText(
getContext(),
"Application "
+ String.valueOf(arg2 + 1)
+ " selected: "
+ ADAPTER
.getItem(which)
.toString(),
Toast.LENGTH_SHORT).show();
OLD_LIST_NAME = APPS_SHORTCUT.get(arg2);
NEW_LIST_NAME = ADAPTER.getItem(which)
.toString();
if (OLD_LIST_NAME != NEW_LIST_NAME) {
APPS_SHORTCUT.remove(arg2);
String NEW_ITEM = ADAPTER.getItem(
which).toString();
APPS_SHORTCUT.add(arg2, NEW_ITEM);
if (LAUNCH_ACTIVITY.get(which) != null) {
INTENT = INSTALLED_PACKAGE
.get(which);
} else {
INTENT = "null";
}
refreshToBePassed(arg2, NEW_ITEM,
INTENT);
}
saveList(arg2);
refreshList();
}
}).show();
}
});
}
private void refreshList() {
APPS_SHORTCUT_ADAPTER = new ArrayAdapter<String>(mContext,
android.R.layout.simple_list_item_1, APPS_SHORTCUT);
APPSLISTVIEW.setAdapter(APPS_SHORTCUT_ADAPTER);
}
private void refreshToBePassed(int position, String APP, String mINTENT) {
APP_NAMES[position] = APP;
KEY_APPNAME[position] = APPS_SHORTCUT_ADAPTER.getItem(position);
KEY_APPINTENT[position] = mINTENT;
mIntent = new Intent();
mIntent.setAction(KEY_INTENT_ACTION[position]);
mIntent.putExtra(KEY_APPNAME_KEY[position], KEY_APPNAME[position]);
mIntent.putExtra(KEY_INTENTNAME_KEY[position], KEY_APPINTENT[position]);
mContext.sendBroadcast(mIntent);
}
private void saveList(int position) {
sp = PreferenceManager.getDefaultSharedPreferences(getContext());
spe = sp.edit();
spe.putString(KEY_LIST[position], APP_NAMES[position]);
spe.commit();
}
private void loadList() {
// TODO Auto-generated method stub
sp = PreferenceManager.getDefaultSharedPreferences(getContext());
APPS_SHORTCUT.clear();
for (int x = 0; x < CAPACITY; x++) {
APP_NAMES[x] = sp.getString(KEY_LIST[x],
"Application " + String.valueOf((x + 1)));
APPS_SHORTCUT.add(APP_NAMES[x]);
}
}
private void sendDeleteCommand(int position) {
KEY_APPNAME[position] = "DELETE";
KEY_APPINTENT[position] = "DELETE";
mIntent = new Intent();
mIntent.setAction(KEY_INTENT_ACTION[position]);
mIntent.putExtra(KEY_APPNAME_KEY[position], KEY_APPNAME[position]);
mIntent.putExtra(KEY_INTENTNAME_KEY[position], KEY_APPINTENT[position]);
mContext.sendBroadcast(mIntent);
}
private void openSPE() {
sp = PreferenceManager.getDefaultSharedPreferences(mContext);
spe = sp.edit();
}
private void commitSPE() {
spe.commit();
}
private class preloadInstalledApplications extends
AsyncTask<Integer, Void, Void> {
@Override
protected Void doInBackground(Integer... params) {
// TODO Auto-generated method stub
final PackageManager PM = mContext.getPackageManager();
List<ApplicationInfo> PACKAGES = PM
.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo PACKAGE_INFO : PACKAGES) {
if (PM.getLaunchIntentForPackage(PACKAGE_INFO.packageName) != null) {
INSTALLED_PACKAGE.add(PACKAGE_INFO.packageName);
LAUNCH_ACTIVITY
.add(PM.getLaunchIntentForPackage(PACKAGE_INFO.packageName));
APP_ICONS.add(PM.getApplicationIcon(PACKAGE_INFO));
APP_NAME.add(PM.getApplicationLabel(PACKAGE_INFO)
.toString());
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
}
}
}
anyone knows how to fix?
thanks
This' to put it inns nutshell
haaaroldb said:
This' to put it inns nutshell
Click to expand...
Click to collapse
I am sorry i don't understand. can you explain ?
I am not sure, but your class might be missing constructor
more info: http://www.javatpoint.com/constructor
For some reason it says that it needs and Empty constructor.
Type inside ChooserAppSettings class:
Code:
public ChooserAppSettings(){
}
This may fix it. I am not sure though why it needs the empty constructor. What class is your ChooserAppSettings extending or implementing??
Can you show all the logcat messages?
@mmdeveloper said:
For some reason it says that it needs and Empty constructor.
Type inside ChooserAppSettings class:
Code:
public ChooserAppSettings(){
}
This may fix it. I am not sure though why it needs the empty constructor. What class is your ChooserAppSettings extending or implementing??
Can you show all the logcat messages?
Click to expand...
Click to collapse
Linearlayout.
Tried the above but didnt worked
Try adding these:
Code:
public ChooserAppSettings(Context context){
super(context);
}
public ChooserAppSettings(Context context, AttributeSet attrs, int defStyle){
super(context, attrs, defStyle);
}
Issue solved.
was a stupid fault of myself xD
typo at launching the java file

Categories

Resources