从AsyncTask的返回JSON数组 [英] Return JSON Array from AsyncTask

查看:220
本文介绍了从AsyncTask的返回JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有得到JSON数组的AsyncTask。我怎么会返回JSON数组是这样的:

  JSONArray渠道=新的JSON()执行(富,吧);包com.example.tvrplayer;

ECLIPS告诉我,我不能做到这一点,它应该是:

 的AsyncTask<对象,整型,JSONArray>渠道=新的JSON()执行(http://192.168.2.136:8080/rest/channel/+的linkID +/+用户名,GET)。

JSON的异步类:

 公共类的Json扩展的AsyncTask<对象,整型,JSONArray> {    JSON(){
        超();
    }    @覆盖
    保护JSONArray doInBackground(对象... PARAMS){
        // Log.i(JSON,URL);
        字符串URL =(字符串)PARAMS [0];
        字符串的方法=(字符串)PARAMS [1];
        InputStream为= NULL;
        字符串结果=;
        JSONArray JSONObject的= NULL;        // HTTP
        尝试{
            HttpClient的HttpClient的=新DefaultHttpClient(); //为80端口的请求!
            如果(方法==GET){
                HTTPGET HTTPGET =新HTTPGET(URL);
                HTT presponse响应= httpclient.execute(HTTPGET);
                HttpEntity实体= response.getEntity();
                是= entity.getContent();
            }否则如果(方法==POST){
                HttpPost httppost =新HttpPost(URL);
                HTT presponse响应= httpclient.execute(httppost);
                HttpEntity实体= response.getEntity();
                是= entity.getContent();
            }
        }赶上(例外五){
            Log.e(JSON - 1 - ,e.toString());
            返回null;
        }        //读取响应字符串
        尝试{
            读者的BufferedReader =新的BufferedReader(新的InputStreamReader(是,UTF-8),8);
            StringBuilder的SB =新的StringBuilder();
            串线= NULL;
            而((行= reader.readLine())!= NULL){
                sb.append(行+\\ n);
            }
            is.close();
            结果= sb.toString();
//结果= result.substring(1,result.length() - 1);
// Log.d(JSON结果,结果);
        }赶上(例外五){
            Log.e(JSON - 2 - ,e.toString());
            返回null;
        }        //字符串转换为对象
        尝试{
            的JSONObject =新JSONArray(结果);
        }赶上(JSONException E){
            Log.e(JSON - 3 - ,e.toString());
            返回null;
        }
        返回的JSONObject;
    }
    @覆盖
    保护无效onPostExecute(JSONArray结果)
    {
        super.onPostExecute(结果);
        最后的消息味精=新的Message();
        msg.obj =结果;
    }
}

这就是我试着做到:

  JSONArray渠道=新的JSON()执行(http://192.168.2.136:8080/rest/channel/+的linkID +/+用户名,GET );
        尝试{
            的for(int i = 0; I< channels.length();我++){
                JSONObject的channel_data = channels.getJSONObject(I)
                。字符串的channelID = channel_data.getString(渠道ID)与toLowerCase();
                JSONArray JSON =新的JSON()执行(http://192.168.2.136:8080/rest/program/+的linkID +/+用户名+/+的channelID,GET)。


解决方案

您不要收益的AsyncTask 。您指示的AsyncTask 称它是前一天做的东西,但不会收益来你任何东西。这就是为什么它被称为异步:你不等待它,它不会等你。

例如,借此code以 SyncTask

 结果= SyncTask();
label.setText(结果);

这意味着的setText()将不会被执行 SyncTask()完成,并产生一个结果。这是同步的。相反,随着异步,你做的:

 新的AsyncTask(){
    @覆盖
    无效onPostExecute(结果){
        label.setText(结果)
    }
}。开始()

这带来了一个全新的世界麻烦。我建议你​​先看看装载机,这同样的工作,但提供更强的抽象。

另外,我要告诉你的事实,这意味着有很多事情,你不明白。您可能希望谷歌了相关文件,教程和文章。

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");

解决方案

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.

这篇关于从AsyncTask的返回JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