android-从AsyncTask获取返回的JSON

android-从AsyncTask获取返回的JSON,第1张

概述因此,我有这个加载程序类,它扩展了AsyncTask.然后我做新的loader().execute();但是我想使用我的加载程序类返回的JSONArray响应,该怎么做?因为我在几个不同的地方需要它?还是我应该将代码移至onPostExecute并在那里执行所有 *** 作?publicclassloaderextendsAsyncTask<String,Inte

因此,我有这个加载程序类,它扩展了AsyncTask.然后我做新的loader().execute();但是我想使用我的加载程序类返回的JSONArray响应,该怎么做?因为我在几个不同的地方需要它?还是我应该将代码移至onPostExecute并在那里执行所有 *** 作?

public class loader extends AsyncTask<String, Integer, JsONArray> {    ProgressDialog dialog;    protected voID onPreExecute() {        dialog = ProgressDialog.show(ChallengeList.this, "", "Laddar...");        dialog.setCancelable(true);    }    @OverrIDe    protected JsONArray doInBackground(String... params) {    JsONArray response = null;    httpClIEnt clIEnt = new DefaulthttpClIEnt();    httpPost httppost = new httpPost(ListURL);    try {        httpResponse resp = clIEnt.execute(httppost);        Statusline statusline = resp.getStatusline();        int statusCode = statusline.getStatusCode();        Log.i("Statuscode", "statusCode"+statusCode);        if (statusCode == 200) {            final JsONObject Json = new JsONObject();            Json.put("userID", prefs.ID());            response = Sendhttp.parsehttp(ListURL, Json);        }    } catch (JsONException e1) {        e1.printstacktrace();    } catch (IOException e1) {        e1.printstacktrace();    }         return response;    }    protected voID onPostExecute(JsONArray result) {        dialog.dismiss();    }}

解决方法:

方法onPostExecute具有您从doInBackground方法返回的JsONArray作为参数.

onPostExecute在主(调用方)活动的线程上运行,因此,除了关闭该方法中的对话框之外,您还可以进一步处理结果数组,并将其安全地传递给其他方法,等等:

@OverrIDeprotected voID onPostExecute(JsONArray result){    super.onPostExecute(result);    final Message msg = new Message();    msg.obj = result;    if (youWantToUseHandler)        handler.dispatchMessage(msg);    else        writeJsONArray(result);}

处理程序:

final Handler handler = new Handler(){    public voID handleMessage(Message msg)     {        final JsONArray result = (JsONArray)msg.obj;        writeJsONArray(result);    };};

其他方法:

private voID writeJsONArray(final JsONArray result){    for (int i = 0; i < result.length(); i++)    {        try        {            Log.d("SAMPLE", result.get(i).toString());        }        catch (JsONException e)        {            Log.e("SAMPLE", "error getting result " + i, e);        }    }}

因为onPostExecute“在doInBackground之后在UI线程上运行.指定的结果是doInBackground返回的值;如果任务被取消或发生了异常,则返回null.” 〜API文件
您可以调用在类中声明的任何方法,并将此数组作为参数传递给它.

总结

以上是内存溢出为你收集整理的android-从AsyncTask获取返回的JSON全部内容,希望文章能够帮你解决android-从AsyncTask获取返回的JSON所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1085303.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-27
下一篇2022-05-27

发表评论

登录后才能评论

评论列表(0条)

    保存