0

I want to get some JSON code from my API. I wish to do something like this in the OnCreate:

try
{  
   String jsonstr = getSomeThingAndPauseAndroid("http://someplace.com/api/xyz");
   if (!jsonstr.isEmpty()) JSONObject jsonobj = new JSONObject(jsonstr);
}
catch { // handle error }

But when it happens, Android just go doing stuff and don't wait for the request to complete and response and I get nothing on jsonstr.

Is there some way to do that not needing a lot of new class files?

NaN
  • 8,596
  • 20
  • 79
  • 153

1 Answers1

1

The correct way to do this is to make the request asynchronously and trigger a method on response. This is an example using Google's Volley:

 //Start volley:
 RequestQueue queue = Volley.newRequestQueue(this);  // this = context


 final String url = "http://someplace.com/api/xyz"";

 // prepare the Request
 JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
     new Response.Listener<JSONObject>() 
     {
         @Override
         public void onResponse(JSONObject response) {   
             //This is where you setup your UI
             //Remember to dismiss the ProgressDialog
         }
     }, 
     new Response.ErrorListener() 
     {
          @Override
          public void onErrorResponse(VolleyError error) {            
             //Remember to dismiss the ProgressDialog
             Log.d("Error.Response", response);
        }
     }
 );

 // add it to the RequestQueue   
 //Here you should add a ProgressDialog so the user knows to wait
 queue.add(getRequest);
Mika
  • 5,807
  • 6
  • 38
  • 83
  • So there's no way of doing that what I want, which I could make on any other OS but not in Android?... – NaN May 30 '14 at 17:08
  • Yes there is. The code I am giving you does just that but following best practice. The same, by the way, is true on iOS network requests should always be done asynchronously regardless of the platform. – Mika May 30 '14 at 17:11
  • Where can I download this jar? – NaN May 30 '14 at 17:50
  • Just simply open your `build.gradle` file in android studio and add in the dependencies: `compile 'com.mcxiaoke.volley:library-aar:1.0.+` that's it! – Mika May 30 '14 at 18:09
  • does it work for intellijIdea 13? I downloaded the jar file and the ide just went buggy with `Negative Time` log errors and didn't load the `src` package. – NaN May 31 '14 at 10:34
  • I have no idea. I use android studio and all I have to do is add one line to the build.gradle file. No need to play with jar files. – Mika Jun 02 '14 at 09:08