如何从Radiogroup获得价值并改变数据库

时间:2018-03-15 20:01:09

标签: java android firebase radio-group

我正在使用firebase在android studio中开发一个应用程序,用户可以更改用户设置,如姓名,电话号码和生物。 我还需要能够更改所选的单选按钮组值。 Settings活动类如下

public class SettingsActivity extends AppCompatActivity {

private EditText mNameField, mPhoneField, mBio;
private Button mBack, mConfirm;
private RadioGroup mSport;
private ImageView mProfileImage;
private FirebaseAuth mAuth;
private DatabaseReference mUserDatabase;
private String userId, name, phone, bio, sport, profileImageUrl, userSex;
private Uri resultUri;

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

    mNameField = (EditText) findViewById(R.id.name);
    mPhoneField = (EditText) findViewById(R.id.phone);
    mBio = (EditText) findViewById(R.id.bio);
    mSport = (RadioGroup) findViewById(R.id.sport);
    mProfileImage = (ImageView) findViewById(R.id.profileImage);
    mBack = (Button) findViewById(R.id.back);
    mConfirm = (Button) findViewById(R.id.confirm);
    mAuth = FirebaseAuth.getInstance();
    userId = mAuth.getCurrentUser().getUid();

    mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(userId);

    getUserInfo();

    mProfileImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent, 1);
        }
    });
    mConfirm.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            saveUserInformation();
        }
    });
    mBack.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
            return;
        }
    });
}


private void getUserInfo() {
    mUserDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){
                Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
                if(map.get("name")!=null){
                    name = map.get("name").toString();
                    mNameField.setText(name);
                }
                if(map.get("phone")!=null){
                    phone = map.get("phone").toString();
                    mPhoneField.setText(phone);
                }
                if(map.get("bio")!=null){
                    bio = map.get("bio").toString();
                    mBio.setText(bio);
                }
                if(map.get("sport")!=null){

                }
                if(map.get("sex")!=null){
                    userSex = map.get("sex").toString();
                }
                if(map.get("sport") !=null){

                }
                Glide.clear(mProfileImage);
                if(map.get("profileImageUrl")!=null){
                    profileImageUrl = map.get("profileImageUrl").toString();
                    switch(profileImageUrl){
                        case "default":
                            Glide.with(getApplication()).load(R.mipmap.default_app_image).into(mProfileImage);
                            break;
                        default:
                            Glide.with(getApplication()).load(profileImageUrl).into(mProfileImage);
                            break;
                    }
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}

private void saveUserInformation() {
    name = mNameField.getText().toString();
    phone = mPhoneField.getText().toString();
    bio = mBio.getText().toString();
    int selectSport = mSport.getCheckedRadioButtonId();
    final RadioButton sportButton = (RadioButton) findViewById(selectSport);
    if(sportButton.getText() == null){
        return;
    }
    Map userInfo = new HashMap();
    userInfo.put("name", name);
    userInfo.put("phone", phone);
    userInfo.put("bio", bio);
    userInfo.put("sport",sport);

    mUserDatabase.updateChildren(userInfo);
    if(resultUri != null){
        StorageReference filepath = FirebaseStorage.getInstance().getReference().child("profileImages").child(userId);
        Bitmap bitmap = null;

        try {
            bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri);
        } catch (IOException e) {
            e.printStackTrace();
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
        byte[] data = baos.toByteArray();
        UploadTask uploadTask = filepath.putBytes(data);
        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                finish();
            }
        });
        uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Uri downloadUrl = taskSnapshot.getDownloadUrl();

                Map userInfo = new HashMap();
                userInfo.put("profileImageUrl", downloadUrl.toString());
                mUserDatabase.updateChildren(userInfo);

                finish();
                return;
            }
        });
    }else{
        finish();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == 1 && resultCode == Activity.RESULT_OK){
        final Uri imageUri = data.getData();
        resultUri = imageUri;
        mProfileImage.setImageURI(resultUri);
    }
}

和XML文件

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.wk001764.finalproject.SettingsActivity"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/profileImage"
        android:layout_width="200sp"
        android:layout_height="200sp"
        android:layout_gravity="center"
        android:layout_marginBottom="20sp"
        android:src="@mipmap/default_app_image" />

    <EditText
        android:id="@+id/name"
        android:layout_width="398dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20sp"
        android:background="@null"
        android:hint="Name" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/phone"
        android:background="@null"
        android:hint="Phone Number"
        android:layout_marginBottom="20sp"
        android:inputType="phone"/>
    <EditText
        android:id="@+id/bio"
        android:layout_width="398dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20sp"
        android:background="@null"
        android:hint="Bio" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Please Select the sport you want to change to:"/>
    <RadioGroup
        android:id="@+id/sport"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_gravity="center">

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <RadioButton
                    android:id="@+id/badminton"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Badminton" />

                <RadioButton
                    android:id="@+id/basketball"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Basketball" />

                <RadioButton
                    android:id="@+id/boxing"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Boxing" />

                <RadioButton
                    android:id="@+id/cricket"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Cricket" />

                <RadioButton
                    android:id="@+id/football"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Football" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <RadioButton
                    android:id="@+id/golf"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Golf" />

                <RadioButton
                    android:id="@+id/hockey"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Hockey" />

                <RadioButton
                    android:id="@+id/rugby"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Rugby" />

                <RadioButton
                    android:id="@+id/swimming"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Swimming" />

                <RadioButton
                    android:id="@+id/tennis"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Tennis" />
            </LinearLayout>
        </LinearLayout>
    </RadioGroup>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/confirm"
        android:text="Save"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/back"
        android:text="Back"/>

</LinearLayout>

如何获取无线电组的新选定值并将其保存到数据库?

1 个答案:

答案 0 :(得分:0)

你应该可以这样做:

int radioButtonId = mSport.getCheckedRadioButtonId();
View radioButton = mSport.findViewById(radioButtonId);
int idx = mSport.indexOfChild(radioButton);

要在RadioGroup上获取选定的RadioButton文本,请使用以下代码:

 RadioButton rb = (RadioButton) mSport.getChildAt(idx);
 String selectedText = rb.getText().toString();

但请注意,如果单选按钮是您的广播组的直接子节点,则此代码将仅 。因此,您需要删除LinearLayouts。实际上,根本不需要使用这些布局。您可以使用以下鳕鱼行在vertical文件中将广播组的方向设置为.XML

android:orientation="vertical"