2017-06-03 93 views
-1

我不想在使用異步粘連的活動中顯示值。對於異步任務的代碼是:如何在活動中顯示asynctask值

private class BackgroundGetSignal extends AsyncTask<String, Void, Void> { 
    private TextView name; 
    //private TextView latitudeField; 
    //private TextView longitudeField; 
    //private TextView placeName; 

    Double lat; 
    Double longit; 
    String addre; 
    MyService myService; 
    private Intent i; 
    private Context context; 

    public BackgroundGetSignal(Context context) { 
     this.context = context; 
    } 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
    } 

    @Override 
    protected Void doInBackground(String[] o) { 
     myService = new MyService(); 
     if (myService.canGetLocation()) { 
      lat = myService.getLatitude(); 
      longit = myService.getLongitude(); 
      addre = myService.getAddress(); 
     } 
     return null; 

    } 


    @Override 
    protected void onPostExecute(Void result) { 
     latitudeField = (TextView) findViewById(R.id.txtLatitude); 
     longitudeField = (TextView) findViewById(R.id.txtLongitude); 
     placeName = (TextView) findViewById(R.id.txtLocation); 

     latitudeField.setText(lat.toString()); 
     longitudeField.setText(longit.toString()); 
     placeName.setText(addre); 

    } 
} 

,這是我怎麼把它叫做:

new BackgroundGetSignal(this).execute(); 

但是,應用程序崩潰。請有人能告訴我我做錯了什麼。

+0

把錯誤logcat放到你的isuue中。 –

+1

您發佈的代碼不正確:TextViews已被註釋掉。 給你一個關於如何使用AsyncTask良好執行的提示:使用**回調接口**在'onPostExecuted'中傳遞計算值並在AsyncTask執行類中實現這些以獲取傳遞的值。 –

+0

你有什麼異常? – EKN

回答

0

你應該做的最好的事情是在你的onPostExecute()方法中給try catch,並將ui更新代碼移動到try塊。因爲在執行onPostExecute()的時候,如果活動不在前臺,有可能會出現excepion。如果您發佈了崩潰日誌,這將有助於對此問題進行詳細分析。