Java 检索json时出现NullPointerException

Java 检索json时出现NullPointerException,java,android,json,Java,Android,Json,我使用代码示例作为检索json值的方向。但在异步任务中,我得到一个NullPointer异常: Caused by: java.lang.NullPointerException at com.adrianopaulus.zusatzstoffe.MainActivity$LoadAllIngreds.doInBackground(MainActivity.java:119) at com.adrianopaulus.zusatzstoffe.MainActivi

我使用代码示例作为检索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;

    }
}
公共类JSONParser{
InputStream=null;
JSONObject jObj=null;
字符串json=“”;
//建造师
公共JSONParser(){
}
//函数从url获取json
//通过使用HTTP POST或GET方法
公共JSONObject makeHttpRequest(字符串url、字符串方法、,
列表参数){
//发出HTTP请求
试一试{
//检查请求方法
如果(方法==“POST”){
//请求方法为POST
//defaultHttpClient
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(url);
setEntity(新的UrlEncodedFormEntity(参数));
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}else if(方法==“GET”){
//请求方法是GET
DefaultHttpClient httpClient=新的DefaultHttpClient();
String paramString=URLEncodedUtils.format(params,“utf-8”);
url+=“?”+参数字符串;
HttpGet HttpGet=新的HttpGet(url);
HttpResponse HttpResponse=httpClient.execute(httpGet);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
试一试{
BufferedReader reader=新的BufferedReader(新的InputStreamReader(
is,“iso-8859-1”),8);
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
is.close();
json=sb.toString();
}捕获(例外e){
Log.e(“缓冲区错误”,“错误转换结果”+e.toString());
}
//尝试将字符串解析为JSON对象
试一试{
jObj=新的JSONObject(json);
}捕获(JSONException e){
Log.e(“JSON解析器”,“错误解析数据”+e.toString());
}
//返回JSON字符串
返回jObj;
}
}
其中,我的参数为0,get jObj返回值为null
如果需要我的异步任务:

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();
            }
        });
    }
}
类装入链接扩展异步任务{
受保护的void onPreExecute(){
super.onPreExecute();
//auf活性achten
iDialog=新建进度对话框(MainActivity.this);
iDialog.setMessage(“Lädt更新herunter.bite haben sie etwas Geduld…”);
iDialog.setUndeterminate(假);
iDialog.setCancelable(假);
iDialog.show();
}
//由于我们只访问数据库,TODO可能会使其无效
受保护的字符串doInBackground(字符串…args){
List params=new ArrayList();
JSONObject json=jParser.makeHttpRequest(url_get_new_value,“get”,params);
试一试{
//此处出错,因为json=null;
int success=Integer.parseInt(json.getString(TAG_success));
如果(成功==1){
//TODO将var名称更改为smth.with配料
配料=json.getJSONArray(标记配料);
int lengthRemoteDB=json.getInt(标记长度);
int lengthLocalDB=dbHandler.getZusatzCount();
如果(lengthRemoteDB>lengthLocalDB){
//对于(int i=0;i<5;i++){
//JSONObject c=配料。getJSONObject(i);
//获取JSON值
JSONArray id=components.getJSONObject(0).getJSONArray(TAG_id);
JSONArray名称=配料。getJSONObject(1)。getJSONArray(标记名称);
JSONArray eName=配料.getJSONObject(2).getJSONArray(TAG_eName);
JSONArray原因=配料。getJSONObject(3)。getJSONArray(标记原因);
JSONArray danger=配料。getJSONObject(4)。getJSONArray(标记危险);
//TODO询问长度
对于(int i=lengthLocalDB;i//TODO create方法能够在DB中插入启动的位置?JPARSER只需在
int success…
line之前发布日志中显示错误的部分(如20行左右…),然后写入
log.v(“json”,“json here=“+json”);
并告诉我们您得到了什么。同时说明您正在使用的JSON解析器的名称。Jackson、Gson或哪一个?检查您的代码,
JSONParser
是您的自定义类。我相信JSON接收不正确,或者您在解析时出错。在
makeHttpRequest()中
您能检查一下在执行操作的块中得到了什么吗
BufferedReader reader=new BufferedReader(新的InputStreamReader(is,“iso-8859-1”),8);
.Als
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)