2013-03-10 62 views
0

我正在編寫一個android應用程序,主要活動啓動並填充聯繫人列表,並且需要提示用戶今天對所有聯繫人的評分(promptUserForInput)並立即處理所有聯繫人的收到評分。我以爲我可以使用對話框提示每個聯繫人並從用戶那裏獲得評分。但下面的代碼失敗,因爲主線程不在等待用戶完成輸入所有用戶的評級。如何提示用戶在循環中輸入文字?

這是我在主要活動中爲所有聯繫人名稱的do while循環調用的函數。評級是一個全球變量。

double rating=0; 
private synchronized void promptUserForInput(String firstName, String lastName) { 

    final String fname = firstName; 
    final String lName = lastName; 

    AlertDialog.Builder alert = new AlertDialog.Builder(this); 
    String custName = firstName + " " + lastName; 
    final EditText input = new EditText(this); 
    alert.setTitle(custName); 
    alert.setView(input); 
    Log.v("Diva: in promptUserForInput", "setting positive buton"); 
    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 

     @Override 
     public void onClick(DialogInterface arg0, int arg1) { 
      Editable res = input.getText(); 
      if(res == null) { 
       Log.v("Diva..", "In positivebutton..befoer getting rating res is null"); 
      } 
      rating = Double.valueOf(input.getText().toString()); 
     } 
    }); 

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 

     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      rating=0; 
     } 
    }); 

    alert.show();   

} 

我的這個promptUserForInput()的調用方看起來像下面。

// get list of contacts in a cursor 
Cursor cursor = ManageDataBaseActivity.queryDataBase(this,  
ManageDataBaseActivity.CONTACT_INFO_TABLE); 

if(cursor.getCount()>0) { 

    double totalRatingForStats=0; 
    cursor.moveToFirst(); 
    do { 
     String[] colNames = cursor.getColumnNames(); 
     Log.v("Diva Colum names = ", colNames[0] + " " + colNames[1] + " " + colNames[2] + " " + colNames[3]); 

     String firstName = cursor.getString(cursor.getColumnIndex("FirstName")); 

     Log.v("Diva ..:", firstName); 
     String lastName = cursor.getString(cursor.getColumnIndex("LastName")); 
     String key = ManageDataBaseActivity.getDbKey(firstName, lastName, 
            date, ManageDataBaseActivity.CUSTOMER_DATA_TABLE); 
     promptUserForInput(firstName, lastName); 
     double ratingReceived = rating; 

     totalRatingForStats = totalRatingForStats+ratingReceived; 
     // some more processing 

         ManageDataBaseActivity.insertValueToDB(ManageDataBaseActivity. 
           CONTACT_DATA_TABLE+" ", .....); 
    } while(cursor.moveToNext());   

回答

1

簡短的回答:不要。

漫長的回答:在等待用戶輸入時,您絕不應該阻塞GUI程序的主線程。 相反,您應該提供一個繼續按鈕,它會觸發導致程序繼續的事件。有幾種方法可以實現這一點,首先想到的是信號和信號量。

我不是很熟悉Android編程 - 但API中應該有類似的東西,也許依賴於Intents。

1

在Activity的主線程中循環通常不是一個好主意。但是,你可以實現像一個pollNext()方法從光標獲取下一個數據集,並改變你的點擊方法是:

@Override 
public void onClick(DialogInterface dialog, int which) { 
    // do your rating stuff 

    // reads the next dataset 
    pollNext(); 

    // shows the next dialog 
    // of course, firstName and lastName must be membervariables to make this work 
    promptUserForInput(firstName, lastName); 
} 

背後的想法是很常見的,並在MVC-pattern

也使用