0

我有2個活動:MainActivity它與main.xml佈局(應用程序「主頁」屏幕)和AboutActivity關聯about.xml佈局(應用程序「關於」屏幕)。活動開關和異步Android

雖然在AboutActivityMainActivity內的Async任務仍嘗試訪問main.xml。我的應用程序因此而停止工作。

有什麼辦法可以嗎?

  • 「暫停」內MainActivityAsync任務和「履歷」他們當 用戶切換從AboutActivity
  • 或仍然在後臺訪問main.xml而在AboutActivity

其他信息:
MainActivity是發起活動。 AboutActivity extends MainActivity。用戶可以轉到「關於」屏幕/使用選項菜單切換到AboutActivity

MainActivity中的Async任務將用戶的當前位置放入文本視圖中。 about.xml只包含靜態文本。 AboutActivity什麼都不做,只能顯示about.xml

AboutActivity:

public class AboutActivity extends MainActivity { 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.about); 

    } 

} 

MainActivity:

public class MainActivity extends Activity { 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
      setContentView(R.layout.main); 
      // Creating a new non-ui thread task to download Google place json data 
      PlacesTask placesTask = new PlacesTask();         

     // Invokes the "doInBackground()" method of the class PlaceTask 
      placesTask.execute(sb.toString()); 
     } 

     /** A class, to download Google Places */ 
    private class PlacesTask extends AsyncTask<String, Integer, String>{ 

     String data = null; 

     // Invoked by execute() method of this object 
     @Override 
     protected String doInBackground(String... url) { 
      //make asynctask wait for debugger 
      //android.os.Debug.waitForDebugger(); 

      try{ 
       data = downloadUrl(url[0]); 
      }catch(Exception e){ 
       Log.d(DEBUG,e.toString()); 
      } 
      return data; 
     } 

     // Executed after the complete execution of doInBackground() method 
     @Override 
     protected void onPostExecute(String result){    
       TextView curLoc = (TextView) findViewById(R.id.CurrentLocation); 
       curLoc.setText(result); 
     } 

    } 
} 

回答

0

的AsyncTask不能暫停,所以我們可以存儲數據時,臨時任務完成,而不是在TextView的顯示數據開始後臺活動。

0

我已經解決了這個問題。這是一個局部變量範圍的問題,部分是由於這樣的事實,我不能用findViewById()那裏,它總是返回null

curLoc是空的onPostExecute中的AsyncTask。

我刪除了以下內容:

TextView curLoc = (TextView) findViewById(R.id.CurrentLocation); 

,並宣佈curLoc作爲類MainActivity

private TextView curLoc; 

,並投入的onCreate()的屬性

curLoc = (TextView) findViewById(R.id.CurrentLocation);