what the error in this code to get json data? [duplicate] - java

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
android.os.NetworkOnMainThreadException . Need to use async task?
(2 answers)
Closed 9 years ago.
What is the error in this code?
I would like to add a facebook page name and get its json data, but there is something error I cannot discover. These are all files I use and added logcat messages:
PagesActivity.java
package com.engahmedphp.facebookcollector;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class PagesActivity extends Activity {
DatabaseHandler db = new DatabaseHandler(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pages);
final Button button = (Button) findViewById(R.id.addPage);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(
PagesActivity.this);
alert.setTitle("Add New Page");
alert.setMessage("Enter Page Name OR Valid Facebook Link");
// Set an EditText view to get user input
final EditText input = new EditText(PagesActivity.this);
alert.setView(input);
alert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String value = input.getText().toString();
// Do something with value!
String url = "http://graph.facebook.com/"
+ value + "/?fields=picture,name";
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Storing each json item in variable
String name = json.getString("name");
String fid = json.getString("id");
String picture = json
.getJSONObject("picture")
.getJSONObject("data")
.getString("url");
db.addPage(name, fid, picture);
} catch (JSONException e) {
e.printStackTrace();
}
// addPageData(value);
}
});
alert.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// Canceled.
}
});
alert.show();
}
});
}
void addPageData(String pageName) {
String url = "http://graph.facebook.com/" + pageName
+ "/?fields=picture,name";
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Storing each json item in variable
String name = json.getString("name");
String fid = json.getString("id");
String picture = json.getJSONObject("picture")
.getJSONObject("data").getString("url");
db.addPage(name, fid, picture);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.splash, menu);
return true;
}
}
JSONParser.java
package com.engahmedphp.facebookcollector;
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;
}
}
LogCat
08-31 03:35:23.031: D/dalvikvm(15972): GC_FOR_ALLOC freed 39K, 6% free 2633K/2792K, paused 65ms, total 68ms
08-31 03:35:23.041: I/dalvikvm-heap(15972): Grow heap (frag case) to 3.767MB for 1136500-byte allocation
08-31 03:35:23.163: D/dalvikvm(15972): GC_FOR_ALLOC freed 2K, 5% free 3740K/3904K, paused 116ms, total 116ms
08-31 03:35:23.511: D/gralloc_goldfish(15972): Emulator without GPU emulation detected.
08-31 03:35:26.611: I/Choreographer(15972): Skipped 30 frames! The application may be doing too much work on its main thread.
08-31 03:39:40.903: D/dalvikvm(15972): GC_FOR_ALLOC freed 47K, 4% free 4013K/4180K, paused 48ms, total 81ms
08-31 03:39:40.903: I/dalvikvm-heap(15972): Grow heap (frag case) to 4.638MB for 635812-byte allocation
08-31 03:39:41.023: D/dalvikvm(15972): GC_FOR_ALLOC freed 2K, 4% free 4631K/4804K, paused 111ms, total 111ms
08-31 03:39:41.483: I/Choreographer(15972): Skipped 83 frames! The application may be doing too much work on its main thread.
08-31 03:39:48.701: D/AndroidRuntime(15972): Shutting down VM
08-31 03:39:48.701: W/dalvikvm(15972): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
08-31 03:39:48.741: E/AndroidRuntime(15972): FATAL EXCEPTION: main
08-31 03:39:48.741: E/AndroidRuntime(15972): android.os.NetworkOnMainThreadException
08-31 03:39:48.741: E/AndroidRuntime(15972): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
08-31 03:39:48.741: E/AndroidRuntime(15972): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
08-31 03:39:48.741: E/AndroidRuntime(15972): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
08-31 03:39:48.741: E/AndroidRuntime(15972): at java.net.InetAddress.getAllByName(InetAddress.java:214)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-31 03:39:48.741: E/AndroidRuntime(15972): at com.engahmedphp.facebookcollector.JSONParser.getJSONFromUrl(JSONParser.java:38)
08-31 03:39:48.741: E/AndroidRuntime(15972): at com.engahmedphp.facebookcollector.PagesActivity$1$1.onClick(PagesActivity.java:49)
08-31 03:39:48.741: E/AndroidRuntime(15972): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
08-31 03:39:48.741: E/AndroidRuntime(15972): at android.os.Handler.dispatchMessage(Handler.java:99)
08-31 03:39:48.741: E/AndroidRuntime(15972): at android.os.Looper.loop(Looper.java:137)
08-31 03:39:48.741: E/AndroidRuntime(15972): at android.app.ActivityThread.main(ActivityThread.java:5103)
08-31 03:39:48.741: E/AndroidRuntime(15972): at java.lang.reflect.Method.invokeNative(Native Method)
08-31 03:39:48.741: E/AndroidRuntime(15972): at java.lang.reflect.Method.invoke(Method.java:525)
08-31 03:39:48.741: E/AndroidRuntime(15972): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
08-31 03:39:48.741: E/AndroidRuntime(15972): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-31 03:39:48.741: E/AndroidRuntime(15972): at dalvik.system.NativeStart.main(Native Method)

