비동기 작업으로 웹 사이트의 데이터를 읽고 싶습니다.
그러나 execute()
을 호출해도 비동기 작업에는 들어 가지 않습니다.
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;
}
}
}
}
당신이 당신의 단편을 포함하는 활동의 코드를 표시하거나 당신이 체크해야 할 텍스트를 설정 onCreateView()가 호출 되었습니까? –
@KevinLEGOFF onCreateView()가 작동 중입니다 ... – taxus1
asynctask의 비 실행과 관련이 없지만'textView.setText (mResult);'는 작동하지 않습니다. asynctask가 끝나면 작업을 시작하지 않을 때 즉시 작업을 수행하고 있습니다. – njzk2