Android Asynctask with PHP not working - java

I have been stuck for weeks.....for this problem
I am using AsynTask to send data to php and recieve a name to print
but it showed this error anyone to help ??
12-29 19:34:12.623: D/dalvikvm(799): GC_CONCURRENT freed 188K, 11% free 2629K/2948K, paused 25ms+61ms, total 218ms
12-29 19:34:13.282: D/gralloc_goldfish(799): Emulator without GPU emulation detected.
12-29 19:34:42.132: W/System.err(799): java.lang.NullPointerException
12-29 19:34:42.164: W/System.err(799): at android.app.Activity.findViewById(Activity.java:1839)
12-29 19:34:42.164: W/System.err(799): at com.example.myweb.MainActivity.afterEffect(MainActivity.java:64)
12-29 19:34:42.164: W/System.err(799): at com.example.myweb.toPHP.onPreExecute(toPHP.java:47)
12-29 19:34:42.164: W/System.err(799): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
12-29 19:34:42.164: W/System.err(799): at android.os.AsyncTask.execute(AsyncTask.java:534)
12-29 19:34:42.164: W/System.err(799): at com.example.myweb.MainActivity$1.onClick(MainActivity.java:54)
12-29 19:34:42.172: W/System.err(799): at android.view.View.performClick(View.java:4204)
12-29 19:34:42.172: W/System.err(799): at android.view.View$PerformClick.run(View.java:17355)
12-29 19:34:42.172: W/System.err(799): at android.os.Handler.handleCallback(Handler.java:725)
12-29 19:34:42.185: W/System.err(799): at android.os.Handler.dispatchMessage(Handler.java:92)
12-29 19:34:42.185: W/System.err(799): at android.os.Looper.loop(Looper.java:137)
12-29 19:34:42.192: W/System.err(799): at android.app.ActivityThread.main(ActivityThread.java:5041)
12-29 19:34:42.212: W/System.err(799): at java.lang.reflect.Method.invokeNative(Native Method)
12-29 19:34:42.212: W/System.err(799): at java.lang.reflect.Method.invoke(Method.java:511)
12-29 19:34:42.212: W/System.err(799): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-29 19:34:42.222: W/System.err(799): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-29 19:34:42.222: W/System.err(799): at dalvik.system.NativeStart.main(Native Method)
JSONParser.java
package com.example.myweb;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
toPHP.java
package com.example.myweb;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class toPHP extends AsyncTask {
MainActivity main = new MainActivity();
private JSONParser jsonParser;
String email,password;
EditText emailBox;
EditText passwordBox;
#Override
protected void onPreExecute() {
super.onPreExecute();
main.afterEffect("sending...");
emailBox = (EditText) main.findViewById(R.id.email);
passwordBox = (EditText) main.findViewById(R.id.password);
email = emailBox.getText().toString();
password = passwordBox.getText().toString();
}
protected JSONObject doInBackground(String... args) {
toPHP userFunction = new toPHP();
JSONObject json = null;
try {
json = userFunction.getUserLoggedIn(email, password);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
public JSONObject getUserLoggedIn(String email,String password) throws ClientProtocolException, IOException, JSONException{
JSONObject json = null;
/*
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://localhost/testand.php");
*/
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("email", email));
pairs.add(new BasicNameValuePair("password", password));
//post.setEntity(new UrlEncodedFormEntity(pairs));
//HttpResponse response = client.execute(post);
//HttpEntity resEntity = response.getEntity();
//if (resEntity != null) {
//String responseStr = EntityUtils.toString(resEntity).trim();
json = jsonParser.getJSONFromUrl("http://localhost/testand.php", pairs);
//}
return json;
}
protected void onPostExecute(JSONObject json) throws JSONException {
String myName = json.getString("name");
String str = myName + ", Welcome to Socionet. :) ";
main.afterEffect(str);
}
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
return null;
}
}
MainActivity.java
package com.example.myweb;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends Activity {
Button button;
EditText emailBox;
EditText passwordBox;
String emailId;
String passwordId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.login1);
emailBox = (EditText)findViewById(R.id.email);
passwordBox = (EditText)findViewById(R.id.password);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
new toPHP().execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void afterEffect(String str){
TextView textV1 = (TextView)findViewById(R.id.textV1);
textV1.setText(str);
}
}
UPDATE 1
new errors after #hasan83 's fixes
12-29 21:38:27.588: W/dalvikvm(1283): threadid=11: thread exiting with uncaught exception (group=0x40a71930)
12-29 21:38:27.748: E/AndroidRuntime(1283): FATAL EXCEPTION: AsyncTask #1
12-29 21:38:27.748: E/AndroidRuntime(1283): java.lang.RuntimeException: An error occured while executing doInBackground()
12-29 21:38:27.748: E/AndroidRuntime(1283): at android.os.AsyncTask$3.done(AsyncTask.java:299)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
12-29 21:38:27.748: E/AndroidRuntime(1283): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.lang.Thread.run(Thread.java:856)
12-29 21:38:27.748: E/AndroidRuntime(1283): Caused by: java.lang.NullPointerException
12-29 21:38:27.748: E/AndroidRuntime(1283): at com.example.myweb.toPHP.getUserLoggedIn(toPHP.java:99)
12-29 21:38:27.748: E/AndroidRuntime(1283): at com.example.myweb.toPHP.doInBackground(toPHP.java:67)
12-29 21:38:27.748: E/AndroidRuntime(1283): at com.example.myweb.toPHP.doInBackground(toPHP.java:1)
12-29 21:38:27.748: E/AndroidRuntime(1283): at android.os.AsyncTask$2.call(AsyncTask.java:287)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
12-29 21:38:27.748: E/AndroidRuntime(1283): ... 4 more

