0

I am using this code example, as orientation to retrieve json values. But in the async task, I get an NullPointer Exception:

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)

, while trying to retrieve a value.
Running the debugger, It starts my JSONParser class:

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;

    }
}

In it, my params is 0, and get jObj returned with value null.
In case needed my 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();
            }
        });
    }
}

Edit more of the Log:

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)
Adrian
  • 360
  • 1
  • 11
  • 21
  • where is that initiated? jParser – nano_nano Feb 18 '15 at 13:56
  • Just post the part of the log that displays error (like 20 lines or so...) – miselking Feb 18 '15 at 13:57
  • in the Activity: 'JSONParser jParser = new JSONParser();' in the Debugger it is going into the class. – Adrian Feb 18 '15 at 13:58
  • possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Jens Feb 18 '15 at 13:58
  • ok then show makeHttpRequest code – nano_nano Feb 18 '15 at 13:58
  • @StefanBeike if I am not mistaking, should be in the JSONParser class. – Adrian Feb 18 '15 at 14:06
  • I hope you actually have "success" tag in your PHP that you are checking. – miselking Feb 18 '15 at 14:07
  • Are there any your error-logs? – DmitryKanunnikoff Feb 18 '15 at 14:07
  • @miselking it is existent, but even if not, my var json is null, so it would throw an exception anyway. – Adrian Feb 18 '15 at 14:10
  • Then, I guess the only way to figure out where there error lies, is to debug the `JSONParser` class (wheb you call `makeHttpRequest` and check if there are any exceptions there or whatsoever)... – miselking Feb 18 '15 at 14:14
  • the AsyncTask hides the exactly position of the exception. I think "is" is null and because of this you get an NPE here: BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); or here: is.close(); – nano_nano Feb 18 '15 at 14:40
  • 1
    Before the `int success...` line, write `Log.v("json", "json here=" + json);` and tell us what you get. Also state the name of JSON parser you're using. Jackson, Gson or which one? – Sufian Feb 18 '15 at 14:45
  • @StefanBeike i will check with the debugger – Adrian Feb 18 '15 at 18:14
  • @StefanBeike is shown like this in the debugger: is = {org.apache.http.conn.EofSensorInputStream@41cd5370} – Adrian Feb 18 '15 at 18:37
  • @Sufian the Log returns json here= null, I am actually not sure what JSONParser I am using, I used the one described in the tutorial, linked in my question. But I posted the code in the question. – Adrian Feb 18 '15 at 18:44
  • 1
    Checked your code, `JSONParser` is your custom class. I believe the JSON is not received properly or you're making a mistake in parsing. In your `makeHttpRequest()` can you check what you get in the block where you do `BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);`. Also can you post complete Logcat? As you can see `makeHttpRequest` logs a lot of errors and if it's failing, you have to show us that part too. – Sufian Feb 19 '15 at 06:31
  • @Sufian I now added complete error log. After the requested block, I get the following value: reader = {java.io.BufferedReader@830032643552} – Adrian Feb 19 '15 at 13:46
  • 1
    `JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of`. It appears that you are getting empty response from server. Have you tested the webservice with tools like Chrome's extension "POSTman"? – Sufian Feb 19 '15 at 14:26
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/71261/discussion-between-adrian-and-sufian). – Adrian Feb 19 '15 at 14:27

0 Answers0