我正在使用this代码示例,作为检索json值的方向。但在异步任务中,我得到一个NullPointer异常:
Caused by: java.lang.NullPointerException
at com.adrianopaulus.zusatzstoffe.MainActivity$LoadAllIngreds.doInBackground(MainActivity.java:119)
at com.adrianopaulus.zusatzstoffe.MainActivity$LoadAllIngreds.doInBackground(MainActivity.java:101)
,同时尝试检索值。
运行调试器,它启动我的JSONParser类:
public class JSONParser {
InputStream is = null;
JSONObject jObj = null;
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;
}
}
在其中,我的参数为0,并返回值为null的jObj。
如果需要我的AsyncTask:
class LoadAllIngreds extends AsyncTask<String, String, String>{
protected void onPreExecute(){
super.onPreExecute();
//auf Activity achten
iDialog = new ProgressDialog(MainActivity.this);
iDialog.setMessage("Lädt update herunter. Bitte haben sie etwas Geduld...");
iDialog.setIndeterminate(false);
iDialog.setCancelable(false);
iDialog.show();
}
//TODO maybe make void since we only access DB
protected String doInBackground(String... args){
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_get_new_values, "GET", params);
try {
//error here since json = null;
int success = Integer.parseInt(json.getString(TAG_SUCCESS));
if (success == 1){
//TODO change var name to smth. with ingredients
ingredients = json.getJSONArray(TAG_INGREDIENTS);
int lengthRemoteDB = json.getInt(TAG_LENGTH);
int lengthLocalDB = dbHandler.getZusatzCount();
if (lengthRemoteDB > lengthLocalDB) {
//for (int i = 0; i < 5; i++) {
//JSONObject c = ingredients.getJSONObject(i);
//getting JSON values
JSONArray id = ingredients.getJSONObject(0).getJSONArray(TAG_ID);
JSONArray name = ingredients.getJSONObject(1).getJSONArray(TAG_NAME);
JSONArray eName = ingredients.getJSONObject(2).getJSONArray(TAG_ENAME);
JSONArray causes = ingredients.getJSONObject(3).getJSONArray(TAG_CAUSES);
JSONArray danger = ingredients.getJSONObject(4).getJSONArray(TAG_DANGER);
//TODO ask for length
for (int i = lengthLocalDB; i < lengthRemoteDB; i++) {
if (dbHandler.getZusatz(i) == null) {
Zusatzstoffe zusatzstoffe = new Zusatzstoffe(Integer.parseInt(String.valueOf(id.getJSONObject(i))),
String.valueOf(name.getJSONObject(i)), String.valueOf(eName.getJSONObject(i)),
String.valueOf(causes.getJSONObject(i)), Integer.parseInt(String.valueOf(danger.getJSONObject(i))));
dbHandler.createZusatz(zusatzstoffe);
//TODO create method to be able to insert in DB <- done
//TODO put values in local DB <- done
//TODO in remote section -> create new table with update, and changed id's <-- probably take easier way, just see id difference (not sure)
//TODO in here -> pull only new data
}else {
Log.e("DB asyncTask", "ID besetzt");
}
}
}
}
}catch (JSONException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url){
iDialog.dismiss();
runOnUiThread(new Runnable() {
@Override
public void run() {
populateList();
}
});
}
}
编辑更多日志:
02-18 19:41:38.015 707-721/com.adrianopaulus.zusatzstoffe E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
02-18 14:51:05.257 1069-1082/com.adrianopaulus.zusatzstoffe E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NullPointerException
at com.adrianopaulus.zusatzstoffe.MainActivity$LoadAllIngreds.doInBackground(MainActivity.java:119)
at com.adrianopaulus.zusatzstoffe.MainActivity$LoadAllIngreds.doInBackground(MainActivity.java:101)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
02-18 19:41:39.846 707-707/com.adrianopaulus.zusatzstoffe E/WindowManager﹕ Activity com.adrianopaulus.zusatzstoffe.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@41c9bf48 that was originally added here
android.view.WindowLeaked: Activity com.adrianopaulus.zusatzstoffe.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@41c9bf48 that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
at android.view.Window$LocalWindowManager.addView(Window.java:547)
at android.app.Dialog.show(Dialog.java:277)
at com.adrianopaulus.zusatzstoffe.MainActivity$LoadAllIngreds.onPreExecute(MainActivity.java:109)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.adrianopaulus.zusatzstoffe.MainActivity.onCreate(MainActivity.java:87)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)