片段

时间:2016-11-06 20:27:59

标签: android android-asynctask fragment

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

这是异步任务:

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

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

任何想法发生了什么?

1 个答案:

答案 0 :(得分:0)

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

尝试在片段的onViewCreated或onResume

中运行异步任务

btw考虑使用第三方库,如Volley或OkHttp或Retrofit进行网络流程