You are getting NetworkOnMainThreadException. See How to fix android.os.NetworkOnMainThreadException? . This exception is thrown when an application attempts to perform a networking operation on its main (UI) thread. Do the networking tasks using AsyncTask or inside a new thread. See the Android Documentation on NetworkOnMainThreadException for reasons of this Exception.
Here:
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
you are doing network related stuff on main UI thread. Try to do this in a new thread.

The JSONParser make a HTTP connect in UI thread(The oneClick is invoked in UI thread)and it was fobidden now.
So you need move the network codes to other thread.

In case you have not noticed; StrictMode for network access results in a fatal error as for Android 3.0 (Honeycomb) or later, unless your app is targeting an API version before Honeycomb.
The right way of solving this is to use Android AsyncTask for network access.
The lazy way of handling this is to turn the check of:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

As others mentioned, you shouldn't be doing networking on UI thread to make your app UI responsive.
Try this
public class JsonParser extends AsyncTask<String, Void, JSONObject> {
InputStream is = null;
JSONObject jObj = null;
String json = "";
#Override
protected JSONObject doInBackground(String... params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(params[0]);
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;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
// Storing each json item in variable
String name = json.getString("name");
String fid = json.getString("id");
String picture = json
.getJSONObject("picture")
.getJSONObject("data")
.getString("url");
db.addPage(name, fid, picture);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Put the above class in your activity class, then use new JsonParser().execute(url); to fetch data and update the database.

Related

Android Application Force closing (retrieving data)

I am new to Android application development and Java programming, currently, I'm working on a project to retrieve from my database the status of a service. However, the application will stop working whenever I tried to submit my tracking ID.
MainActivity.java
package com.example.trackstatus;
import com.example.testapp.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button btnViewStatus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Buttons
btnViewStatus = (Button) findViewById(R.id.btnViewStatus);
// view products click event
btnViewStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launching View status activity
Intent i = new Intent(getApplicationContext(), ViewTrackingStatusActivity.class);
startActivity(i);
}
});
}}
TrackStatus Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package = "com.example.trackstatus"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="20" />
<!-- Internet Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- View Tracking Status Activity -->
<activity
android:name=".ViewTrackingStatusActivity"
android:label="View Tracking Status" >
</activity>
</application>
</manifest>
ViewTrackingStatusActivity.java
package com.example.trackstatus;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.testapp.R;
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.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ViewTrackingStatusActivity extends Activity{
TextView textView1;
EditText trackingNumberText;
Button btnViewStatus;
String tid;
String tracking;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// url to get service status
private static String url = "http://10.0.2.2/1201716f/android%20connect/get_svc.php?tid=0";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_TRACKING = "tracking";
private static final String TAG_TID = "tid";
public String trackingno;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = (TextView) findViewById(R.id.textView1);
trackingNumberText = (EditText) findViewById(R.id.trackingNumberText);
trackingno = trackingNumberText.getText().toString();
btnViewStatus = (Button) findViewById(R.id.btnViewStatus);
Intent intent = getIntent();
tid = intent.getStringExtra(TAG_TID);
// Getting tracking status details in background thread
new GetStatusDetails().execute();
//Toast.makeText(getApplicationContext(),"Hello",
// Toast.LENGTH_LONG).show();
}
class GetStatusDetails extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewTrackingStatusActivity.this);
pDialog.setMessage("Loading details");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tid", trackingno));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);
// check your log for json response
Log.d("Tracking Status Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray trackingObj = json.getJSONArray(TAG_TRACKING); // JSON Array
// get first product object from JSON Array
JSONObject tracking = trackingObj.getJSONObject(0);
// display tracking status in ToastBox
Toast.makeText(ViewTrackingStatusActivity.this,json.getString(TAG_TRACKING),Toast.LENGTH_LONG).show();
}
else
{
//service with tid not found
Toast.makeText(getApplicationContext(),"Service not found!",Toast.LENGTH_LONG).show();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
});
return null;
}
}
}
JSONParser.java
package com.example.trackstatus;
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;
}
}
Logcat
08-19 23:52:46.644: D/AndroidRuntime(3809): Shutting down VM
08-19 23:52:46.644: W/dalvikvm(3809): threadid=1: thread exiting with uncaught exception (group=0x41b37700)
08-19 23:52:46.654: E/AndroidRuntime(3809): FATAL EXCEPTION: main
08-19 23:52:46.654: E/AndroidRuntime(3809): android.os.NetworkOnMainThreadException
08-19 23:52:46.654: E/AndroidRuntime(3809): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
08-19 23:52:46.654: E/AndroidRuntime(3809): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
08-19 23:52:46.654: E/AndroidRuntime(3809): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
08-19 23:52:46.654: E/AndroidRuntime(3809): at libcore.io.IoBridge.connect(IoBridge.java:112)
08-19 23:52:46.654: E/AndroidRuntime(3809): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
08-19 23:52:46.654: E/AndroidRuntime(3809): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
08-19 23:52:46.654: E/AndroidRuntime(3809): at java.net.Socket.connect(Socket.java:842)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-19 23:52:46.654: E/AndroidRuntime(3809): at com.example.trackstatus.JSONParser.makeHttpRequest(JSONParser.java:63)
08-19 23:52:46.654: E/AndroidRuntime(3809): at com.example.trackstatus.ViewTrackingStatusActivity$GetStatusDetails$1.run(ViewTrackingStatusActivity.java:92)
08-19 23:52:46.654: E/AndroidRuntime(3809): at android.os.Handler.handleCallback(Handler.java:730)
08-19 23:52:46.654: E/AndroidRuntime(3809): at android.os.Handler.dispatchMessage(Handler.java:92)
08-19 23:52:46.654: E/AndroidRuntime(3809): at android.os.Looper.loop(Looper.java:137)
08-19 23:52:46.654: E/AndroidRuntime(3809): at android.app.ActivityThread.main(ActivityThread.java:5293)
08-19 23:52:46.654: E/AndroidRuntime(3809): at java.lang.reflect.Method.invokeNative(Native Method)
08-19 23:52:46.654: E/AndroidRuntime(3809): at java.lang.reflect.Method.invoke(Method.java:525)
08-19 23:52:46.654: E/AndroidRuntime(3809): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
08-19 23:52:46.654: E/AndroidRuntime(3809): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
08-19 23:52:46.654: E/AndroidRuntime(3809): at dalvik.system.NativeStart.main(Native Method)
08-19 23:52:49.086: I/Process(3809): Sending signal. PID: 3809 SIG: 9
According to your LogCat message:
Caused by: java.lang.NullPointerException at com.example.trackstatus.ViewTrackingStatusActivity.onCreate(ViewTrackingStatusActivity.java:55)
You are missing :
setContentView(R.layout.your_layout);
where your EditText trackingNumberText must be declared.
thats the reason for what trackingNumberText is null
trackingNumberText = (EditText) findViewById(R.id.trackingNumberText);
More info:
setContentView() method
Update:
Since you have this new exception: NetworkOnMainThreadException
android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
you have to implement the use of AsyncTask
And hey! you donĀ“t need to use runOnUiThread inside the doInBackground() method of the Asynctask :P:
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
Move the lines that implies operations on UI thread like
Toast.makeText(getApplicationContext(),"Service not found!",Toast.LENGTH_LONG).show();
to the onPostExecute() method of the Asynctask
The error is in Line55
String trackingno = trackingNumberText.getText().toString();
trackingNumberText is NULL
instead try to do NULL check
String trackingno = "";
if(trackingNumberText.getText().length() > 0)
{
trackingno = trackingNumberText.getText().toString();
} else {
Toast.makeText(getApplicationContext(), "Enter values", Toast.LENGTH_LONG).show();
return;
}
EDIT:
You have to send all requests to server in Background Thread, use AsyncTask
Here is the detailed example for performing Network Operation.

