2013-03-10 61 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

也使用