Async-TaskでWebサイトからデータを読み込みたい。
しかし、私はを呼び出しますが、Async-Taskには入りません。
preExecute()
メソッドが呼び出されていなくても、少なくともそのようなログエントリは表示されません。なぜ私のAsyncTaskは実行されませんか?
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;
}
}
}
}
を設定し、
そして後のフィールドにをのTextViewを保存し、あなたの断片を含む活動のコードを表示したり、チェックしましたonCreateView()が呼び出されましたか? –
@KevinLEGOFF onCreateView()が働いています... – taxus1
あなたのasynctaskの非実行とは無関係ですが、 'textView.setText(mResult);'は動作しません。 asynctaskが完了したら、あなたはそれをやっていません。タスクが開始されていなくても、あなたは即座にそれをやっています。 – njzk2