2

I have an AsyncTask that gets a JSON Array. How would I return the JSON array like this:

JSONArray channels = new Json().execute(foo, bar);package com.example.tvrplayer;

Eclips tells me I cant do that, it should be:

AsyncTask<Object, Integer, JSONArray> channels = new Json().execute("http://192.168.2.136:8080/rest/channel/"+ linkid +"/"+ username, "GET");

The Json Async Class:

public class Json extends AsyncTask<Object, Integer, JSONArray> {

    Json(){
        super();
    }

    @Override
    protected JSONArray doInBackground(Object... params) {
        // Log.i("JSON",url);
        String url = (String) params[0];
        String method = (String) params[1];
        InputStream is = null;
        String result = "";
        JSONArray jsonObject = null;

        // HTTP
        try {
            HttpClient httpclient = new DefaultHttpClient(); // for port 80 requests!
            if ( method == "GET") {
                HttpGet httpget = new HttpGet(url);
                HttpResponse response = httpclient.execute(httpget);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
            } else if (method == "POST") {
                HttpPost httppost = new HttpPost(url);
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
            }


        } catch(Exception e) {
            Log.e("JSON - 1 -", e.toString());
            return null;
        }

        // Read response to string
        try {           
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();    
//          result = result.substring(1,result.length()-1);
//          Log.d("JSON result",result);
        } catch(Exception e) {
            Log.e("JSON - 2 -", e.toString());
            return null;
        }

        // Convert string to object
        try {
            jsonObject = new JSONArray(result);            
        } catch(JSONException e) {
            Log.e("JSON - 3 -", e.toString());
            return null;
        }
        return jsonObject;
    }
    @Override
    protected void onPostExecute(JSONArray result)
    {
        super.onPostExecute(result);
        final Message msg = new Message();
        msg.obj = result;
    }
}

this is what Im trying to accomplish:

JSONArray channels = new Json().execute("http://192.168.2.136:8080/rest/channel/"+ linkid +"/"+ username, "GET");
        try {
            for (int i=0; i < channels.length(); i++) { 
                JSONObject channel_data = channels.getJSONObject(i);
                String channelID = channel_data.getString("ChannelID").toLowerCase();
                JSONArray json = new Json().execute("http://192.168.2.136:8080/rest/program/"+ linkid +"/"+ username +"/" + channelID, "GET");
4
  • I can't get you...what do you want ... Commented Feb 21, 2013 at 15:58
  • asynctask, as the name suggests, is asynchronous. it means it cannot return a result immediatly (which would be synchronous, see?). you have to wait until onPostExecute to receive something. execute() is not intended to return anything. Commented Feb 21, 2013 at 15:58
  • I want to get the JSON array back, so that channels = the jsonObject Commented Feb 21, 2013 at 15:59
  • @njzk2, then how do I get the result back of the onPostExecute? Commented Feb 21, 2013 at 16:00

3 Answers 3

3

You don't return from AsyncTask. You instruct the AsyncTask to do stuff before calling it a day, but it won't return to you with anything. This is why it's called "asynchronous": you don't wait for it, it doesn't wait for you.

For example, take this code with a SyncTask:

result = SyncTask();
label.setText(result);

That implies that the setText() line won't be executed until SyncTask() is done and yields a result. It's synchronous. Instead, with async, you do:

new AsyncTask() {
    @Override
    void onPostExecute(result) {
        label.setText(result)
    }
}.start()

This brings in a whole new world of trouble. I recommend you take a look at Loaders, which work similarly but provide a stronger abstraction.

Also, the fact that I'm telling you this means that there's a lot going on that you don't understand. You may want to google up relevant documentation, tutorials or articles.

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

3 Comments

thanks, I started with android dev on monday, so yes, there is ALLOT i dont understand yet.
@Harry patience then :) this is a particularly hairy subject. I do mean it. Older versions of Android (which run most of today's phones) have a very poor API for asynchronous work. The Android Support Library ports a lot of modern features to older platforms, you'll find better tools there.
Please se my update, thats what Im trying. What do you suggest I do then? this code I added is inside a asyncTask
1

You dont have to return anything from ASyncTask

@Override
protected void onPostExecute(JSONArray result)
{
    super.onPostExecute(result);
    channels = result
    //<here you can use channels to integrate with other code>
}

Here channels will be declared as Class variable

 JSONArray channels;

Comments

0

execute(Runnable runnable) from Asynctask returns void.

Assign your result in onPostExecute() , something like this :

channels = result; doSomething(channels)

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.