【问题标题】:Problems with async task inside fragment片段内的异步任务问题
【发布时间】:2016-11-07 04:39:55
【问题描述】:

我正在使用异步任务从服务器获取数据。在片段的 onCreate 方法上调用异步任务。但是从片段内部调用时,结果始终为空。

这是异步任务:

public class getDateEventsAsync extends AsyncTask<String,Void,String> {
    @Override
    protected String doInBackground(String... params) {
        Log.v("getDateEvents","OK");
        InputStream input;

        try{
            URL url = new URL(ServerURL);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setReadTimeout(10000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setInstanceFollowRedirects(true);
            conn.setUseCaches(false);
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(10000 /* milliseconds */);
            JSONObject obj = new JSONObject();


            obj.put("action","getDateEvents");
            obj.put("date",mParam1);


            JSONArray x = new JSONArray(mParam2);
            obj.put("userDisciplinas",x);


            Log.d("Request-Events",obj.toString());



            ContentValues val = new ContentValues();
            val.put("rpc_message",obj.toString());


            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(val.toString());

            writer.flush();
            writer.close();

            conn.connect();
            int response = conn.getResponseCode();
            Log.e("Result", "" + response);

            StringBuilder sbuilder = new StringBuilder();

            if (response == HttpURLConnection.HTTP_OK) {

                input = conn.getInputStream();
                String line;
                BufferedReader buf = new BufferedReader(new InputStreamReader(input));
                while ((line = buf.readLine()) != null) {
                    sbuilder.append(line);
                }
                Log.e("Result", sbuilder.toString());
            }


            return sbuilder.toString();

        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }


    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        try{
            events_array = new JSONArray(s);
            Log.e("Array",events_array.toString());
            RestartAdapter();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

但是,当我从以下活动中调用异步任务时,它可以工作。

 Fragment frag = DayFragment.newInstance(day,new getDateEventsAsync().execute(day).get());
        //Fragment frag = DayFragment.newInstance(day,userModules_ids.toString());
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.container_body, frag,"DIA").addToBackStack(null);
        fragmentTransaction.commit();

但是,如果我将片段加载为注释行,并从片段内部使用异步任务,它将不起作用。

有什么想法吗?

【问题讨论】:

  • 永远不要将 .execute().get() 与 AsyncTask 一起使用。它破坏了使其 async 的目的
  • 此外,AsyncTask 和 POST-ing JSON 会变得很乱……你考虑过使用 Volley、OkHttp 还是 Retrofit?
  • 我建议您使用 REST API 发送 JSON 的任何地方,使用@cricket_007 提到的任何库。让您的生活更轻松,在某些情况下执行速度更快instructure.github.io/blog/2013/12/09/volley-vs-retrofit

标签: android android-asynctask fragment


【解决方案1】:

使用异步任务的目的是在后台运行代码,但是当您使用 .get() 方法时,您的程序将等待异步任务完成工作!

尝试在片段的 onViewCreated 或 onResume 中运行异步任务

顺便说一句,考虑为您的网络进程使用 Volley 或 OkHttp 或 Retrofit 等第三方库

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多