Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/187.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 为什么';我的异步任务不能执行吗?_Android_Android Asynctask - Fatal编程技术网

Android 为什么';我的异步任务不能执行吗?

Android 为什么';我的异步任务不能执行吗?,android,android-asynctask,Android,Android Asynctask,我想在异步任务中读取网站上的数据。 但是,尽管我调用了execute(),但它并没有进入异步任务。 甚至没有调用preExecute()方法,至少日志条目没有出现 public class NewFragment extends Fragment { private String mResult; //This Result will be returned by FetchDataTask() private final String LOG_TAG = NewFrag

我想在异步任务中读取网站上的数据。
但是,尽管我调用了
execute()
,但它并没有进入异步任务。
甚至没有调用
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;

            }

        }
    }
}
public类NewFragment扩展了Fragment{
私有字符串mResult;//此结果将由FetchDataTask()返回
私有最终字符串LOG_TAG=NewFragment.class.getSimpleName();
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
//从example.com获取数据并在textView中显示
CreateView上的公共视图(布局、充气机、视图组容器、捆绑包保存状态){
super.onCreate(savedInstanceState);
FetchDataTask FetchDataTask=新建FetchDataTask();
fetchDataTask.execute(“http://example.com");
视图根视图=充气机。充气(R.layout.fragment\u new,container,false);
TextView TextView=(TextView)rootView.findViewById(R.id.TextView);
textView.setText(mResult);
返回rootView;
}
公共类FetchDataTask扩展了AsyncTask{
私有最终字符串LOG_TAG=FetchDataTask.class.getSimpleName();
@凌驾
受保护的void onPreExecute(){
Log.e(Log_标记,“onPreExecute()”;//这个日志条目没有出现,为什么??
}
@凌驾
受保护的字符串背景(字符串…字符串){
//http连接:
HttpURLConnection HttpURLConnection=null;
BufferedReader BufferedReader=null;
字符串结果=”;
试一试{
URL=新URL(字符串[0]);
httpURLConnection=(httpURLConnection)url.openConnection();
InputStream InputStream=httpURLConnection.getInputStream();
//读取数据:
如果(inputStream==null){
Log.v(Log_标签,“没有什么”;
}否则{
bufferedReader=新的bufferedReader(新的InputStreamReader(inputStream));
弦线;
而((line=bufferedReader.readLine())!=null){
结果+=行+“\n”;
}
}
}捕获(例外e){
Log.e(Log_标记,“http连接中的错误”+e.toString());
}最后{
if(httpURLConnection!=null){
httpURLConnection.disconnect();
}
if(bufferedReader!=null){
试一试{
bufferedReader.close();
}捕获(最终IOE例外){
Log.e(Log_标签,“错误关闭流”,e);
}
}
}
Log.e(Log_标记,“doInBackground()”);
返回结果;
}
@凌驾
受保护的void onPostExecute(字符串){
mResult=null;
if(字符串!=null){
mResult=字符串;
}
}
}
}

公共类FetchDataTask扩展AsyncTask
更改为
公共类FetchDataTask扩展AsyncTask
,以使签名与AsyncTask实现类似

另外,在片段
onCreate()
中添加
setRetainInstance(true)
,以在发生方向更改时保留视图。这只是一个最佳实践

最后,让您在activity中拥有
newFragment
实例,从而调用
newFragment.startfetch()
,其中

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

参考资料:

关于为什么看不到该消息,您是否正在创建片段类并将其添加到活动中?否则,这个问题就无法重现

//此结果将由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);
    }

}

您是否可以显示包含片段的活动的代码,或者检查是否调用了onCreateView()。@KevinLEGOFF onCreateView()正在工作…与未执行asynctask无关,但是
textView.setText(mResult)不起作用。当异步任务完成时,您并没有这样做,而是在任务甚至还没有启动时立即这样做。@taxus1您是否有执行日志。我想不出我们为什么不至少从阅读编码开始,你能解释一下区别吗?他必须用整数参数实现onProgressUpdate(),以使签名匹配。@RafaelCardoso中的第二个数据类型代表onProgressUpdate()-方法,我不使用它,因此,将其更改为voidTask是明智的,但AsyncTask永远不会因此停止工作。无论如何,我似乎没有任何影响。我可能建议您学习其他HTTP库,如Volley(如果您有JSON数据,可以进行改装),因为它们比AsyncTasks更易于使用。