Android Json HttpGet/Post HttpResponse

I am trying to take a product from mysql database according to its barcode number. I checked my php codes they are working but on android side i am taking an error.
Here my GetProductDetails class (i think this part is ok);
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
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.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Query_product extends Activity {
EditText txtId, txtName, txtPrice, txtDesc;
Button btnSave, btnDelete;
String ID = "";
String pid;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// url to get all products list
private static final String url_product_details = "http://10.0.2.2/ssa/get_product_details.php";
private static final String url_update_product = "http://10.0.2.2/ssa/update_product.php";
private static final String url_delete_product = "http://10.0.2.2/ssa/delete_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String TAG_PID = "barcode";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.query_prod);
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
ID += " " + getIntent().getExtras().getString(Constants.ID);
pid = ID;
new GetProductDetails().execute();
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// starting background task to update product
new SaveProductDetails().execute();
}
});
// Delete button click event
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// deleting product in background thread
new DeleteProduct().execute();
}
});
}
class GetProductDetails extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Query_product.this);
pDialog.setMessage("Loading product details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_PID, pid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_product_details, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtId = (EditText) findViewById(R.id.inputId);
txtName = (EditText) findViewById(R.id.inputName);
txtPrice = (EditText) findViewById(R.id.inputPrice);
txtDesc = (EditText) findViewById(R.id.inputDesc);
// display product data in EditText
txtId.setText(product.getString(TAG_PID));
txtName.setText(product.getString(TAG_NAME));
txtPrice.setText(product.getString(TAG_PRICE));
txtDesc.setText(product.getString(TAG_DESCRIPTION));
}
else
{
String error = "Not found!";
Toast.makeText(Query_product.this, error, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
Here makeHttpRequest class;
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;
}
}
I couldn't be able to solve the problem. Program runs until this line;
HttpResponse httpResponse = httpClient.execute(httpGet);
Logcat errors;
12-14 18:05:30.994: E/AndroidRuntime(986): FATAL EXCEPTION: main
12-14 18:05:30.994: E/AndroidRuntime(986): android.os.NetworkOnMainThreadException
12-14 18:05:30.994: E/AndroidRuntime(986): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
12-14 18:05:30.994: E/AndroidRuntime(986): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
12-14 18:05:30.994: E/AndroidRuntime(986): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
12-14 18:05:30.994: E/AndroidRuntime(986): at libcore.io.IoBridge.connect(IoBridge.java:112)
12-14 18:05:30.994: E/AndroidRuntime(986): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
12-14 18:05:30.994: E/AndroidRuntime(986): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
12-14 18:05:30.994: E/AndroidRuntime(986): at java.net.Socket.connect(Socket.java:842)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-14 18:05:30.994: E/AndroidRuntime(986): at com.example.ssa.JSONParser.makeHttpRequest(JSONParser.java:66)
12-14 18:05:30.994: E/AndroidRuntime(986): at com.example.ssa.Query_product$GetProductDetails$1.run(Query_product.java:134)
12-14 18:05:30.994: E/AndroidRuntime(986): at android.os.Handler.handleCallback(Handler.java:725)
12-14 18:05:30.994: E/AndroidRuntime(986): at android.os.Handler.dispatchMessage(Handler.java:92)
12-14 18:05:30.994: E/AndroidRuntime(986): at android.os.Looper.loop(Looper.java:137)
12-14 18:05:30.994: E/AndroidRuntime(986): at android.app.ActivityThread.main(ActivityThread.java:5041)
12-14 18:05:30.994: E/AndroidRuntime(986): at java.lang.reflect.Method.invokeNative(Native Method)
12-14 18:05:30.994: E/AndroidRuntime(986): at java.lang.reflect.Method.invoke(Method.java:511)
12-14 18:05:30.994: E/AndroidRuntime(986): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-14 18:05:30.994: E/AndroidRuntime(986): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-14 18:05:30.994: E/AndroidRuntime(986): at dalvik.system.NativeStart.main(Native Method)
12-14 18:10:31.483: I/Process(986): Sending signal. PID: 986 SIG: 9
12-14 18:10:33.372: D/gralloc_goldfish(1025): Emulator without GPU emulation detected.
You cannot perform network tasks on the main thread because it might block your application in case the network task takes a very long time. You need to run such tasks in the background using AsyncTask instead.
Here's the documentation.
Try using the below code inside your main activity below setContentView(), to avoid the networkOnmainThread exception..
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Looks like the error is not of json.
You are trying to call a url from Main Thread which is not allowed from android 4.0
Try using AsynTask or call the url from secondary thread.

