单选按钮在安卓中返回错误的值

huangapple go评论66阅读模式
英文:

Radio button returns wrong value in Android

问题

以下是翻译好的代码部分:

ViewFriend.java(显示列表视图并具有编辑选项的类)

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {
        // ...
        builder.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // ...
                intent.putExtra("gender", gender);
                // ...
            }
        });
        // ...
    }
});

editFriend.java(用传递的意图填充表单数据并显示)

public class editFriend extends AppCompatActivity {
    // ...
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_editordeletefriend);
        // ...
        name = intent.getStringExtra("name");
        age = intent.getStringExtra("age");
        gender = intent.getStringExtra("gender");
        address = intent.getStringExtra("address");
        // ...
    }
    // ...
    public void displayForm() {
        // ...
        if (gender.equals("Male")) {
            rb = (RadioButton)findViewById(R.id.resultGenderMale_update);
        } else if (gender.equals("Female")) {
            rb = (RadioButton)findViewById(R.id.resultGenderFemale_update);
        }
        rb.setChecked(true);
        // ...
    }
    // ...
}

如果您有任何其他问题或需要进一步的帮助,请随时问我。

英文:

I have a form where a person can enter details about a friend (name, age, gender, address). This friend is displayed in a list view and when a friend from the list is clicked on they have the choice to edit that record.

I can successfully update every detail about a friend except for the gender.

For example:

List view:

1) James Bond, 20, Male, Sydney NSW

Then I click edit and change it to

James smith, 21, Female, Canberra NSW

and then back in my list view it will show:

1) James smith, 21, Male, Canberra NSW

Notice how the gender doesn't change?

I can figure out why this is happening as I use the same logic to change the name and age as i did to change the gender

Here is the relevant code:

ViewFriend.java ( this class displays the list view and has the edit option)

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView&lt;?&gt; parent, final View view, final int position, long id) {
        String text = listView.getItemAtPosition(position).toString();
        final int ID = Integer.parseInt(String.valueOf(text.charAt(0)));
        AlertDialog.Builder builder = new AlertDialog.Builder(viewFriends.this);
        builder.setTitle(&quot;Notice&quot;);
        builder.setMessage(&quot;Please select to to edit, delete a friend or cancel&quot;);

        // add the buttons
        builder.setPositiveButton(&quot;Edit&quot;, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(getApplicationContext(), editOrDelete.class);
                ArrayList&lt;String&gt; result1 = mydb.retrieveRow(ID);
                name = result1.get(1);
                age = result1.get(2);
                gender = result1.get(3);
                address = result1.get(4);
                code = result1.get(0);
                intent.putExtra(&quot;code&quot;, code);
                intent.putExtra(&quot;name&quot;, name);
                intent.putExtra(&quot;age&quot;, age);
                intent.putExtra(&quot;gender&quot;, gender);
                intent.putExtra(&quot;address&quot;, address);
                startActivity(intent);
            }
        });
        builder.setNeutralButton(&quot; Delete&quot;, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mydb.deleteTitle(ID);
                finish();
                Intent intent = new Intent(getApplicationContext(),viewFriends.class);
                startActivity(intent);
            }
        });
        builder.setNegativeButton(&quot;Cancel&quot;, null);
        AlertDialog dialog = builder.create();
        dialog.show();
    }
});

The code above retrieves the details from the database and passes it to the intent. I have printed the contents of each variable (name, age, gender, address) and they print out correctly.

