1

I am trying to pass some JSONObject data back from my AsyncTask.OnPostExecute to my MainActivity.JSONCallBackComplete.

My problem is when I attempt to check my passed-back JSONObject I get the following execption:

10-14 18:40:25.820: E/AndroidRuntime(4153): FATAL EXCEPTION: main
10-14 18:40:25.820: E/AndroidRuntime(4153): java.lang.NullPointerException
10-14 18:40:25.820: E/AndroidRuntime(4153):     at com.icerge.revivaltimes.MainActivity.JSONCallBackComplete(MainActivity.java:31)
10-14 18:40:25.820: E/AndroidRuntime(4153):     at com.icerge.revivaltimes.JsonObj.onPostExecute(JsonObj.java:70)
10-14 18:40:25.820: E/AndroidRuntime(4153):     at com.icerge.revivaltimes.JsonObj.onPostExecute(JsonObj.java:1)
10-14 18:40:25.820: E/AndroidRuntime(4153):     at android.os.AsyncTask.finish(AsyncTask.java:417)
10-14 18:40:25.820: E/AndroidRuntime(4153):     at android.os.AsyncTask.access$300(AsyncTask.java:127)
10-14 18:40:25.820: E/AndroidRuntime(4153):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
10-14 18:40:25.820: E/AndroidRuntime(4153):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-14 18:40:25.820: E/AndroidRuntime(4153):     at android.os.Looper.loop(Looper.java:144)
10-14 18:40:25.820: E/AndroidRuntime(4153):     at android.app.ActivityThread.main(ActivityThread.java:4937)
10-14 18:40:25.820: E/AndroidRuntime(4153):     at java.lang.reflect.Method.invokeNative(Native Method)
10-14 18:40:25.820: E/AndroidRuntime(4153):     at java.lang.reflect.Method.invoke(Method.java:521)
10-14 18:40:25.820: E/AndroidRuntime(4153):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
10-14 18:40:25.820: E/AndroidRuntime(4153):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
10-14 18:40:25.820: E/AndroidRuntime(4153):     at dalvik.system.NativeStart.main(Native Method)

My MainActivity class is as follows:

public class MainActivity extends Activity{

        private JSONObject jsonData = null;

        public void JSONCallBackComplete(JSONObject jsonData){
            this.jsonData = jsonData;
            Log.e("TESTing in callback: ", jsonData.toString()  );
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            new JsonObj(this).execute("http://myserver/json");
         }
    }

And my AsyncTask class is as follows:

public class JsonObj extends AsyncTask<String, Void, JSONObject>{
    MainActivity activity;
    int tid;
    String term;

    public JsonObj(MainActivity activity){
        this.activity = activity;
//      Log.e("TESTING: ", activity.getClass().toString());
    }

    @Override
    protected JSONObject doInBackground(String... url) {
        // TODO Auto-generated method stub
        DefaultHttpClient   httpclient = new DefaultHttpClient(new BasicHttpParams());
        HttpPost httppost = new HttpPost(url[0]);
        JSONObject jsonObject = null;
        // Depends on your web service
        httppost.setHeader("Content-type", "application/json");

        InputStream inputStream = null;
        String result = null;
        try {
            HttpResponse response = httpclient.execute(httppost);           
            HttpEntity entity = response.getEntity();

            inputStream = entity.getContent();
            // json is UTF-8 by default
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null){
                sb.append(line + "\n");
            }
            result = sb.toString();
            Log.e("JSON-Test [RESULT]: ", result);
            jsonObject = new JSONObject(result);
        } catch (Exception e) { 
            Log.e("JSON-Test [exception]: ", e.toString());
        }
        finally {
            try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
        }

        return jsonObject;
    }

    @Override
protected void onPostExecute(JSONObject result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);
    if( !result.equals(null) ){
        this.activity.JSONCallBackComplete(result);
    }
}
}

I have a constructor in the AsyncTask assigning the MainActivity-Context and using it to call my JSONCallBackComplete feedback function with the JSONObject argument.

However, instead of displaying my JSON-DATA, I get the exception I pasted above.

halfer
  • 19,824
  • 17
  • 99
  • 186
sisko
  • 9,604
  • 20
  • 67
  • 139
  • it seems to me that line 31 of `MainActivity` is null are you sure your jsonData object is not null when it get back there? – tyczj Oct 14 '13 at 19:29
  • Is `result` `null` in `onPostExecute()`? – codeMagic Oct 14 '13 at 19:29
  • I have performed a '.equals(NULL)' check in both relevant places but the nullpointer-exception persists. My code is updated to show the check in the onPostExecute function – sisko Oct 14 '13 at 19:47
  • Before you `return jsonObject;` try to print it. – wtsang02 Oct 14 '13 at 19:50
  • @wtsang02: same problem. The first occurence of JSONObject ( if( !result.equals(null) ){ ... ) throws a nullpointer-exception – sisko Oct 14 '13 at 20:00
  • @SargeBorsch AsycTasks deprecated? From when? I dont see anything in developer site. – prijupaul Oct 14 '13 at 21:47
  • @prijupaul http://stackoverflow.com/a/8045489/1418097 – Display Name Oct 15 '13 at 04:39
  • 1
    @SargeBorsch AsyncTask is not deprecated :). Its on onRetainConfigurationInstance which is deprecated. And sisko is not using the function to retain the previous state. – prijupaul Oct 15 '13 at 05:01

1 Answers1

1

You're having NullPointerExceptions. The first one I'm seeing is coming from here

if(!result.equals(null) ){

This should actually be

if (result != null) {

You shouldn't really use .equals() to compare to null, because .equals() is usually implemented to check if the human perceived values of 2 objects are the same, not memory address. When you want to compare something to the null memory address, just use the direct == or !=, where Java will compare the addresses for you (what you want).

bclymer
  • 6,679
  • 2
  • 27
  • 36
  • Thank you. I corrected my result check accordingly but my if-statement is not firing. It likely means no data is being sent from my doInBackground function OR something-else I'm not seeing – sisko Oct 14 '13 at 23:44
  • It's likely your network request is failing. See what your StringBuilder `sb` is after you finish appending to it. – bclymer Oct 15 '13 at 01:14
  • The string builder in the doInBackground function has all the data fetched from the server. It correctly print the JSON data – sisko Oct 16 '13 at 03:28