Комбинированная строка не привязана к значению - PullRequest
0 голосов
/ 30 июля 2011

Кто-нибудь может понять, почему моя строка с вымышленным именем не привязывается к значению?

public void setNames() {

    //*******************//
    //***DATABASE INFO***//
    //*******************//
    DBAdapter db = new DBAdapter(this);

    if (totalPlayerCount >= 1){  


    //**********************//
    //***SET PLAYER NAMES***//
    //**********************//
    AlertDialog.Builder alert = new AlertDialog.Builder(this);

    alert.setTitle("Player " + nameLoop);
    alert.setMessage("Name:");

    // Set an EditText view to get user input 
    final EditText input = new EditText(this);
    alert.setView(input);

    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
      String newName = "name"+nameLoop;
      // If i put "name1" here like so, the value "wow" stays with "name1" all the way to the database and does not end up null
      name1 = "wow";
      newName = input.getText().toString(); <-- newName should be name1, name2, name3, name4 each time around.  If i do a simple Toast, it displays name1, name2, etc.  But when i insert those values into the database, they are all null.
      setNames();
      }
    });

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int whichButton) {
        // Canceled.
      }
    });

    alert.show();

    nameLoop++;

    }
    if (totalPlayerCount == 0){
        db.open();
        db.insertPlayers(String.valueOf(name1), String.valueOf(name2), String.valueOf(name3),
                String.valueOf(name4));
        db.close();

        AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
        //myAlertDialog.setTitle("Saved");
        myAlertDialog.setMessage("Names saved");
        myAlertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int which) {
                return;
            } }); 
        myAlertDialog.show();
    }   
    totalPlayerCount--;
    return;
}

Вот тот самый клип, только что разорванный, что у меня возникли проблемы с

public void onClick(DialogInterface dialog, int whichButton) {
      String newName = "name"+nameLoop;
      // If i put "name1" here like so, the value "wow" stays with "name1" all the way to the database and does not end up null
      name1 = "wow";
      newName = input.getText().toString(); <-- newName should be name1, name2, name3, name4 each time around.  If i do a simple Toast, it displays name1, name2, etc.  But when i insert those values into the database, they are all null.
      setNames();
      }
    });

Ответы [ 2 ]

1 голос
/ 30 июля 2011

Вы не можете динамически создать переменную и затем присвоить ей значение. Java не работает как JavaScript.

Вы должны заменить свой

  String newName = "name"+nameLoop;
  // If i put "name1" here like so, the value "wow" stays with "name1" all the way to the database and does not end up null
  name1 = "wow";
  newName = input.getText().toString(); <-- newName should be name1, name2, name3, name4 each time around.  If i do a simple Toast, it displays name1, name2, etc.  But when i insert those values into the database, they are all null.

секция с оператором switch.

String newName = input.getText().toString();
switch(nameLoop){
case 1: name1=newName;break;
case 2: name2=newName;break;
....
0 голосов
/ 30 июля 2011

Короткая версия alert.show () не блокируется, поэтому вы выполняете вставку базы данных до того, как вернете присвоение значения name1 через onClick.

Длинная версия, сделайте несколько шагов назад и изучите синтаксис Java и то, как работает программирование на основе событий. Это второй вопрос как сегодня. Это здорово, что вы стремитесь работать, но я рекомендую вам сосредоточиться на некоторых основах, прежде чем вы начнете работать в полную силу. С хорошим пониманием вы сможете писать код отцу и быстрее с меньшим стрессом и меньшим объездом. an ounce of prevention is worth a pound of cure

...