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");
Harry
  • 13,091
  • 29
  • 107
  • 167
  • I can't get you...what do you want ... – Pragnani Feb 21 '13 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. – njzk2 Feb 21 '13 at 15:58
  • I want to get the JSON array back, so that channels = the jsonObject – Harry Feb 21 '13 at 15:59
  • @njzk2, then how do I get the result back of the onPostExecute? – Harry Feb 21 '13 at 16:00

3 Answers3

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.

salezica
  • 74,081
  • 25
  • 105
  • 166
  • thanks, I started with android dev on monday, so yes, there is ALLOT i dont understand yet. – Harry Feb 21 '13 at 16:01
  • @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. – salezica Feb 21 '13 at 16:04
  • Please se my update, thats what Im trying. What do you suggest I do then? this code I added is inside a asyncTask – Harry Feb 21 '13 at 16:06
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;
silwar
  • 6,470
  • 3
  • 46
  • 66
0

execute(Runnable runnable) from Asynctask returns void.

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

channels = result; doSomething(channels)

Dany Pop
  • 3,590
  • 2
  • 21
  • 28