2011-12-15 33 views
0

在我的應用程序中,我試圖在PopupDialog中使用ListView。這是在AsyncTask之內完成的。我認爲問題在於onPreExecuteonPostExecute之間.....所有事情都正確返回,但list = null我使用findViewById()後。我無法弄清楚爲什麼......請注意,AsyncTask和Adapter都是內部類。PopupDialog中的ListView爲空

protected void onPreExecute() { 
     AlertDialog.Builder alert = new AlertDialog.Builder(CreateNewReport.this); 
     LayoutInflater inflater = LayoutInflater.from(CreateNewReport.this); 
     popupView = inflater.inflate(R.layout.add_expenses, null); 

     alert.setTitle("Add Expenses").setView(popupView); 

     alert.setNeutralButton("Save", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int whichButton) { 

      } 
     }); 

     alert.show(); 
    } 

    protected void onPostExecute(List<Expense> expenses){ 
     availableExpenses = expenses; 

     // create list adapter for available expenses 
     ArrayAdapter<Expense> adapter = new ArrayAdapter<Expense>(CreateNewReport.this, 
       android.R.layout.simple_list_item_1, expenses); 

     // get a reference to the list 
     final ListView list = (ListView) findViewById(R.id.listViewAvailableExpenses); 

     // set the list adapter 
     list.setAdapter(adapter); 

     // find widgets 
     final ProgressBar progress = (ProgressBar) findViewById(R.id.loading_expenses); 
     final LinearLayout listLayout = (LinearLayout) findViewById(R.id.available_expenses); 
     final LinearLayout progressContainer = (LinearLayout) findViewById(R.id.available_expenses_loading); 

     // change visibility as needed 
     progressContainer.setVisibility(View.INVISIBLE); 
     progress.setVisibility(View.INVISIBLE); 
     listLayout.setVisibility(View.VISIBLE); 
    } 

XML爲彈出框

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 
    <ProgressBar 
     android:id="@+id/loading_expenses" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     style="@android:style/Widget.ProgressBar.Large" 
     android:layout_centerInParent="true" 
     /> 
     <ListView 
      android:id="@+id/listViewAvailableExpenses" 
      style="@style/Container" 
      android:cacheColorHint="#00000000" 
      /> 
</RelativeLayout> 

回答

2

這是因爲findViewById()呼叫正在尋找列表中的活動中(它的活動實例的方法),但你的名單內對話。相反,您需要保存對該對話框的引用,然後執行theDialog.findViewById(R.id.ListNote)

//PreExecute 
theDialog = alert.create(); //theDialog is an instance variable of the asynctask 
theDialog.show(); 


//PostExecute 
final ListView list = (ListView) theDialog.findViewById(R.id.ListNote); 
+0

Spot on。這完全正確。 – Cody 2011-12-15 17:06:59