1

I'm getting a NullPointerException when I try to request a JSON with AsyncTask. I'm using loopj and AsyncTask

Here's my code:

 String str = null;   
    public class MainActivity extends Activity {
       @Override
       protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new TheTask().execute();
       }

       class TheTask extends AsyncTask<Void, Void, String> {
         @Override
         protected String doInBackground(Void... params)  {

          try{
            AsyncHttpClient client = new AsyncHttpClient();
            client.addHeader("Authorization", "Token token=Wa5sfwP3ku7c15qkZTsd**");
            client.get("http://*********.com/api/v1/***", new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(String response) {
                    str = response;
                   Log.v("==========RESULT==========", response); 
                }
             });
          } catch(Exception e){
             Log.v("========== ERROR ==========", e.toString());
          }
          return str;   
        }

        @Override
        protected void onPostExecute(String result) {
          TextView txt = (TextView) findViewById(R.id.textView1);
          txt.setText("Result: " + result);   
        }
       }
    }
8
  • 2
    where is your return statement in doInbackground?? Commented Mar 30, 2014 at 7:14
  • can you post the stacktrace please? Commented Mar 30, 2014 at 7:21
  • @Raghunandan updated my question. Is the onPostExecute means that the async is finished? Commented Mar 30, 2014 at 7:21
  • @Emmanuel java.lang.NullPointerException: println needs a message Commented Mar 30, 2014 at 7:22
  • @AllenChun Are you sure your webservice functions right? Commented Mar 30, 2014 at 7:23

1 Answer 1

3

You are doing it wrong. In your doInBackground() method you should use synchronous methods, and you are using asynchronous:

 client.get("http://*********.com/api/v1/***", new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(String response) {
                    str = response;
                   Log.v("==========RESULT==========", response); 
                }

That's why your doInBackground() returns null, and you are trying to deal with null in onPostExecute()

You should use methods from class SyncHttpClient from Loopj-Async library.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.