java Null pointer Exception on fetching JSON

this is my code it throws java null pointer exception on fetching json from url.i have given the internet permission in android manifest and now fetch url in new thread as it does not allow network activities in main threaed
package com.example.usa;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
public class Home extends Activity {
// 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";
JSONArray contacts = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
final ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
final JSONParser jParser = new JSONParser();
final JSONObject json = null ;
// getting JSON string from URL
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Thread thread = new Thread()
{
#Override
public void run() {
try {
while(true) {
JSONObject json = jParser.getJSONFromUrl(url);
sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
//
finish();
}
}, 5000);
// JSONObject json = jParser.getJSONFromUrl(url);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
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);
///////////////////////////
Log.w("ID",id);
Log.w("Name",name);
Log.w("Email",email);
Log.w("Gender",gender);
Log.w("mobile",mobile);
Log.w("home",home);
Log.w("office",office);
Log.w("address",address);
///////////////////
// 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();
}
//
finish();
}
}, 5000);
// TODO Auto-generated method stub
}
}
this is the stack trace
10-04 06:39:24.830: D/dalvikvm(777): GC_FOR_ALLOC freed 15K, 4% free 4156K/4288K, paused 42ms, total 45ms
10-04 06:39:24.850: I/dalvikvm-heap(777): Grow heap (frag case) to 5.635MB for 1536016-byte allocation
10-04 06:39:25.040: D/dalvikvm(777): GC_FOR_ALLOC freed <1K, 3% free 5655K/5792K, paused 180ms, total 180ms
10-04 06:39:30.280: D/AndroidRuntime(777): Shutting down VM
10-04 06:39:30.280: W/dalvikvm(777): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
10-04 06:39:30.290: E/AndroidRuntime(777): FATAL EXCEPTION: main
10-04 06:39:30.290: E/AndroidRuntime(777): java.lang.NullPointerException
10-04 06:39:30.290: E/AndroidRuntime(777): at com.example.usa.Home$2.run(Home.java:105)
10-04 06:39:30.290: E/AndroidRuntime(777): at android.os.Handler.handleCallback(Handler.java:730)
10-04 06:39:30.290: E/AndroidRuntime(777): at android.os.Handler.dispatchMessage(Handler.java:92)
10-04 06:39:30.290: E/AndroidRuntime(777): at android.os.Looper.loop(Looper.java:137)
10-04 06:39:30.290: E/AndroidRuntime(777): at android.app.ActivityThread.main(ActivityThread.java:5103)
10-04 06:39:30.290: E/AndroidRuntime(777): at java.lang.reflect.Method.invokeNative(Native Method)
10-04 06:39:30.290: E/AndroidRuntime(777): at java.lang.reflect.Method.invoke(Method.java:525)
10-04 06:39:30.290: E/AndroidRuntime(777): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-04 06:39:30.290: E/AndroidRuntime(777): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-04 06:39:30.290: E/AndroidRuntime(777): at dalvik.system.NativeStart.main(Native Method)
10-04 06:39:34.957: D/dalvikvm(777): GC_FOR_ALLOC freed 261K, 6% free 6445K/6824K, paused 81ms, total 98ms
10-04 06:40:00.868: D/dalvikvm(777): GC_FOR_ALLOC freed 2688K, 36% free 5075K/7880K, paused 39ms, total 43ms
10-04 06:44:25.888: I/Process(777): Sending signal. PID: 777 SIG: 9
Here is the problem:
JSONObject json = jParser.getJSONFromUrl(url);
In the first thread you are retreiving data from URL and parsing it to json, soon after first thread, you are trying to retrieve data from JSON object, which most probably don't have any data because it is still busy in retrieving data.
So it is not a good idea. Retrieve and get data from JSON array in the same thread. This will save you alot of trouble.
Second you are storing the json parsed data in a local json object in the first thread instead of the global one and trying to use the null json object to get TAG_CONTACT data. This is causing NULL Pointer Exception
You have this line
JSONObject json = jParser.getJSONFromUrl(url);
but you also have a method variable json, which I think you are intending to use later.

