Im trying to create an app that gets a json object from a url. This is proving to be unnecessarily frustrating as it keeps crashing on the activity that is supposed to load and parse the json object. It just pops up the message "Unfortunately, (AppName) has stopped." and then exits the application. The data from the JSON is never shown on the screen. Here is the code with the activity and the JSON parsing
JSONParser.class
package com.example.android.andrtest1;
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.equals("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.equals("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 (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).append("\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 getJSONFromUrl(String url_create_product,
List<NameValuePair> params) {
// TODO Auto-generated method stub
return null;
}
}
Error in Logcat
06-11 15:18:32.448 17200-17200/com.example.android.andrtest1 E/Buffer Error: Error converting result java.lang.NullPointerException: lock == null
06-11 15:18:32.451 17200-17200/com.example.android.andrtest1 E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of
06-11 15:18:32.456 17200-17200/com.example.android.andrtest1 D/AndroidRuntime: Shutting down VM
06-11 15:18:32.457 17200-17200/com.example.android.andrtest1 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.andrtest1, PID: 17200
java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONObject.getInt(java.lang.String)' on a null object reference
at com.example.android.andrtest1.NameSearchDisplayActivity$GetProductDetails$1.run(NameSearchDisplayActivity.java:91)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5651)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
NameSearchDisplayActivity.class
package com.example.android.andrtest1;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import junit.framework.Assert;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class NameSearchDisplayActivity extends Activity {
TextView empnameview;
TextView empcugview;
TextView emprailphnview;
TextView empdesigview;
TextView empresipnview;
String empname;
ProgressDialog pDialog;
JSONParser jsonParser=new JSONParser();
private static final String url_product_details = "http://192.168.116.1/serdb1.0/get_employee_details.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
//private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_CUG = "CUG";
private static final String TAG_RAILWAY_PHN = "railway_phone";
private static final String TAG_DESIGNATION = "designation";
private static final String TAG_RESIDENCE_PN = "residence_pn";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.namesearch_display);
// getting product details from intent
Intent i = getIntent();
// getting name from intent
empname = i.getStringExtra(NameSearchDisplayActivity.TAG_NAME);
// Getting complete product details in background thread
new GetProductDetails().execute();
}
private class GetProductDetails extends AsyncTask<String, String, JSONObject> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NameSearchDisplayActivity.this);
pDialog.setMessage("Loading employee details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected JSONObject doInBackground(String... args) {
if(pDialog!=null)
pDialog.dismiss();
// Check for success tag
JSONObject product=null;
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", empname));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json;
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
product = productObj.getJSONObject(0);
}
else {
}// product with pid not found
} catch (JSONException e) {
e.printStackTrace();
}
return product;
}
protected void onPostExecute(JSONObject product) {
// Edit Text
try{
empnameview = (TextView) findViewById(R.id.namevalueview);
empcugview = (TextView) findViewById(R.id.cugvalueview);
emprailphnview = (TextView) findViewById(R.id.railphnvalueview);
empdesigview = (TextView) findViewById(R.id.desigvalueview);
empresipnview = (TextView) findViewById(R.id.resipnvalueview);
// display product data in EditText
empcugview.setText(product.getString(TAG_CUG));
emprailphnview.setText(product.getString(TAG_RAILWAY_PHN));
empdesigview.setText(product.getString(TAG_DESIGNATION));
empresipnview.setText(product.getString(TAG_RESIDENCE_PN));}
catch (JSONException e) {
e.printStackTrace();
}
// dismiss the dialog once got all details
if(pDialog != null)
pDialog.dismiss();
}
}
}
Check whether the method is POST or GET using Postman extension in Chrome. and Use the specific method to get the data.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.