I have the following code.
I want to post on the first time the user press a button that the data will be send to httpclient and will return data. This works fine (Button 1). When a user press button 1 it will give the right results.
Then I want to post a second time with different data to the httpclient. When a user press button 2. The data will be send to the function but the logs (see code) returns in the exceptions every time NULL. So I think it will not send to httpclient and will not fill the httppost with the data I want to send.
My question is, what do I wrong or do I forget?
Do I need to create a second httpclient handler?
Do I need to create a second httppost handler?
Please help.
Thank you.
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import info.androidhive.customlistviewvolley.util.MyHttpClient;
public class Login extends Activity {
HttpPost httppost;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
ProgressDialog offlineDialog = null;
String logged, token, valid;
String expired = "expired";
String status, responseContent = "0";
String msg = "";
public void onCreate(Bundle savedInstanceState) {
httpclient=new MyHttpClient(getApplicationContext());
httppost= new HttpPost("https://www.test.com/json/index.php");
b = (Button)findViewById(R.id.buttonLogin);
c = (Button)findViewById(R.id.shareData);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(Login.this, "","Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
String username = 'abc';
String password = 'xxx';
String token = '12321abcksadkm';
c.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
offlineDialog = ProgressDialog.show(Login.this, "", "Share content...", true);
new Thread(new Runnable() {
public void run() {
// This will be executed but will give NULL and offcourse no results
share.connectDP(username,password,"share","18228",token);
}
}).start();
}
});
}
void login(){
try{
final byte[] SALT;
Random random = new Random();
random.setSeed(System.currentTimeMillis());
byte[] buf = new byte[20];
random.nextBytes(buf);
SALT = buf;
nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("token",SALT.toString().trim()));
Log.i("Salt", "Key =" + SALT.toString().trim());
Log.i("test", "test" + nameValuePairs);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
String responseContent = EntityUtils.toString(response.getEntity());
//Log.d("Response", responseContent );
JSONObject jsonObject = new JSONObject(responseContent);
JSONArray jArray = jsonObject.getJSONArray("result");
for (int i = 0; i < jArray.length(); i++) {
try {
JSONObject json_data = jArray.getJSONObject(i);
logged = json_data.getString("status"); // obtain status
token = json_data.getString("token"); // obtain token
valid = json_data.getString("valid"); // obtain validation period
expired = "no";
Log.i("Logged JSON", "Result?" + json_data.getString("status"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void connectDP(String username, String password, String action, String id, String token){
// This is passed, it returns the data = :)
Log.i("connect", "username" + username);
Log.i("connect", "password" + password);
Log.i("connect", "action" + action);
Log.i("connect", "id" + id);
Log.i("connect", "token" + token);
try{
final byte[] SALT;
Random random = new Random();
random.setSeed(System.currentTimeMillis());
byte[] buf = new byte[20];
random.nextBytes(buf);
SALT = buf;
nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("username",username.toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password",password.toString().trim()));
nameValuePairs.add(new BasicNameValuePair("token",SALT.toString().trim()));
Log.i("Salt", "Key =" + SALT.toString().trim());
Log.i("test", "test" + nameValuePairs);
//// <!---- After here it will break, but no any error or warning -----!>
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
String responseContent = EntityUtils.toString(response.getEntity());
//Log.d("Response", responseContent );
JSONObject jsonObject = new JSONObject(responseContent);
JSONArray jArray = jsonObject.getJSONArray("result");
for (int i = 0; i < jArray.length(); i++) {
try {
JSONObject json_data = jArray.getJSONObject(i);
logged = json_data.getString("status"); // obtain status
token = json_data.getString("token"); // obtain token
valid = json_data.getString("valid"); // obtain validation period
expired = "no";
Log.i("Logged JSON", "Result?" + json_data.getString("status"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
}
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/connect﹕ usernameabc
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/connect﹕ passwordxxx
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/connect﹕ actionshare
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/connect﹕ id18228
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/connect﹕ token12321abcksadkm
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/test 1﹕ test[username=abc, password=xxx, requestAction=share, requestFile=18228, load_remote_token=12321abcksadkm
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 1a﹕ testnull
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 2﹕ testnull
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 2a﹕ testnull
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 3﹕ testnull
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 4﹕ testnull
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 4a﹕ testnull
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 5﹕ 0
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/System.out﹕ Exception : Value 0 of type java.lang.Integer cannot be converted to JSONObject
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/Log share﹕ [ 04-03 19:33:25.390 169:0x204 W/InputManagerService ]
Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#4156a2c8
package info.androidhive.customlistviewvolley.util;
import android.content.Context;
import info.androidhive.customlistviewvolley.R;
import org.apache.http.conn.ClientConnectionManager;
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.SingleClientConnManager;
import java.io.InputStream;
import java.security.KeyStore;
import org.apache.http.conn.ssl.SSLSocketFactory;
public class MyHttpClient extends DefaultHttpClient {
final Context _context;
public MyHttpClient(Context context) {
this._context = context;
}
#Override
protected ClientConnectionManager createClientConnectionManager() {
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
// Register for port 443 our SSLSocketFactory with our keystore
// to the ConnectionManager
registry.register(new Scheme("https", (org.apache.http.conn.scheme.SocketFactory) newSslSocketFactory(), 443));
return new SingleClientConnManager(getParams(), registry);
}
private SSLSocketFactory newSslSocketFactory() {
try {
// Get an instance of the Bouncy Castle KeyStore format
KeyStore trusted = KeyStore.getInstance("BKS");
// Get the raw resource, which contains the keystore with
// your trusted certificates (root and any intermediate certs)
InputStream in = _context.getResources().openRawResource(R.raw.keystore);
try {
// Initialize the keystore with the provided trusted certificates
// Also provide the password of the keystore
trusted.load(in, "xxxxxxxx".toCharArray());
} finally {
in.close();
}
// Pass the keystore to the SSLSocketFactory. The factory is responsible
// for the verification of the server certificate.
SSLSocketFactory sf = new SSLSocketFactory(trusted);
// Hostname verification from certificate
// http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
return sf;
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ java.lang.NullPointerException
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at info.androidhive.customlistviewvolley.Login.connectDP(Login.java:247)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at info.androidhive.customlistviewvolley.adater.CustomGridOfflineMedia$2.onClick(CustomGridOfflineMedia.java:200)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.view.View.performClick(View.java:3511)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.view.View$PerformClick.run(View.java:14110)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:605)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:92)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.os.Looper.loop(Looper.java:137)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:4424)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:511)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
i hope somebody more qualified will answer your question soon, until then something to maybe look into:
HttpPost.reset inherited from AbstractExecutionAwareRequest
says in the docs:
"Resets internal state of the request making it reusable."
making me think that maybe if you do not reset the httppost object it isn't reusable...
src: http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/methods/AbstractExecutionAwareRequest.html#reset()
According to the logcat, your API doesnt response a valid JSON format.
It must be "response" : "0" or something liek that instead of plain 0.
I suggest you to check the server side code for connectDB function and what it returns.
This has been solved by changing some code.
Related
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.
hello i am learning to connect android application with MYSQL using this tutorial.. Tutorial
i want to login and add some comments to the MYSQL database in my hosting.
i have done all the steps correctly. but when i try to load the application in the phone .that say "unfortunately the MYSQL has stopped working" and gives me the following error.
can some one help me to fix this error please. thank you....
Full error stack
02-08 15:21:43.578: E/AndroidRuntime(9705): FATAL EXCEPTION: AsyncTask #1
02-08 15:21:43.578: E/AndroidRuntime(9705): java.lang.RuntimeException: An error occured while executing doInBackground()
02-08 15:21:43.578: E/AndroidRuntime(9705): at android.os.AsyncTask$3.done(AsyncTask.java:299)
02-08 15:21:43.578: E/AndroidRuntime(9705): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
02-08 15:21:43.578: E/AndroidRuntime(9705): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
02-08 15:21:43.578: E/AndroidRuntime(9705): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
02-08 15:21:43.578: E/AndroidRuntime(9705): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
02-08 15:21:43.578: E/AndroidRuntime(9705): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-08 15:21:43.578: E/AndroidRuntime(9705): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-08 15:21:43.578: E/AndroidRuntime(9705): at java.lang.Thread.run(Thread.java:838)
02-08 15:21:43.578: E/AndroidRuntime(9705): Caused by: java.lang.NullPointerException
02-08 15:21:43.578: E/AndroidRuntime(9705): at lk.adspace.mysqltest.Login$AttemptLogin.doInBackground(Login.java:141)
02-08 15:21:43.578: E/AndroidRuntime(9705): at lk.adspace.mysqltest.Login$AttemptLogin.doInBackground(Login.java:1)
02-08 15:21:43.578: E/AndroidRuntime(9705): at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-08 15:21:43.578: E/AndroidRuntime(9705): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-08 15:21:43.578: E/AndroidRuntime(9705): ... 4 more
02-08 15:21:43.928: D/OpenGLRenderer(9705): Flushing caches (mode 0)
02-08 15:21:43.985: D/OpenGLRenderer(9705): Flushing caches (mode 0)
02-08 15:21:44.342: D/OpenGLRenderer(9705): Flushing caches (mode 1)
02-08 15:21:44.345: D/InputMethodManager(9705): deactivate the inputconnection in ControlledInputConnectionWrapper.
02-08 15:21:44.355: D/OpenGLRenderer(9705): Flushing caches (mode 0)
02-08 15:21:44.363: E/WindowManager(9705): Activity lk.adspace.mysqltest.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41344e60 V.E..... R......D 0,0-456,144} that was originally added here
02-08 15:21:44.363: E/WindowManager(9705): android.view.WindowLeaked: Activity lk.adspace.mysqltest.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41344e60 V.E..... R......D 0,0-456,144} that was originally added here
02-08 15:21:44.363: E/WindowManager(9705): at android.view.ViewRootImpl.<init> (ViewRootImpl.java:409)
02-08 15:21:44.363: E/WindowManager(9705): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:218)
02-08 15:21:44.363: E/WindowManager(9705): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:70)
02-08 15:21:44.363: E/WindowManager(9705): at android.app.Dialog.show(Dialog.java:281)
02-08 15:21:44.363: E/WindowManager(9705): at lk.adspace.mysqltest.Login$AttemptLogin.onPreExecute(Login.java:110)
02-08 15:21:44.363: E/WindowManager(9705): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
02-08 15:21:44.363: E/WindowManager(9705): at android.os.AsyncTask.execute(AsyncTask.java:534)
02-08 15:21:44.363: E/WindowManager(9705): at lk.adspace.mysqltest.Login.onClick(Login.java:83)
02-08 15:21:44.363: E/WindowManager(9705): at android.view.View.performClick(View.java:4212)
02-08 15:21:44.363: E/WindowManager(9705): at android.view.View$PerformClick.run(View.java:17476)
02-08 15:21:44.363: E/WindowManager(9705): at android.os.Handler.handleCallback(Handler.java:800)
02-08 15:21:44.363: E/WindowManager(9705): at android.os.Handler.dispatchMessage(Handler.java:100)
02-08 15:21:44.363: E/WindowManager(9705): at android.os.Looper.loop(Looper.java:194)
02-08 15:21:44.363: E/WindowManager(9705): at android.app.ActivityThread.main(ActivityThread.java:5371)
02-08 15:21:44.363: E/WindowManager(9705): at java.lang.reflect.Method.invokeNative(Native Method)
02-08 15:21:44.363: E/WindowManager(9705): at java.lang.reflect.Method.invoke(Method.java:525)
02-08 15:21:44.363: E/WindowManager(9705): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
02-08 15:21:44.363: E/WindowManager(9705): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
02-08 15:21:44.363: E/WindowManager(9705): at dalvik.system.NativeStart.main(Native Method)
02-08 15:21:44.364: D/OpenGLRenderer(9705): Flushing caches (mode 0)
here is my login.java file
package lk.adspace.mysqltest;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends Activity implements OnClickListener{
private EditText user, pass;
private Button mSubmit, mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script location:
//localhost :
//testing on your device
//put your local ip instead, on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
// private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/login.php";
//testing on Emulator:
private static final String LOGIN_URL = "http://www.adspace.lk/webservice/login.php";
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";
//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
//setup input fields
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
//setup buttons
mSubmit = (Button)findViewById(R.id.login);
mRegister = (Button)findViewById(R.id.register);
//register listeners
mSubmit.setOnClickListener(this);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
break;
case R.id.register:
Intent i = new Intent(this, Register.class);
startActivity(i);
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
// save user data
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(Login.this);
Editor edit = sp.edit();
edit.putString("username", username);
edit.commit();
//Intent i = new Intent(Login.this, ReadComments.class);
//finish();
//startActivity(i);
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
Intent i = new Intent(Login.this, ReadComments.class);
finish();
startActivity(i);
}
}
}
JSONParser.java file
package lk.adspace.mysqltest;
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.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) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
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();
} 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;
}
public JSONObject makeHttpRequest(String loginUrl, String string,
List<NameValuePair> params) {
// TODO Auto-generated method stub
return null;
}
}
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="lk.adspace.mysqltest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="lk.adspace.mysqltest.Login"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="lk.adspace.mysqltest.Register"
android:label="#string/app_name" >
</activity>
<activity
android:name="lk.adspace.mysqltest.AddComment"
android:label="#string/app_name" >
</activity>
<activity
android:name="lk.adspace.mysqltest.ReadComments"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
Start your new activity on onPostExecute method instead on doInBackground
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
// save user data
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(Login.this);
Editor edit = sp.edit();
edit.putString("username", username);
edit.commit();
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
Intent i = new Intent(Login.this, ReadComments.class);
finish();
startActivity(i);
Ok, i find a lot of people with the same problem but i was not able to find a good answer yet.
I im doing a simple httprequest with JSON parser, but im getting this error:
12-13 17:11:35.406: E/AndroidRuntime(28346): FATAL EXCEPTION: AsyncTask #1
12-13 17:11:35.406: E/AndroidRuntime(28346): java.lang.RuntimeException: An error occured while executing doInBackground()
12-13 17:11:35.406: E/AndroidRuntime(28346): at android.os.AsyncTask$3.done(AsyncTask.java:278)
I am really lost. Anyone have an answer?
here is my code:
Java: Main Ac.
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Vector;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.exemple.beans.MesaBean;
import com.exemple.json.JSONParser;
public class MainActivity extends Activity {
public static final String ESTABELECIMENTO = "NossoBar";
JSONParser jsonParser = new JSONParser();
EditText numeroMesa;
private ProgressDialog pDialog;
Button criar;
private static String url_create_product = "http://www.naga.net.br/android/beerapp/delete_product.php";
private static final String TAG_SUCCESS = "success";
public static Vector<MesaBean> mesas;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
criar = (Button) findViewById(R.id.btncriar);
numeroMesa = (EditText) findViewById(R.id.numeroMesa);
if (mesas == null) {
mesas = new Vector<MesaBean>();
}
criar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int numero = Integer.valueOf(numeroMesa.getText().toString());
String senha = gerarsenha();
int id = mesas.size()+1;
String currentDateTimeString = DateFormat
.getDateTimeInstance().format(new Date());
MesaBean mb = new MesaBean();
mb.setCriadoEm(currentDateTimeString);
mb.setIdmesa(id);
mb.setSenha(senha);
mb.setMesa(numero);
mesas.add(mb);
String resp = ESTABELECIMENTO+numero+senha;
new CreateNewProduct(resp).execute();
}
});
}
class CreateNewProduct extends AsyncTask<String, String, String> {
String resp;
CreateNewProduct() {
}
public CreateNewProduct(String resp) {
this.resp = resp;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Postando comparação...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
// getting JSON Object
try {
// Note that create product url accepts POST method
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("mesaconta", resp));
params.add(new BasicNameValuePair("lalal", "lalal"));
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
resp = "Sucess";
} else {
resp = "Fail";
}
} catch (JSONException e) {
startActivity(new Intent(getApplicationContext(),
MainActivity.class));
}
if (resp.equalsIgnoreCase("Sucess")) {
// closing this screen
startActivity(new Intent(getApplicationContext(),
ListaMesas.class));
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
private String gerarsenha() {
int min = 0;
int max = 9;
Random r = new Random();
Integer a = r.nextInt(max - min + 1) + min;
Integer b = r.nextInt(max - min + 1) + min;
Integer c = r.nextInt(max - min + 1) + min;
Integer d = r.nextInt(max - min + 1) + min;
Integer e = r.nextInt(max - min + 1) + min;
Integer f = r.nextInt(max - min + 1) + min;
String resp = a.toString() + b.toString() + c.toString() + d.toString()
+ e.toString() + f.toString();
return resp;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
JsonParser:
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
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() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// 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();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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();
} 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;
}
}
The code in PHP on the server allready works fine, im using it in another program.
Can you help me?
Full tracktrace:
12-13 18:03:06.516: E/JSON Parser(31184): Error parsing data org.json.JSONException: End of input at character 1 of
12-13 18:03:06.516: W/dalvikvm(31184): threadid=11: thread exiting with uncaught exception (group=0x41a0b6f0)
12-13 18:03:06.546: E/AndroidRuntime(31184): FATAL EXCEPTION: AsyncTask #1
12-13 18:03:06.546: E/AndroidRuntime(31184): java.lang.RuntimeException: An error occured while executing doInBackground()
12-13 18:03:06.546: E/AndroidRuntime(31184): at android.os.AsyncTask$3.done(AsyncTask.java:278)
12-13 18:03:06.546: E/AndroidRuntime(31184): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
12-13 18:03:06.546: E/AndroidRuntime(31184): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
12-13 18:03:06.546: E/AndroidRuntime(31184): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
12-13 18:03:06.546: E/AndroidRuntime(31184): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
12-13 18:03:06.546: E/AndroidRuntime(31184): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
12-13 18:03:06.546: E/AndroidRuntime(31184): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
12-13 18:03:06.546: E/AndroidRuntime(31184): at java.lang.Thread.run(Thread.java:856)
12-13 18:03:06.546: E/AndroidRuntime(31184): Caused by: java.lang.NullPointerException
12-13 18:03:06.546: E/AndroidRuntime(31184): at com.example.gerente2.MainActivity$CreateNewProduct.doInBackground(MainActivity.java:117)
12-13 18:03:06.546: E/AndroidRuntime(31184): at com.example.gerente2.MainActivity$CreateNewProduct.doInBackground(MainActivity.java:1)
12-13 18:03:06.546: E/AndroidRuntime(31184): at android.os.AsyncTask$2.call(AsyncTask.java:264)
12-13 18:03:06.546: E/AndroidRuntime(31184): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
12-13 18:03:06.546: E/AndroidRuntime(31184): ... 4 more
12-13 18:03:07.306: W/IMGSRV(31184): :0: gralloc_unregister_buffer: ID: 3355 handle: 0x866bf70 size: 540 x 888 fmt: 2 usage: 0x933
12-13 18:03:07.306: W/IMGSRV(31184): :0: gralloc_unregister_buffer: ID: 3356 handle: 0x86bfa60 size: 540 x 888 fmt: 2 usage: 0x933
12-13 18:03:07.316: W/IMGSRV(31184): :0: gralloc_unregister_buffer: ID: 3359 handle: 0x8649a10 size: 392 x 175 fmt: 1 usage: 0x933
12-13 18:03:07.316: W/IMGSRV(31184): :0: gralloc_unregister_buffer: ID: 3360 handle: 0x8669800 size: 392 x 175 fmt: 1 usage: 0x933
12-13 18:03:08.006: E/WindowManager(31184): Activity com.example.gerente2.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#211b52a0 that was originally added here
12-13 18:03:08.006: E/WindowManager(31184): android.view.WindowLeaked: Activity com.example.gerente2.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#211b52a0 that was originally added here
12-13 18:03:08.006: E/WindowManager(31184): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:356)
12-13 18:03:08.006: E/WindowManager(31184): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:267)
12-13 18:03:08.006: E/WindowManager(31184): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215)
12-13 18:03:08.006: E/WindowManager(31184): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:140)
12-13 18:03:08.006: E/WindowManager(31184): at android.view.Window$LocalWindowManager.addView(Window.java:537)
12-13 18:03:08.006: E/WindowManager(31184): at android.app.Dialog.show(Dialog.java:284)
12-13 18:03:08.006: E/WindowManager(31184): at com.example.gerente2.MainActivity$CreateNewProduct.onPreExecute(MainActivity.java:99)
12-13 18:03:08.006: E/WindowManager(31184): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:561)
12-13 18:03:08.006: E/WindowManager(31184): at android.os.AsyncTask.execute(AsyncTask.java:511)
12-13 18:03:08.006: E/WindowManager(31184): at com.example.gerente2.MainActivity$1.onClick(MainActivity.java:70)
12-13 18:03:08.006: E/WindowManager(31184): at android.view.View.performClick(View.java:3531)
12-13 18:03:08.006: E/WindowManager(31184): at android.view.View$PerformClick.run(View.java:14224)
12-13 18:03:08.006: E/WindowManager(31184): at android.os.Handler.handleCallback(Handler.java:605)
12-13 18:03:08.006: E/WindowManager(31184): at android.os.Handler.dispatchMessage(Handler.java:92)
12-13 18:03:08.006: E/WindowManager(31184): at android.os.Looper.loop(Looper.java:137)
12-13 18:03:08.006: E/WindowManager(31184): at android.app.ActivityThread.main(ActivityThread.java:4699)
12-13 18:03:08.006: E/WindowManager(31184): at java.lang.reflect.Method.invokeNative(Native Method)
12-13 18:03:08.006: E/WindowManager(31184): at java.lang.reflect.Method.invoke(Method.java:511)
12-13 18:03:08.006: E/WindowManager(31184): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
12-13 18:03:08.006: E/WindowManager(31184): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
12-13 18:03:08.006: E/WindowManager(31184): at dalvik.system.NativeStart.main(Native Method)
Have you checked the string that you are receiving back from that server? The
Error parsing data org.json.JSONException: End of input at character 1
Means you're getting an empty response back from the server.
I'm trying to add getByName to get the IP address of a hostname and use it in my POST command
the problem is wherever i insert this code it crashes
i tried to insert in doInBackground it also crashes So where should i insert it ??
package com.example.loginad;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Logindb extends Activity {
Button login;
EditText u,p;
TextView res;
String result;
String x="mobile";
String host;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logindb);
login=(Button)findViewById(R.id.login);
u=(EditText)findViewById(R.id.u);
p=(EditText)findViewById(R.id.p);
res=(TextView)findViewById(R.id.res);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new MyAsyncTask().execute(u.getText().toString(),p.getText().toString());
}
});
}
private class MyAsyncTask extends AsyncTask<String, Integer, Boolean>{
#Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
boolean success = postData(params[0],params[1]);
try
{
InetAddress address=null;
address = InetAddress.getByName("Nicky-PC");
host=address.getHostAddress();
}
catch(Exception e)
{
e.printStackTrace();
}
return success;
}
protected void onPostExecute(Boolean localres){
if (localres){
res.setText("A Correct Username and Password");
}else{
res.setText("Incorrect Username or Password");
}
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Integer... progress){
//pb.setProgress(progress[0]);
//Toast.makeText(getApplicationContext(), "Done", Toast.LENGTH_LONG).show();
}
/*public void ObtainHost()
{
try
{
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
} */
public Boolean postData(String a,String b) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", a));
postParameters.add(new BasicNameValuePair("password", b));
postParameters.add(new BasicNameValuePair("mobileid",x));
// String valid = "1";
String response = null;
try {
// Toast.makeText(getApplicationContext(), host.toString(), Toast.LENGTH_LONG).show();
response = CustomHttpClient.executeHttpPost("http://"+host+"/new/check.php",postParameters);
//now in result you will have the response from php file either 0 or 1.
result = response.toString();
// res = res.trim();
result = result.replaceAll("\\s+", "");
// error.setText(res);
} catch (Exception e) {
res.setText(e.toString());
}
return result.equals("1");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.logindb, menu);
return true;
}
}
Stacktrace
11-26 21:28:37.856: D/libEGL(17150): loaded /system/lib/egl/libEGL_genymotion.so
11-26 21:28:37.876: D/(17150): HostConnection::get() New Host Connection established 0xb8ed35a8, tid 17150
11-26 21:28:37.900: D/libEGL(17150): loaded /system/lib/egl/libGLESv1_CM_genymotion.so
11-26 21:28:37.900: D/libEGL(17150): loaded /system/lib/egl/libGLESv2_genymotion.so
11-26 21:28:37.968: W/EGL_genymotion(17150): eglSurfaceAttrib not implemented
11-26 21:28:37.976: E/OpenGLRenderer(17150): Getting MAX_TEXTURE_SIZE from GradienCache
11-26 21:28:37.996: E/OpenGLRenderer(17150): Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
11-26 21:28:37.996: D/OpenGLRenderer(17150): Enabling debug mode 0
11-26 21:28:44.876: W/dalvikvm(17150): threadid=13: thread exiting with uncaught exception (group=0xa4c1f648)
11-26 21:28:44.920: E/AndroidRuntime(17150): FATAL EXCEPTION: AsyncTask #3
11-26 21:28:44.920: E/AndroidRuntime(17150): java.lang.RuntimeException: An error occured while executing doInBackground()
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.lang.Thread.run(Thread.java:841)
11-26 21:28:44.920: E/AndroidRuntime(17150): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:5908)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:837)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:358)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.widget.TextView.checkForRelayout(TextView.java:6524)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.widget.TextView.setText(TextView.java:3771)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.widget.TextView.setText(TextView.java:3629)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.widget.TextView.setText(TextView.java:3604)
11-26 21:28:44.920: E/AndroidRuntime(17150): at com.example.loginad.Logindb$MyAsyncTask.postData(Logindb.java:130)
11-26 21:28:44.920: E/AndroidRuntime(17150): at com.example.loginad.Logindb$MyAsyncTask.doInBackground(Logindb.java:70)
11-26 21:28:44.920: E/AndroidRuntime(17150): at com.example.loginad.Logindb$MyAsyncTask.doInBackground(Logindb.java:1)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-26 21:28:44.920: E/AndroidRuntime(17150): ... 4 more
11-26 21:28:44.932: D/dalvikvm(17150): GC_FOR_ALLOC freed 259K, 5% free 6365K/6660K, paused 8ms, total 8ms
First if you will use AsyncHttpClient then you do not need AsyncTask but if you will use HttpClient then you need AsyncTask task.
the below code is part from working code to execute get and post requests. Modify it as your need
#Override
protected String doInBackground(String... params) {
backGroundExecuted = false;
Log.d("doInBackground", "Start processing doInBackground");
HttpClient httpClient = null;
HttpPost httpPost = null;
HttpGet httpGet = null;
if (httpMethodType == null || url == null) {
Log.d("doInBackground" , "The URL and Method Type is mandatory, cannot be null - httpMethodType =" + httpMethodType + " and url =" + url);
this.getApiResponse().setSuccess(false);
this.getApiResponse().setResponseCode(HttpResponseCode.BAD_REQUEST);
this.getApiResponse().setResponseDescription("The URL and Method Type is mandatory, cannot be null");
return null;
}
try {
//set timeout
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, TIME_OUT);
HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIME_OUT);
httpClient = new DefaultHttpClient(httpParameters);
HttpResponse httpResponse = null;
if (httpMethodType.equals(HTTPMethodType.POST.toString())) {
httpPost = new HttpPost(url);
//setting json object to request.
if (postParams != null) {
AbstractHttpEntity entity = null;
entity = new ByteArrayEntity(postParams.getBytes("UTF8"));
if (httpContentType != null) {
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, httpContentType));
}
httpPost.setEntity(entity);
}
httpResponse = httpClient.execute(httpPost);
} else if (httpMethodType.equals(HTTPMethodType.GET.toString()) || httpMethodType.equals(HTTPMethodType.PUT.toString())) {
if (queryParams != null) {
url = url + "?" + URLEncodedUtils.format(queryParams, "utf-8");
Log.d(TAG ,"new URL :" + url);
}
httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
this.getApiResponse().setResponseCode(httpResponse.getStatusLine().getStatusCode());
this.getApiResponse().setResponseDescription(httpResponse.getStatusLine().getReasonPhrase());
if (this.getApiResponse().getResponseCode() != HttpStatus.SC_OK) {
this.getApiResponse().setSuccess(false);
Log.w(getClass().getSimpleName(),
"Error " + this.getApiResponse().getResponseCode() + " for URL " + url);
Log.w(getClass().getSimpleName(),
"Error " + this.getApiResponse().getResponseDescription() + " for URL " + url);
}
Log.d("doInBackground", "The API call executed and will check the response");
HttpEntity entityResp = httpResponse.getEntity();
if (entityResp != null) {
this.getApiResponse().setResponse(appHelper.getStringFromInputStream(entityResp.getContent()));
Log.d("doInBackground","The response is :" + this.getApiResponse().getResponse());
this.getApiResponse().setSuccess(true);
}
} catch (UnsupportedEncodingException e1) {
Log.e("doInBackground","Exception :" + e1.toString());
this.getApiResponse().setSuccess(false);
this.getApiResponse().setResponseCode(HttpResponseCode.BAD_REQUEST);
this.getApiResponse().setResponseDescription("Exception :" + e1.toString());
Log.e("doInBackground","Exception :" + e1.toString());
e1.printStackTrace();
} catch (Exception e) {
Log.e("doInBackground","Exception :" + e.toString());
this.getApiResponse().setSuccess(false);
this.getApiResponse().setResponseCode(HttpResponseCode.BAD_REQUEST);
this.getApiResponse().setResponseDescription("Exception :" + e.toString());
if (httpPost != null && !httpPost.isAborted()) {
httpPost.abort();
}
} finally {
if (httpClient != null) {
httpClient.getConnectionManager().shutdown();
}
backGroundExecuted = true;
}
return null;
}
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
I am new to android application development. I was doing this tutorial app.
When I run it in the emulator ,it says "Unfortunately AndroidJSONParsingActivity has stopped working.
" There are no errors in the code. The API level is 17 and the emulator is Nexus S.
Please help me out.
I got the tutorial CODE from JSON tutorial
AndroidJsonParsing.java
package com.example.androidjsonparsingactivity;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AndroidJSONParsing extends ListActivity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
}
}
JSONParser.java
package com.example.androidjsonparsingactivity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
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();
} 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;
}
}
SingleMenuItemActivity.java
package com.example.androidjsonparsingactivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SingleMenuItemActivity extends Activity {
// JSON node keys
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PHONE_MOBILE = "mobile";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String cost = in.getStringExtra(TAG_EMAIL);
String description = in.getStringExtra(TAG_PHONE_MOBILE);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCost = (TextView) findViewById(R.id.email_label);
TextView lblDesc = (TextView) findViewById(R.id.mobile_label);
lblName.setText(name);
lblCost.setText(cost);
lblDesc.setText(description);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidjsonparsingactivity"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.androidjsonparsingactivity.AndroidJSONParsing"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SingleListItem"
android:label="Single Item Selected"></activity>
</application>
</manifest>
Logcat
08-01 07:32:35.531: D/dalvikvm(1121): GC_FOR_ALLOC freed 42K, 7% free 2609K/2792K, paused 37ms, total 41ms
08-01 07:32:35.541: I/dalvikvm-heap(1121): Grow heap (frag case) to 3.288MB for 635812-byte allocation
08-01 07:32:35.591: D/dalvikvm(1121): GC_FOR_ALLOC freed 2K, 6% free 3227K/3416K, paused 47ms, total 47ms
08-01 07:32:35.672: D/dalvikvm(1121): GC_CONCURRENT freed <1K, 6% free 3237K/3416K, paused 9ms+16ms, total 82ms
08-01 07:32:35.740: D/AndroidRuntime(1121): Shutting down VM
08-01 07:32:35.740: W/dalvikvm(1121): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
08-01 07:32:35.761: E/AndroidRuntime(1121): FATAL EXCEPTION: main
08-01 07:32:35.761: E/AndroidRuntime(1121): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.androidjsonparsingactivity/com.example.androidjsonparsingactivity.AndroidJSONParsing}: android.os.NetworkOnMainThreadException
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.os.Handler.dispatchMessage(Handler.java:99)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.os.Looper.loop(Looper.java:137)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.main(ActivityThread.java:5041)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.lang.reflect.Method.invoke(Method.java:511)
08-01 07:32:35.761: E/AndroidRuntime(1121): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-01 07:32:35.761: E/AndroidRuntime(1121): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-01 07:32:35.761: E/AndroidRuntime(1121): at dalvik.system.NativeStart.main(Native Method)
08-01 07:32:35.761: E/AndroidRuntime(1121): Caused by: android.os.NetworkOnMainThreadException
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.net.InetAddress.getAllByName(InetAddress.java:214)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-01 07:32:35.761: E/AndroidRuntime(1121): at com.example.androidjsonparsingactivity.JSONParser.getJSONFromUrl(JSONParser.java:38)
08-01 07:32:35.761: E/AndroidRuntime(1121): at com.example.androidjsonparsingactivity.AndroidJSONParsing.onCreate(AndroidJSONParsing.java:54)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.Activity.performCreate(Activity.java:5104)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
08-01 07:32:35.761: E/AndroidRuntime(1121): ... 11 more
For Android 4.0 and above you cant do network operations on UI Thread and need to use background threads.
You are calling the following code from the main thread instead of
background thread therefore this exception is thrown .
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
Instead create a async task and perform this in the doInBackground() of the async task
Async task performs the opertaion in background instead of performing it on the main /UI thread
class FetchJsonTask extends AsyncTask<Void, Void, void> {
protected Void doInBackground(Void... params) {
try {
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
} catch (Exception e) {
}
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//code to be executed after background task is finished
}
protected void onPreExecute() {
super.onPreExecute();
//code to be executed before background task is started
}
return null;
}
In onCreate() call the execute the async task in the following way :
new FetchJsonTask().execute();
Related Link:
How to fix android.os.NetworkOnMainThreadException?
you have called the Web from main thread. that's why you have got
Caused by: android.os.NetworkOnMainThreadException
after android 4.0 you cant do network operations on its UIThread. you need to use background threads. i will prefer to use AsyncTask for network call.
Hope it Helps!!
read commented parts and change your code according to that.
class MyAsync extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
// do your JSON parse here
return null;
}
#Override
protected void onPostExecute(Void result) {
// after gettin json data do whatever you want here
super.onPostExecute(result);
}
}
call your async class in your oncreate as:
new MyAsync().execute();