Getting an error when connecting from android to PHP server

I have an android application project that connect to PHP server that I write it in codeigniter.
My JSONparser is:
package com.example.com.tourism;
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 method
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;
}
}
and my activity java code that connect to the server is
package com.example.com.tourism;
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.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.EditText;
public class SignUp extends Activity {
EditText first,last,birth ,pass;
private ProgressDialog pDialog;
private static String url_create_user = "http://10.0.2.2/tourism/index.php/site/register";
JSONParser jsonParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_up);
Button signUp=(Button)findViewById(R.id.sign_up);
first =(EditText) findViewById(R.id.edfname);
last =(EditText) findViewById(R.id.edlname);
pass =(EditText) findViewById(R.id.edpass);
signUp.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Createnewuser().execute();
}
});
}
class Createnewuser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SignUp.this);
pDialog.setMessage("Creating User..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = first.getText().toString();
String price = last.getText().toString();
String description = pass.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("first_name", name));
params.add(new BasicNameValuePair("last_name", price));
params.add(new BasicNameValuePair("password", description));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_user,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} 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 done
pDialog.dismiss();
}
}
and the error in log cat is
07-07 11:30:44.159: E/JSON Parser(20514): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
07-07 11:30:44.189: W/dalvikvm(20514): threadid=11: thread exiting with uncaught exception (group=0x40a71930)
07-07 11:30:44.229: E/AndroidRuntime(20514): FATAL EXCEPTION: AsyncTask #1
07-07 11:30:44.229: E/AndroidRuntime(20514): java.lang.RuntimeException: An error occured while executing doInBackground()
07-07 11:30:44.229: E/AndroidRuntime(20514): at android.os.AsyncTask$3.done(AsyncTask.java:299)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
07-07 11:30:44.229: E/AndroidRuntime(20514): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.lang.Thread.run(Thread.java:856)
07-07 11:30:44.229: E/AndroidRuntime(20514): Caused by: java.lang.NullPointerException
07-07 11:30:44.229: E/AndroidRuntime(20514): at com.example.com.tourism.SignUp$Createnewuser.doInBackground(SignUp.java:98)
07-07 11:30:44.229: E/AndroidRuntime(20514): at com.example.com.tourism.SignUp$Createnewuser.doInBackground(SignUp.java:1)
07-07 11:30:44.229: E/AndroidRuntime(20514): at android.os.AsyncTask$2.call(AsyncTask.java:287)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
07-07 11:30:44.229: E/AndroidRuntime(20514): ... 4 more
07-07 11:30:44.429: I/Choreographer(20514): Skipped 49 frames! The application may be doing too much work on its main thread.
07-07 11:30:44.779: I/Choreographer(20514): Skipped 222 frames! The application may be doing too much work on its main thread.
07-07 11:30:45.069: I/Choreographer(20514): Skipped 149 frames! The application may be doing too much work on its main thread.
07-07 11:30:45.369: I/Choreographer(20514): Skipped 194 frames! The application may be doing too much work on its main thread.
07-07 11:30:45.459: I/Choreographer(20514): Skipped 50 frames! The application may be doing too much work on its main thread.
07-07 11:30:46.019: E/WindowManager(20514): Activity com.example.com.tourism.SignUp has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40d743a8 V.E..... R.....ID 0,0-304,96} that was originally added here
07-07 11:30:46.019: E/WindowManager(20514): android.view.WindowLeaked: Activity com.example.com.tourism.SignUp has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40d743a8 V.E..... R.....ID 0,0-304,96} that was originally added here
07-07 11:30:46.019: E/WindowManager(20514): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
07-07 11:30:46.019: E/WindowManager(20514): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
07-07 11:30:46.019: E/WindowManager(20514): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
07-07 11:30:46.019: E/WindowManager(20514): at android.app.Dialog.show(Dialog.java:281)
07-07 11:30:46.019: E/WindowManager(20514): at com.example.com.tourism.SignUp$Createnewuser.onPreExecute(SignUp.java:75)
07-07 11:30:46.019: E/WindowManager(20514): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
07-07 11:30:46.019: E/WindowManager(20514): at android.os.AsyncTask.execute(AsyncTask.java:534)
07-07 11:30:46.019: E/WindowManager(20514): at com.example.com.tourism.SignUp$1.onClick(SignUp.java:57)
07-07 11:30:46.019: E/WindowManager(20514): at android.view.View.performClick(View.java:4204)
07-07 11:30:46.019: E/WindowManager(20514): at android.view.View$PerformClick.run(View.java:17355)
07-07 11:30:46.019: E/WindowManager(20514): at android.os.Handler.handleCallback(Handler.java:725)
07-07 11:30:46.019: E/WindowManager(20514): at android.os.Handler.dispatchMessage(Handler.java:92)
07-07 11:30:46.019: E/WindowManager(20514): at android.os.Looper.loop(Looper.java:137)
07-07 11:30:46.019: E/WindowManager(20514): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-07 11:30:46.019: E/WindowManager(20514): at java.lang.reflect.Method.invokeNative(Native Method)
07-07 11:30:46.019: E/WindowManager(20514): at java.lang.reflect.Method.invoke(Method.java:511)
07-07 11:30:46.019: E/WindowManager(20514): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-07 11:30:46.019: E/WindowManager(20514): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-07 11:30:46.019: E/WindowManager(20514): at dalvik.system.NativeStart.main(Native Method)
i don't know where the problem is, please help me
is my code incorrect ???
if any one have correct code please give it to me i am using codeigniter for php and this is the code that i call it above
function register_get()
{
$json = array('status' => false );
if($this->input->post()==null){
$this -> response($json, 200);
}
$firstname = $this->post("first_name");
$lastname = $this->post("last_name");
$password = $this->post("password");
if(!$firstname || !$lastname || !$password){
$json['status'] = "wrong insert";
$this -> response($json, 200);
}
$this->load->model('Data_model');
$result = $this->Data_model->search($firstname, $lastname);
if($result)
{
$this->Data_model->insert($firstname,$lastname,$password);
$json['status'] = true;
}
// here if false..
$this -> response($json, 200);
}
There are issues with your PHP. You are not passing back any JSON. You will need to change your script to encode your array into JSON.
$result = json_encode($json)
Returning the actual JSON will help. Make sure you are not returning any HTML either. Your Java is trying to parse a JSON response, but you are responding with <!DOCTYPE...