You can't create a new MainActivity in your AsyncTask. When you are in your MainActivity, pass the activity to the constructor of the AsyncTask. You will be able to get and update your views in the onPreExecute() method.
public class toPHP extends AsyncTask {
public toPHP(Activity activity) {
}
}
And in your activity:
new toPHP(MainActivity.this).execute();

Add a constructor so that you can pass in the current MainActivity to your AsyncTask
public class toPHP extends AsyncTask {
final MainActivity main;
public toPHP(MainActivity main) {
this.main = main;
}
...
then call like so
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
new toPHP(MainActivity.this).execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}

Error says it's unable to find your TextView with id of R.id.textV1. Make sure it's available in the content view :R.layout.activity_main
But the main problem is why are you doing this MainActivity main = new MainActivity(), in your AsyncTask. It should be passed by reference from the actual Activity.

Points:
I don't see #Override keyword before onPostExecute and doInBackground methods.
Move the code in onPreExecute to doInBackground.
Send the main activity as a parameter for the AsynkTask execute method.
Catch the activity on the do doInBackground.
dont' declare an object of toPhp just call getUserLoggedIn. you are in the same class.
That's it.
new toPHP().execute(MainActivity.this);
#Override
protected Object doInBackground(Object... args) {
main = (MainActivity) args[0];
main.afterEffect("sending...");
emailBox = (EditText) main.findViewById(R.id.email);
passwordBox = (EditText) main.findViewById(R.id.password);
email = emailBox.getText().toString();
password = passwordBox.getText().toString();
..
}

Related

Sending String to PHP file via android application

