应用程序没有响应,然后在尝试使用名称字段从数据库中获取数据时崩溃



我试图创建一个从 url 获取 json 对象的应用程序。事实证明,这是不必要的令人沮丧的,因为它不断崩溃应该加载和解析 json 对象的活动。它只是弹出消息"不幸的是,(AppName(已停止",然后退出应用程序。来自 JSON 的数据永远不会显示在屏幕上。下面是包含活动和 JSON 解析

的代码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;
}
}

日志猫中的错误

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)

名称搜索显示活动.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();
}

}
}

检查该方法是 POST 还是 GET 使用 Chrome 中的 Postman 扩展程序。 并使用特定方法获取数据。

邮递员扩展链接

最新更新