Having trouble connecting to webservice through android

I am currently having trouble connecting to my webservice on android. I am using a Jetty web service and building it using ANT. On my laptop it works perfectly and displays items from my database. However it won't seem to connect on my Android application. Attached is the code and LOGCAT report.
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class Android2Servlet extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dbtest);
TextView txtresp = (TextView)findViewById(R.id.servlet_response);
String url = "http://(MY LAPTOPS IP):8085/DB";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try{
System.out.println("About to execute");
HttpResponse response = client.execute(request);
String helpedResp=HttpUnpack.request(response);
System.out.println(helpedResp);
txtresp.setText(helpedResp);
System.out.println(response);
}catch(Exception ex){
txtresp.setText("Failed!");
ex.printStackTrace();
}
} }
The HTTP Unpack File
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
public class HttpUnpack {
public static String request(HttpResponse response){
String result = "";
try{ InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
}catch(Exception ex){
result = "Error retrieving response";
}
return result;
}
}
The HTTP Unpack and the Android2Servlet do not cause any errors, however the text box only returns "Failed!".
LOGCAT file
W/System.err(1282): android.os.NetworkOnMainThreadException
W/System.err(1282): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
W/System.err(1282): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
W/System.err(1282): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
W/System.err(1282): at libcore.io.IoBridge.connect(IoBridge.java:112)
W/System.err(1282): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
W/System.err(1282): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
W/System.err(1282): at java.net.Socket.connect(Socket.java:842)
W/System.err(1282): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
W/System.err(1282): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
W/System.err(1282): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
W/System.err(1282): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
W/System.err(1282): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
W/System.err(1282): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
W/System.err(1282): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
W/System.err(1282): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
W/System.err(1282): at myFood.myFood.Android2Servlet.onCreate(Android2Servlet.java:24)
W/System.err(1282): at android.app.Activity.performCreate(Activity.java:4465)
W/System.err(1282): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
W/System.err(1282): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
W/System.err(1282): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
W/System.err(1282): at android.app.ActivityThread.access$600(ActivityThread.java:123)
W/System.err(1282): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
W/System.err(1282): at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err(1282): at android.os.Looper.loop(Looper.java:137)
W/System.err(1282): at android.app.ActivityThread.main(ActivityThread.java:4424)
W/System.err(1282): at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err(1282): at java.lang.reflect.Method.invoke(Method.java:511)
W/System.err(1282): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
W/System.err(1282): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
W/System.err(1282): at dalvik.system.NativeStart.main(Native Method)
Any response would be greatly helpful.
Regards.
EDIT:
I have now removed the network access and put it in another Java class. And called it form another class. And it is still returning the same errors. Any other advice?
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class androidconnectors {
public static final String main(String args[]) throws Exception {
String txtresp = "";
try{
String url = "http://(LAPTOPS IP):8085/Hello";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
System.out.println("About to execute");
HttpResponse response = client.execute(request);
String helpedResp=HttpUnpack.request(response); // Http Unpack is not part of
System.out.println(helpedResp); // of HttpClient library
txtresp =(helpedResp);
System.out.println(response);
}catch(Exception ex){
ex.printStackTrace();
}
return txtresp;
}
}
And the android class.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Settings extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dbtest);
Button mybutton = (Button) findViewById(R.id.buttonpress);
mybutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
TextView txtresp = (TextView)findViewById(R.id.servlet_response);
String[] args = null;
try {
String x = androidconnectors.main(args);
txtresp.setText(x);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
txtresp.setText("Failed");
}
}
});
}
}
It would seem, based on a quick google search, that since Honeycomb you are not supposed to execute network access on your app's main thread (to improve responsiveness).
Create another thread for network access as suggested here.
You can't do Network Operations on the UI Thread better use AsyncTask/Service/IntentService
NetworkOnMainThreadException
The exception that is thrown when an application attempts to perform a
networking operation on its main thread.(Since API 11)
To resovled StrictMode issue you need to use below code in your activity -
static{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}

Categories