2016-08-29 2 views
0

비동기 작업으로 웹 사이트의 데이터를 읽고 싶습니다.
그러나 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; 

      } 

     } 
    } 
} 
+0

당신이 당신의 단편을 포함하는 활동의 코드를 표시하거나 당신이 체크해야 할 텍스트를 설정 onCreateView()가 호출 되었습니까? –

+0

@KevinLEGOFF onCreateView()가 작동 중입니다 ... – taxus1

+0

asynctask의 비 실행과 관련이 없지만'textView.setText (mResult);'는 작동하지 않습니다. asynctask가 끝나면 작업을 시작하지 않을 때 즉시 작업을 수행하고 있습니다. – njzk2

답변

0

, 당신은 Fragment 클래스를 만들고 Activity에 추가하고 있습니까? 그렇지 않으면, 그. 제를 재현 할 수 없습니다.

// This Result will be returned by FetchDataTask()

거짓. 비동기 코드가 작동하는 방식이 아닙니다. TextView를 null으로 설정하고 AsyncTask가 완료 될 때까지 기다리지 않습니다.

는 대신에, 단지

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

} 
+0

감사합니다. 정말 좋은 설명입니다. 많이 도와 줬어! – taxus1

+0

환영합니다. JSON 데이터가 있다면 Volley와 같은 다른 HTTP 라이브러리 (또는 JSON 데이터가있는 경우 Retrofit)에 대해 배울 것을 제안 할 수 있습니다. AsyncTasks보다 더 잘 작동하기 때문입니다. –

-1

변경, public class FetchDataTask extends AsyncTask<String, Void, String>public class FetchDataTask extends AsyncTask<String, Integer, String>은 AsyncTask를 구현하는 서명이 유사한 확인합니다.

또한 방향 변경이 일어나는 동안 onCreate() 조각에 setRetainInstance(true)을 추가하면보기가 유지됩니다. 단지 모범 사례.

그리고 마지막으로, 당신은 당신이 뭔가를 가지고 newFragment.startFetching()를 호출하여, 활동 newFragment 인스턴스를 보자

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

참조 : 왜 당신이 메시지가 표시되지 않습니다에 관해서 https://gist.github.com/daichan4649/2480065

+0

차이점을 설명해 주시겠습니까? – RafaelC

+1

고마워, 좋은 생각이야! 그러나 불행히도 여전히 효과가 없습니다. – taxus1

+0

서명을 일치 시키려면 Integer 매개 변수와 함께 onProgressUpdate()를 구현해야합니다. –

관련 문제