I am developing an app which includes the upload of all contacts to my server what i am doing is displaying all the contacts and sending them to my server as a string.Here is my code:
package com.example.core.freemusic;
import java.io.IOException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
public class MainActivity extends Activity {
LinearLayout ll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ll = (LinearLayout) findViewById(R.id.LinearLayout1);
LoadContactsAyscn lca = new LoadContactsAyscn();
lca.execute();
}
class LoadContactsAyscn extends AsyncTask < Void, Void, String > {
ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = ProgressDialog.show(MainActivity.this, "Please Wait","");
}
#Override
protected String doInBackground(Void...params) {
String contacts = "";
Cursor c = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (c.moveToNext()) {
String contactName = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phNumber = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts += contactName + ":" + phNumber + "\n";
}
c.close();
return contacts;
}
#Override
protected void onPostExecute(String contacts) {
super.onPostExecute(contacts);
pd.cancel();
TextView a = (TextView) findViewById(R.id.textView);
a.setText(contacts);
doInBackground(contacts);
}
protected void doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.2.30/b.php?username="+params);
try {
httpclient.execute(httppost);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Actually the code shows no error but on running it in emulator it crashes.
the error on logcat is:
05-24 14:00:57.989 2488-2500/com.example.core.freemusic W/art﹕ Suspending all threads took: 5.841ms
05-24 14:00:57.992 2488-2500/com.example.core.freemusic I/art﹕ Background partial concurrent mark sweep GC freed 1888(115KB) AllocSpace objects, 0(0B) LOS objects, 50% free, 502KB/1014KB, paused 6.923ms total 95.188ms
05-24 14:00:58.073 2488-2488/com.example.core.freemusic I/Choreographer﹕ Skipped 37 frames! The application may be doing too much work on its main thread.
05-24 14:00:58.080 2488-2488/com.example.core.freemusic D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
05-24 14:00:58.102 2488-2488/com.example.core.freemusic D/AndroidRuntime﹕ Shutting down VM
05-24 14:00:58.103 2488-2488/com.example.core.freemusic E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.core.freemusic, PID: 2488
java.lang.IllegalArgumentException: Illegal character in query at index 43: http://192.168.2.30/b.php?username=Sd:(546) 456-4826
Sad:486-44
at java.net.URI.create(URI.java:730)
at org.apache.http.client.methods.HttpPost.<init>(HttpPost.java:79)
at com.example.core.freemusic.MainActivity$LoadContactsAyscn.onPostExecute(MainActivity.java:64)
at com.example.core.freemusic.MainActivity$LoadContactsAyscn.onPostExecute(MainActivity.java:38)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
05-24 14:01:01.259 2488-2488/com.example.core.freemusic I/Process﹕ Sending signal. PID: 2488 SIG: 9
05-24 15:24:12.790 2685-2685/com.example.core.freemusic D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
As error code state, you need to encode the query:
HttpPost httppost = new HttpPost("http://192.168.2.30/b.php?username="+params);
need to changed into:
HttpPost httppost = new HttpPost("http://192.168.2.30/b.php?username="+java.net.URLEncoder.encode(params[0], "UTF-8"));

Choose activity dynamically during splashscreen

I'm doing a small project, and today I had to make a conditional validation in splashscreen. The project was practically finalized when we decided to do this validation in splashscreen.
Modified my class and was working ok, but I had to include the time for the splash disappears (variable SPLASH_TIME_OUT) and started giving an error that I do not understand.
My splashscreen clas (now) is:
package com.clubee.vote;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Splashscreen extends Activity {
// Splash screen timer
private static String url_Pesquisa_voto = "http://dev.clubee.com.br/dbvote/PesquisaVoto.php";
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String TAG_SUCCESS = "success";
public String retrieveMacAddress(Context context) {
WifiManager wfman = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String macAddress = wfman.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Dispositivo sem endereço mac address ou wi-fi desabilitado";
}
return macAddress;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new PesquisaVoto().execute();
}
class PesquisaVoto extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Splashscreen.this);
pDialog.setMessage("Pesquisando Voto..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
int SPLASH_TIME_OUT = 2000;
WifiManager wfman = (WifiManager) getSystemService(Context.WIFI_SERVICE);
String macAddress = wfman.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Dispositivo sem endereço mac";
}
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("macAddress", macAddress));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_Pesquisa_voto, "GET", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
new Handler().postDelayed(new Runnable() {
public void run() {
Intent i = new Intent(Splashscreen.this, ResultadoFalho.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
} else {
new Handler().postDelayed(new Runnable() {
public void run() {
Intent i = new Intent(Splashscreen.this, MainActivity.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
}
The error I am getting is:
03-03 17:38:49.882 10432-10450/com.clubee.vote D/Create Response﹕ {"voto":[{"count":"1"}],"success":1}
03-03 17:38:49.882 10432-10450/com.clubee.vote W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x4164dd88)
03-03 17:38:49.892 10432-10450/com.clubee.vote E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.clubee.vote, PID: 10432
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done
Anyone knows what I did wrong? Is it possivel to implement the Runnable inside the IF statement? If I do not put the timeout variable, everything is right.
UPDATE THE LOG WITH ERROR
03-03 22:01:50.016 18731-18746/com.clubee.vote W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x4164dd88)
03-03 22:01:50.026 18731-18746/com.clubee.vote E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.clubee.vote, PID: 18731
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.(Handler.java:200)
at android.os.Handler.(Handler.java:114)
at com.clubee.vote.Splashscreen$PesquisaVoto.doInBackground(Splashscreen.java:87)
at com.clubee.vote.Splashscreen$PesquisaVoto.doInBackground(Splashscreen.java:48)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
03-03 22:01:50.697 18731-18731/com.clubee.vote E/WindowManager﹕ android.view.WindowLeaked: Activity com.clubee.vote.Splashscreen has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{44aa2458 V.E..... R......D 0,0-681,345} that was originally added here
at android.view.ViewRootImpl.(ViewRootImpl.java:350)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:294)
at com.clubee.vote.Splashscreen$PesquisaVoto.onPreExecute(Splashscreen.java:58)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.clubee.vote.Splashscreen.onCreate(Splashscreen.java:44)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2201)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:212)
at android.app.ActivityThread.main(ActivityThread.java:5135)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
at dalvik.system.NativeStart.main(Native Method)
03-03 22:01:52.529 18731-18746/com.clubee.vote I/Process﹕ Sending signal. PID: 18731 SIG: 9
Tks in advance for answers and comments. I corrected my code, re-wrote and re-structured it, became easier to see where the mistakes were.
below, I leave the code that is working for future research. thank you very much
package com.clubee.vote;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Splashscreen extends Activity {
// Splash screen timer
private static String url_Pesquisa_voto = "http://dev.clubee.com.br/dbvote/PesquisaVoto.php";
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String TAG_SUCCESS = "success";
private static int SPLASH_TIME_OUT = 2000;
public String retrieveMacAddress(Context context) {
WifiManager wfman = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String macAddress = wfman.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Dispositivo sem endereço mac address ou wi-fi desabilitado";
}
return macAddress;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
new PesquisaVoto().execute();
}
}, SPLASH_TIME_OUT);
}
class PesquisaVoto extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Splashscreen.this);
pDialog.setMessage("Pesquisando Voto..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
WifiManager wfman = (WifiManager) getSystemService(Context.WIFI_SERVICE);
String macAddress = wfman.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Dispositivo sem endereço mac";
}
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("macAddress", macAddress));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_Pesquisa_voto, "GET", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Intent i = new Intent(Splashscreen.this, ResultadoFalho.class);
startActivity(i);
}
else {
Intent i = new Intent(Splashscreen.this, MainActivity.class);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
}
I cannot clearly see what is wrong based on the Logs you provided but there is something wrong with your structure.
You are starting an Activity within doInBackground Process and then dismissing the Progress Dialog which belongs to the Activity that you just finished.
Try to pass a parameter to the onPostExecute and then finish your Activity there.
And post some more details from your Log to make it clear. There has to be some more logs indicating what went wrong.