editFriend.java ( this class pre fills the form with the data passed through the intent that displays correctly)

  public class editFriend extends AppCompatActivity {
    private  Intent intent;
    private RadioGroup rg;
    private Button update;
    private RadioButton rb;
    private String newName,newAddress,newGender;
    private int newAge;
    EditText ed, ed1;
    public String name,address,gender,age,code;
    private int selectedID,ages,codes;
    NumberPicker numberPicker;
    private databaseManager4 myDataBase;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_editordeletefriend);
        intent= getIntent();
        myDataBase = new databaseManager4(this);
        rg = (RadioGroup)findViewById(R.id.radioGroup_update);
        selectedID = rg.getCheckedRadioButtonId();
        rb = (RadioButton) findViewById(selectedID);
        ed = (EditText)findViewById(R.id.fullName_update);
        numberPicker = (NumberPicker)findViewById(R.id.resultAge_update);
        numberPicker.setMinValue(6);
        numberPicker.setMaxValue(110);
        numberPicker.setWrapSelectorWheel(false);
        update = (Button)findViewById(R.id.update_button);
        ed1 = (EditText)findViewById(R.id.address_update);
        name = intent.getStringExtra(&quot;name&quot;);
        age = intent.getStringExtra(&quot;age&quot;);
        gender = intent.getStringExtra(&quot;gender&quot;);
        address = intent.getStringExtra(&quot;address&quot;);
        code = intent.getStringExtra(&quot;code&quot;);
        codes = Integer.parseInt(code);
        displayForm();
        newName = ed.getText().toString();
        newAge = numberPicker.getValue();
        newGender = rb.getText().toString();


        update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              
              int id = rg.getCheckedRadioButtonId();
            rb = (RadioButton) findViewById(id);
                if (myDataBase.updateRow(codes,newName,newAge,newGender,ed1.getText().toString())){
                Toast.makeText(getApplicationContext(),&quot;successfully updated the friend &quot;
                           +ed.getText().toString(),Toast.LENGTH_SHORT).show();
               }
               else{
                   Toast.makeText(getApplicationContext(),&quot;Could not  update the friend &quot;
                           +ed.getText().toString(),Toast.LENGTH_SHORT).show();
               }
               intent = new Intent(getApplicationContext(),viewFriends.class);
               startActivity(intent);
            }
        });
    }

    public void displayForm(){
        ed.setText(name);
        ed1.setText(address);

       if (gender.equals(&quot;Male&quot;)){
            rb = (RadioButton)findViewById(R.id.resultGenderMale_update);
        }
         else if (gender.equals(&quot;Female&quot;))
        {
            rb = (RadioButton)findViewById(R.id.resultGenderFemale_update);
        }
        rb.setChecked(true);

        ages= Integer.parseInt(age);
        numberPicker.setValue(ages);


    }
    public void clear(){
        ed.setText(&quot;&quot;);
        ed1.setText(&quot;&quot;);
    }
}

This is where the issue lies, even if the user clicks on Male it registers as female and i am unsure why.

Any ideas how i can fix this?

答案1

得分: 0

你的问题在于你将 rb 变量的值设置为一个单选按钮,根据先前的性别值预定义,代码如下:

if (gender.equals("Male")){
  rb = (RadioButton)findViewById(R.id.resultGenderMale_update);
}
else if (gender.equals("Female"))
{
  rb = (RadioButton)findViewById(R.id.resultGenderFemale_update);
}

然后你在同一个按钮上读取值。为了解决这个问题,在更新按钮的点击监听器中,你需要使用 getCheckedRadioButtonId 方法来读取选中的单选按钮 id,使用你的 rg 变量来表示单选按钮组。

以下是你的 "Edit Friend" 活动代码可能的外观:

public class EditFriendActivity extends AppCompatActivity {
  // ... 其他成员变量的初始化

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_editordeletefriend);
    initUI();

    mDatabaseManager = new databaseManager4(this);
  }

  private void initUI() {
    // ... 初始化 UI 元素的代码

    mUpdateButton = (Button) findViewById(R.id.update_button);
    mUpdateButton.setOnClickListener(updateClickListener);

    mGenderRadioGroup = (RadioGroup) findViewById(R.id.radioGroup_update);

    RadioButton targetRadioButton = null;
    switch (Gender.fromString(intent.getStringExtra("gender"))) {
      case MALE:
        targetRadioButton = (RadioButton) findViewById(R.id.resultGenderMale_update);
        break;
      case FEMALE:
        targetRadioButton = (RadioButton) findViewById(R.id.resultGenderFemale_update);
        break;
    }
    if (targetRadioButton != null) {
      targetRadioButton.setChecked(true);
    }
  }

  // ... 其他方法的定义

  private View.OnClickListener updateClickListener =
      new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          Gender newGender = getSelectedGender();
          int code = Integer.parseInt(getIntent().getStringExtra("code"));
          // ... 更新数据库并显示 Toast 通知

          Intent viewFriendsIntent = new Intent(getApplicationContext(), viewFriends.class);
          startActivity(viewFriendsIntent);
          finish();
        }
      };

  // ... 其他内部类和枚举的定义
}

