为什么我的AsyncTask不执行?

时间:2016-08-29 18:35:43

标签: android android-asynctask

我想在异步任务中从网站读取数据 但是,虽然我打电话给execute(),但它并没有进入Async-Task 甚至没有调用preExecute()方法,至少会记录日志条目,但不会出现。

public class NewFragment extends Fragment {

    private String mResult; //This Result will be returned by FetchDataTask()



    private final String LOG_TAG = NewFragment.class.getSimpleName();

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

    }

    // fetch data from example.com and show them in textView
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState ) {
        super.onCreate(savedInstanceState);

        FetchDataTask fetchDataTask = new FetchDataTask();

        fetchDataTask.execute("http://example.com");


        View rootView = inflater.inflate(R.layout.fragment_new,container,false);
        TextView textView = (TextView) rootView.findViewById(R.id.textView);
        textView.setText(mResult);


        return rootView;


    }

    public class FetchDataTask extends AsyncTask<String, Integer, String >{

        private final String LOG_TAG = FetchDataTask.class.getSimpleName();

        @Override
        protected void onPreExecute(){
            Log.e(LOG_TAG,"onPreExecute()"); //This Log-entry doesn't appear, why??
        }



        @Override
        protected String doInBackground(String... strings){
            //http-connection:
            HttpURLConnection httpURLConnection = null;
            BufferedReader bufferedReader = null;

            String result = "";

            try{
                URL url = new URL(strings[0]);
                httpURLConnection = (HttpURLConnection) url.openConnection();
                InputStream inputStream = httpURLConnection.getInputStream();

                //read data:

                if(inputStream==null){
                    Log.v(LOG_TAG,"There is nothin'");
                } else {
                     bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    String line;

                    while ((line = bufferedReader.readLine()) != null) {
                        result += line + "\n";
                    }
                }




            }catch(Exception e){
                Log.e(LOG_TAG, "Error in http connection"+e.toString());
            } finally {
                if(httpURLConnection!=null){
                    httpURLConnection.disconnect();
                }
                if(bufferedReader != null){
                    try{
                        bufferedReader.close();
                    }catch (final IOException e){
                        Log.e(LOG_TAG,"Error closing stream", e);
                    }
                }
            }



            Log.e(LOG_TAG,"doInBackground()");
            return result;


        }
        @Override
        protected void onPostExecute(String string){
            mResult=null;

            if(string!=null){
                mResult=string;

            }

        }
    }
}

2 个答案:

答案 0 :(得分:0)

关于您没有看到该消息的原因,您是在制作Fragment类并添加到Activity吗?否则,该问题无法再现。

  

// This Result will be returned by FetchDataTask()

<强>假即可。这不是异步代码的工作原理。您正在将TextView设置为null,而不是等待AsyncTask完成。

相反,只需将textview存储在字段

private TextView textView;

public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState ) {
    super.onCreate(savedInstanceState);

    View rootView = inflater.inflate(R.layout.fragment_new,container,false);
    textView = (TextView) rootView.findViewById(R.id.textView);

    FetchDataTask fetchDataTask = new FetchDataTask();
    fetchDataTask.execute("http://example.com");

    return rootView;
}

稍后,设置文字

@Override
protected void onPostExecute(String string){

    if(string!=null){
        textView.setText(string);
    }

}

答案 1 :(得分:-1)

public class FetchDataTask extends AsyncTask<String, Integer, String>更改为public class FetchDataTask extends AsyncTask<String, Void, String>以使签名类似于您的asynctask实现。

此外,在片段setRetainInstance(true)中添加onCreate()以在定向更改发生时保留视图。只是一种最佳做法。

最后,让您在活动中拥有newFragment个实例,从而调用newFragment.startFetching(),其中包含类似的内容,

public class NewFragment extends Fragment {
    public void startFetching() {
        FetchDataTask fetchDataTask = new FetchDataTask();
        fetchDataTask.execute("http://example.com");
    }
    ...
}

参考:https://gist.github.com/daichan4649/2480065