How to fix application has stopped in android app when clicking another button inside main activity?

I have an app that when logged in by user the user redirects to main activity which had his personal details displayed and had two buttons to click: dashboard button redirected to his dashboard manager settings and a button log out. When logged in all is working fine showing his personal details and when I clicked dashboard button for his dashboard settings the app is unfortunately stopped. It said errors in my log cat which I can't fix with my own. I am new to Android. I searched and tried threads here in SO that has same problems with me but still can not be solved. Anybody with a great heart can help me to solve this? It's been quiet a week I'm stuck on this.
note* my dashboard button is calling another layout that contains two buttons
This is my main activity java :
package com.myapp;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import library.JSONParser;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ProfileView extends Activity implements OnClickListener{
private Button bLogout, backdashboard;
private TextView tvusername, tvfullname;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// Profile json object
JSONArray user;
JSONObject display;
//String name for my sharedpref extras
String ngalan;
// Profile JSON url
private static final String PROFILE_URL = "http://10.0.2.2/webservice/profile.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
//setup textview
tvusername=(TextView)(findViewById(R.id.tvusernamedisplay));
tvfullname=(TextView)(findViewById(R.id.tvfullname));
//settup buttons
backdashboard=(Button)(findViewById(R.id.backdashboard));
bLogout=(Button)(findViewById(R.id.blogout));
//button listener
backdashboard.setOnClickListener(this);
bLogout.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
if (extras.containsKey("username")) {
ngalan = extras.getString("username");
// Loading Profile in Background Thread
new LoadProfile().execute();
}
}
#Override
public void onClick(View args) {
// TODO Auto-generated method stub
switch (args.getId()) {
case R.id.backdashboard:
Intent r = new Intent(this, Dashboard.class);
startActivity(r);
finish();
break;
case R.id.blogout:
new AlertDialog.Builder(this)
.setTitle("Logout")
.setMessage("Would you like to logout?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// logout
Intent myIntent = new Intent(ProfileView.this, LoginActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);// clear back stack
startActivity(myIntent);
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// user doesn't want to logout
}
})
.show();
default:
break;
}
}
class LoadProfile extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ProfileView.this);
pDialog.setMessage("Loading Profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Profile JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
String json = null;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", ngalan));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(PROFILE_URL);
httppost.setEntity(new UrlEncodedFormEntity(params));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
json = EntityUtils.toString(resEntity);
Log.i("Profile JSON: ", json.toString());
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPostExecute(String json) {
super.onPostExecute(json);
// dismiss the dialog after getting all products
pDialog.dismiss();
try
{
display = new JSONObject(json);
JSONArray user = display.getJSONArray("user");
JSONObject jb= user.getJSONObject(0);
String idnum = jb.getString("username");
String fulname = jb.getString("lastname");
// displaying all data in textview
tvusername.setText(idnum );
tvfullname.setText(fulname);
}catch(Exception e)
{
e.printStackTrace();
}
}
}
}
This is my Dashboard activity java another activity calls when dashboard button is clicked...
package com.myapp;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Dashboard extends Activity implements OnClickListener{
private Button view, manage, logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
initialise();
}
private void initialise() {
// TODO Auto-generated method stub
//settup buttons
manage=(Button)(findViewById(R.id.bManage));
view=(Button)(findViewById(R.id.bView));
logout=(Button)(findViewById(R.id.blogout));
//button listener
manage.setOnClickListener(this);
view.setOnClickListener(this);
logout.setOnClickListener(this);
}
#Override
public void onClick(View item) {
// TODO Auto-generated method stub
switch (item.getId()) {
case R.id.bManage:
Intent r = new Intent(this, Manage.class);
startActivity(r);
finish();
break;
case R.id.bView:
Intent l = new Intent(this, View.class);
startActivity(l);
finish();
break;
case R.id.blogout:
new AlertDialog.Builder(this)
.setTitle("Logout")
.setMessage("Would you like to logout?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// logout
Intent myIntent = new Intent(Dashboard.this, LoginActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);// clear back stack
startActivity(myIntent);
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// user doesn't want to logout
}
})
.show();
default:
break;
}
}
}
This is my log cat error message"
08-23 18:59:36.949: E/AndroidRuntime(900): FATAL EXCEPTION: main
08-23 18:59:36.949: E/AndroidRuntime(900): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp/com.myapp.Dashboard}: java.lang.NullPointerException
Please help me guys :(
This is the full logcat message:
Unable to start activity ComponentInfo{com.myapp/com.myapp.Dashboard}: java.lang.NullPointerException
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.os.Handler.dispatchMessage(Handler.java:99)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.os.Looper.loop(Looper.java:137)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread.main(ActivityThread.java:5039)
08-23 18:59:36.949: E/AndroidRuntime(900): at java.lang.reflect.Method.invokeNative(Native Method)
08-23 18:59:36.949: E/AndroidRuntime(900): at java.lang.reflect.Method.invoke(Method.java:511)
08-23 18:59:36.949: E/AndroidRuntime(900): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-23 18:59:36.949: E/AndroidRuntime(900): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-23 18:59:36.949: E/AndroidRuntime(900): at dalvik.system.NativeStart.main(Native Method)
08-23 18:59:36.949: E/AndroidRuntime(900): Caused by: java.lang.NullPointerException
08-23 18:59:36.949: E/AndroidRuntime(900): at com.myapp.Dashboard.onCreate(Dashboard.java:27)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.Activity.performCreate(Activity.java:5104)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
08-23 18:59:36.949: E/AndroidRuntime(900): ... 11 more
I guess that NPE occurs in this line: grade.setOnClickListener(this);
You don't initialize this variable anywhere.

Android VerifyError crash using jackson parser

Here is my log cat. Unfortunately I am not a pro in reading errors from logcat so please help me :)
05-30 12:12:16.510: I/System.out(838): We made it this far 1
05-30 12:12:17.230: I/System.out(838): We made it this far 2
05-30 12:12:17.240: W/dalvikvm(838): VFY: unable to resolve exception class 748 (Lcom/fasterxml/jackson/core/JsonParseException;)
05-30 12:12:17.240: W/dalvikvm(838): VFY: unable to find exception handler at addr 0x2a
05-30 12:12:17.240: W/dalvikvm(838): VFY: rejected Lcom/example/bitmapdisplay/MainActivity$URLArray;.doInBackground ([Ljava/lang/Void;)Ljava/lang/Void;
05-30 12:12:17.240: W/dalvikvm(838): VFY: rejecting opcode 0x0d at 0x002a
05-30 12:12:17.250: W/dalvikvm(838): VFY: rejected Lcom/example/bitmapdisplay/MainActivity$URLArray;.doInBackground ([Ljava/lang/Void;)Ljava/lang/Void;
05-30 12:12:17.250: W/dalvikvm(838): Verifier rejected class Lcom/example/bitmapdisplay/MainActivity$URLArray;
05-30 12:12:17.250: D/AndroidRuntime(838): Shutting down VM
05-30 12:12:17.250: W/dalvikvm(838): threadid=1: thread exiting with uncaught exception (group=0xb1adaba8)
05-30 12:12:17.270: E/AndroidRuntime(838): FATAL EXCEPTION: main
05-30 12:12:17.270: E/AndroidRuntime(838): Process: com.example.bitmapdisplay, PID: 838
05-30 12:12:17.270: E/AndroidRuntime(838): java.lang.VerifyError: com/example/bitmapdisplay/MainActivity$URLArray
05-30 12:12:17.270: E/AndroidRuntime(838): at com.example.bitmapdisplay.MainActivity.onCreate(MainActivity.java:72)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.Activity.performCreate(Activity.java:5231)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.os.Handler.dispatchMessage(Handler.java:102)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.os.Looper.loop(Looper.java:136)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-30 12:12:17.270: E/AndroidRuntime(838): at java.lang.reflect.Method.invokeNative(Native Method)
05-30 12:12:17.270: E/AndroidRuntime(838): at java.lang.reflect.Method.invoke(Method.java:515)
05-30 12:12:17.270: E/AndroidRuntime(838): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-30 12:12:17.270: E/AndroidRuntime(838): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-30 12:12:17.270: E/AndroidRuntime(838): at dalvik.system.NativeStart.main(Native Method)
05-30 12:12:30.390: I/Process(838): Sending signal. PID: 838 SIG: 9
Here is the logcat code and here is my Java code. It seems like the problems are coming from the thread URLArray because, as seen in the logcat, the system doesn't even print the third "we made it this far":
package com.example.bitmapdisplay;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import com.fasterxml.jackson.core.JsonParseException;
import android.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class MainActivity extends Activity {
/**
* Bitmap items na dimage displaying
*/
Bitmap image;
BitmapDrawable bd;
ImageView temp;
ProgressDialog pd;
/**
* JSON URL
*/
URL url;
/**
* Data from JSON file
*/
ArrayList<String> urls;
ArrayList<ImageView> images;
JsonParsing obj;
String json_link_str = "http://api.tumblr.com/v2/blog/humansofnewyork.com/posts?api_key=7ag2CJXOuxuW3vlVS5wQG6pYA6a2ZQcSCjzZsAp2pDbVwf3xEk&notes_info=true&filter=text";
int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println(" We made it this far 1");
super.onCreate(savedInstanceState);
setContentView(com.example.bitmapdisplay.R.layout.image_container);
counter = 0;
images = new ArrayList<ImageView>();
urls = new ArrayList<String>();
System.out.println(" We made it this far 2");
new URLArray().execute();
}
/**
* Fills the ListView
*/
private void fillGridView() {
ArrayAdapter<ImageView> adapter = new ArrayAdapter<ImageView>(this, com.example.bitmapdisplay.R.layout.image_container,images);
GridView grid = (GridView) findViewById(com.example.bitmapdisplay.R.id.gvImages);
grid.setAdapter(adapter);
}
public class URLArray extends AsyncTask<Void, Void, Void > {
public URLArray() {
}
#Override
protected Void doInBackground(Void...params ) {
try {
System.out.println(" We made it this far 3");
URL json_link = new URL(json_link_str);
JsonParsing parse_images = new JsonParsing(json_link);
try {
parse_images.parseFile(3, urls);
System.out.println(" We made it this far 4");
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
obj = parse_images;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void arg) {
super.onPreExecute();
System.out.println(" We made it this far 5");
urls = obj.getURLs();
new TheTask().execute();
}
}
class TheTask extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params) {
System.out.println(" We made it this far 6");
pd = new ProgressDialog(MainActivity .this);
pd.show();
System.out.println(" We made it this far 7");
try
{
int counter = 0;
for (ImageView temp : images) {
image = downloadBitmap(urls.get(counter));
temp.setImageBitmap(image);
images.add(temp);
counter++;
}
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
System.out.println(" We made it this far 8");
super.onPostExecute(result);
pd.dismiss();
if(image!=null)
{
fillGridView();
}
}
}
private Bitmap downloadBitmap(String url) {
// initilize the default HTTP client object
final DefaultHttpClient client = new DefaultHttpClient();
//forming a HttoGet request
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
//check 200 OK for success
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode +
" while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
// getting contents from the stream
inputStream = entity.getContent();
// decoding stream data back into image Bitmap that android understands
image = BitmapFactory.decodeStream(inputStream);
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// You Could provide a more explicit error message for IOException
getRequest.abort();
Log.e("ImageDownloader", "Something went wrong while" +
" retrieving bitmap from " + url + e.toString());
}
return image;
}
}
The key problem is here
05-30 12:12:17.240: W/dalvikvm(838): VFY: unable to resolve exception class 748 (Lcom/fasterxml/jackson/core/JsonParseException;)
05-30 12:12:17.240: W/dalvikvm(838): VFY: unable to find exception handler at addr 0x2a
05-30 12:12:17.240: W/dalvikvm(838): VFY: rejected Lcom/example/bitmapdisplay/MainActivity$URLArray;.doInBackground ([Ljava/lang/Void;)Ljava/lang/Void;
05-30 12:12:17.240: W/dalvikvm(838): VFY: rejecting opcode 0x0d at 0x002a
05-30 12:12:17.250: W/dalvikvm(838): VFY: rejected Lcom/example/bitmapdisplay/MainActivity$URLArray;.doInBackground ([Ljava/lang/Void;)Ljava/lang/Void;
05-30 12:12:17.250: W/dalvikvm(838): Verifier rejected class Lcom/example/bitmapdisplay/MainActivity$URLArray;
and it all goes downhill from there.
Looks like JsonParseException (and possibly other classes from Jackson) are not being included in your APK. This could happen if they're not being exported by Eclipse.
Instead of adding it as an external library, just place jackson-core-x.x.x.jar in the libs folder of your Android project and it should be enough to ensure this.

Send a string to a servlet from android

I am trying to send a string from a android application to a servlet and then retrieve that string to my android application ,but when i try to invoke the servlet it force close on me
and i dont know why (im very new to android and this is a practice exercise for me)
here is my android simple app:
ANDROID
package com.theopentutorials.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class HttpGetServletActivity extends Activity implements OnClickListener {
Button button;
TextView outputText;
public static String request = "kjo ishte e gjitha";
public static final String URL = ("http://10.0.2.2:8080/HttpGetServlet/HelloWorldServlet?param1=" + request);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewsById();
button.setOnClickListener(this);
}
private void findViewsById() {
button = (Button) findViewById(R.id.button);
outputText = (TextView) findViewById(R.id.outputTxt);
}
public void onClick(View view) {
GetXMLTask task = new GetXMLTask();
task.execute(new String[] { URL });
}
private class GetXMLTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String output = null;
for (String url : urls) {
output = getOutputFromUrl(url);
}
return output;
}
private String getOutputFromUrl(String url) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = getHttpConnection(url);
BufferedReader buffer = new BufferedReader(
new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
} catch (IOException e1) {
e1.printStackTrace();
}
return output.toString();
}
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
#Override
protected void onPostExecute(String output) {
outputText.setText(output);
}
}
}
and here is my simple servlet
SERVLET
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/HelloWorldServlet")
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HelloWorldServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String par1 = request.getParameter("param1");
PrintWriter out = response.getWriter();
out.println(par1);
}
}
And the logcat log error says
01-10 13:36:50.014: E/AndroidRuntime(1187): FATAL EXCEPTION: AsyncTask #1
01-10 13:36:50.014: E/AndroidRuntime(1187): java.lang.RuntimeException: An error occured while executing doInBackground()
01-10 13:36:50.014: E/AndroidRuntime(1187): at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
01-10 13:36:50.014: E/AndroidRuntime(1187): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.lang.Thread.run(Thread.java:856)
01-10 13:36:50.014: E/AndroidRuntime(1187): Caused by: java.lang.NullPointerException: lock == null
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.io.Reader.<init>(Reader.java:64)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.io.InputStreamReader.<init>(InputStreamReader.java:122)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.io.InputStreamReader.<init>(InputStreamReader.java:59)
01-10 13:36:50.014: E/AndroidRuntime(1187): at com.theopentutorials.android.HttpGetServletActivity$GetXMLTask.getOutputFromUrl(HttpGetServletActivity.java:64)
01-10 13:36:50.014: E/AndroidRuntime(1187): at com.theopentutorials.android.HttpGetServletActivity$GetXMLTask.doInBackground(HttpGetServletActivity.java:54)
01-10 13:36:50.014: E/AndroidRuntime(1187): at com.theopentutorials.android.HttpGetServletActivity$GetXMLTask.doInBackground(HttpGetServletActivity.java:1)
01-10 13:36:50.014: E/AndroidRuntime(1187): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
01-10 13:36:50.014: E/AndroidRuntime(1187): ... 4 more
doest somebody have any idea ?
Thank you for your help in advance !
Have a nice day!
You need to add the internet access permission
<uses-permission android:name="android.permission.INTERNET"/>
I found that you should use the URLEncoder to encode the url because your url contains spaces. Please check http://developer.android.com/reference/java/net/URLEncoder.html
You have forgot to set param1 from your android app.
connection.setRequestProperty("param1", "Your String Value");
then you will get the value back as response from Servlet.

Categories

Resources