注意:上面的代码片段仅包含翻译后的部分,用于描述问题和解决方案。实际使用时,你需要将这些代码片段与你的项目整合,并根据需要进行调整。

英文:

Your problem is that you set value of rb variable to a single radio button, predefined with previous gender value here

if (gender.equals(&quot;Male&quot;)){
rb = (RadioButton)findViewById(R.id.resultGenderMale_update);
}
else if (gender.equals(&quot;Female&quot;))
{
rb = (RadioButton)findViewById(R.id.resultGenderFemale_update);
}

And you read value of the same button then. To fix that in you click listener for update button you need to read checked radio button id using getCheckedRadioButtonId on radio group (your rg variable).

upd:
this is how your Edit Friend activity code might look like

public class EditFriendActivity extends AppCompatActivity {
private RadioGroup mGenderRadioGroup;
private Button mUpdateButton;
private EditText mNameField;
private EditText mAddressField;
private NumberPicker mAgePicker;
private databaseManager4 mDatabaseManager;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_editordeletefriend);
initUI();
mDatabaseManager = new databaseManager4(this);
}
private void initUI() {
Intent intent = getIntent();
mNameField = (EditText) findViewById(R.id.fullName_update);
mNameField.setText(intent.getStringExtra(&quot;name&quot;));
mAddressField = (EditText) findViewById(R.id.address_update);
mAddressField.setText(intent.getStringExtra(&quot;address&quot;));
mAgePicker = (NumberPicker) findViewById(R.id.resultAge_update);
mAgePicker.setMinValue(6);
mAgePicker.setMaxValue(110);
mAgePicker.setWrapSelectorWheel(false);
mAgePicker.setValue(Integer.parseInt(intent.getStringExtra(&quot;age&quot;)));
mUpdateButton = (Button) findViewById(R.id.update_button);
mUpdateButton.setOnClickListener(updateClickListener);
mGenderRadioGroup = (RadioGroup) findViewById(R.id.radioGroup_update);
RadioButton targetRadioButton = null;
switch (Gender.fromString(intent.getStringExtra(&quot;gender&quot;))) {
case MALE:
targetRadioButton = (RadioButton) findViewById(R.id.resultGenderMale_update);
break;
case FEMALE:
targetRadioButton = (RadioButton) findViewById(R.id.resultGenderFemale_update);
break;
}
if (targetRadioButton != null) {
targetRadioButton.setChecked(true);
}
}
public void clear() {
mNameField.setText(&quot;&quot;);
mAddressField.setText(&quot;&quot;);
}
private Gender getSelectedGender() {
int checkedButtonId = mGenderRadioGroup.getCheckedRadioButtonId();
switch (checkedButtonId) {
case R.id.resultGenderMale_update:
return Gender.MALE;
case R.id.resultGenderFemale_update:
return Gender.FEMALE;
}
return Gender.UNDEFINED;
}
private View.OnClickListener updateClickListener =
new View.OnClickListener() {
@Override
public void onClick(View v) {
Gender newGender = getSelectedGender();
int code = Integer.parseInt(getIntent().getStringExtra(&quot;code&quot;));
System.out.println(&quot;gender is&quot; + newGender.stringValue);
if (mDatabaseManager.updateRow(
code,
mNameField.getText().toString(),
mAgePicker.getValue(),
newGender.stringValue,
mAddressField.getText().toString())) {
Toast.makeText(
getApplicationContext(),
&quot;successfully updated the friend &quot; + ed.getText().toString(),
Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(
getApplicationContext(),
&quot;Could not  update the friend &quot; + ed.getText().toString(),
Toast.LENGTH_SHORT)
.show();
}
Intent viewFriendsIntent = new Intent(getApplicationContext(), viewFriends.class);
startActivity(viewFriendsIntent);
finish();
}
};
private enum Gender {
UNDEFINED(&quot;undefined&quot;),
MALE(&quot;Male&quot;),
FEMALE(&quot;Female&quot;);
private @Nullable String stringValue;
Gender(@Nullable String stringValue) {
this.stringValue = stringValue;
}
public static Gender fromString(@Nullable String value) {
if (value != null) {
for (Gender gender : Gender.values()) {
if (value.equals(gender.stringValue)) {
return gender;
}
}
}
return UNDEFINED;
}
}
}

huangapple
  • 本文由 发表于 2020年9月11日 13:23:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/63841205.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定