2

So, I'm writing an android app. During OnCreate() of an activity, I request some JSONObjects via HTTP GET. That method has a response listener that, well, does something when it gets a JSONObject. In the OnCreate-method, I need to use the response, so can I somehow set it up so that the OnCreate method waits until the response listener does it's job? Do I have to use multithreading? Here's the code I'm talking about:

Here's the call in OnCreate():

...
// Instantiate the RequestQueue.
final RequestQueue queue = Volley.newRequestQueue(this);
executeJson(QUERY_URL);

System.out.println(jsonresponse);
...

Here's the called method:

private void executeJson(String url) {
    SharedPreferences prefs = this.getSharedPreferences("AppPref", MODE_PRIVATE);
    final String token = prefs.getString("token", null);
    RequestQueue queue = Volley.newRequestQueue(this);
    Map<String, String> params = new HashMap<String, String>();
    System.out.println(token);
    params.put("access_token", token);
    CustomRequest jsonRequest = new CustomRequest(url, params,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    jsonresponse = response;
                }
            }, this.createRequestErrorListener());
    System.out.println(jsonRequest);
    queue.add(jsonRequest);
}

I realize that a simple Thread.Sleep() would, well, make my app go to sleep entirely, so that can't be the solution.

The intention of this activity is to be a "Loading Activity" - It pops up once the user wants to access his data and creates an intent to the data activity, destroying itself after the data is loaded.

FuriousFry
  • 181
  • 1
  • 2
  • 12
  • I see you're using Volley. Why not take a look at `RequestFuture` class. It is the same as `Request` but can be done `synchronously`; as in further code below it won't run until the response or timeout. Please PLEASE do not block the UI thread with this. EDIT: Like... http://stackoverflow.com/a/17035421/3309883 – Unknownweirdo Aug 07 '15 at 16:25
  • Okay, as I realized I didn't specify what the intention of this activity was, I edited the original post. – FuriousFry Aug 07 '15 at 16:52

1 Answers1

0

Yes, you need to do the request in a background thread. Use an AsyncTask, or other method. You do not want to do an arbitrarily long running request on the UI thread, nor 'pause' the UI thread to wait for the request to return. Read Android Processes and Threads for more info using threads in Android.

Craig
  • 311
  • 4
  • 12
  • Okay, thanks for your help. However, the doInBackGround of the AsyncTask requires a return Statement, which I can not provide until the listener got its object. I have to wait for it to get a response before I can return something. – FuriousFry Aug 07 '15 at 16:19