簡體   English   中英

單選按鈕文本推送到 Firebase

[英]Radio Button text pushed to Firebase

我正在構建一個應用程序,我希望用戶能夠將各種食品或飲料產品上傳到firebase 要求用戶輸入的信息是圖像、產品名稱、描述、價格和類別(食品或飲料)。 我使用ImageButton作為圖像,使用EditText作為名稱、描述和價格。 對於我使用RadioGroup / RadioButton的類別。 圖片、描述、價格和名稱正在推送到firebase

但是,我在RadioButtons上苦苦掙扎。 我想將 RadioButton 文本 Food or Beverage 推送到 Firebase。 我找到了一個關於它的部分教程,但我的西班牙語不太流利,也無法跟上正在發生的一切。

package com.example.nccummings.concertconnectowner;

import android.content.Intent;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

public class AddNewProductContinued extends AppCompatActivity {

private ImageButton productImage;
private static final int GALLREQ = 2;
private EditText name,description,price;
private String stringFoodOrBev;
private RadioGroup bevOrFood;
private RadioButton bevOrFoodOption;
private Uri uri = null;
private StorageReference storageReference = null;
private DatabaseReference mRef;
private FirebaseDatabase firebaseDatabase;

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

storageReference = 
FirebaseStorage.getInstance().getReference("Product Pictures");
mRef = FirebaseDatabase.getInstance().getReference("Product 
Information");

name = findViewById(R.id.productName);
description = findViewById(R.id.productDescription);
price = findViewById(R.id.productPrice);
bevOrFood = findViewById(R.id.rgbevorfood);


// This method allows user to select which category the product belongs 
//to (food or bev).

bevOrFood.setOnCheckedChangeListener(new 
RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {

bevOrFoodOption = bevOrFood.findViewById(checkedId);

switch (checkedId)
{
case R.id.rbfood:
stringFoodOrBev = bevOrFoodOption.getText().toString().trim();
break;
case R.id.rbbev:
stringFoodOrBev = bevOrFoodOption.getText().toString().trim();
break;
default:
}
}
});
}

// This method allows user to select image from phone
// once image button is clicked.
public void imageProductButtonClicked(View view){

Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,GALLREQ);
}

// Once image has been selected from the phone it gets set set to a uri 
//aka url.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent 
data) 
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLREQ && resultCode == RESULT_OK){
uri = data.getData();
productImage = findViewById(R.id.productImageButton);
productImage.setImageURI(uri);

}
}

// This method adds the information input into the form to Firebase.
public void addProductToMenuButtonClicked(View view){

final String name_text = name.getText().toString().trim();
final String description_text = 
description.getText().toString().trim();
final String price_text = price.getText().toString().trim();

if (!TextUtils.isEmpty(name_text) && 
!TextUtils.isEmpty(description_text) && !TextUtils.isEmpty(price_text)){

StorageReference filepath = 
storageReference.child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new 
OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) 
{
final Uri downloadurl = taskSnapshot.getDownloadUrl();

Toast.makeText(com.example.nccummings.concertconnectowner.
AddNewProductContinued.this,"Product Information has been successfully 
uploaded.", Toast.LENGTH_SHORT).show();

final DatabaseReference newPost = mRef.push();
newPost.child("Product").setValue(name_text);
newPost.child("Description").setValue(description_text);
newPost.child("Price").setValue(price_text);
newPost.child("pImage").setValue(downloadurl.toString());
newPost.child("Category").setValue(stringFoodOrBev);

}
});
}

}


}

下面是 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"
android:orientation="vertical"
tools:context=".AddNewProductContinued">


<ImageButton
android:id="@+id/productImageButton"
android:layout_width="match_parent"
android:layout_height="230dp"
android:onClick="imageProductButtonClicked"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="54dp" />

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/productName"
android:hint="Enter name of product."
/>

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/productDescription"
android:hint="Enter product description."
/>

<EditText
android:id="@+id/productPrice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter product price." />


<RadioGroup
android:layout_width="match_parent"
android:layout_height="38dp"
android:id="@+id/rgbevorfood"
>

<RadioButton
android:id="@+id/rbfood"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Food" />

<RadioButton
android:id="@+id/rbbev"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Beverage" />
</RadioGroup>

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="addProductToMenuButtonClicked"
android:text="Add product to menu" />




</LinearLayout>

可以試試這個,我的小項目之一。 它對我有用。

xml

<RadioGroup
    android:id="@+id/radio"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <RadioButton
        android:id="@+id/radioMale"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/radio_male" 
        android:checked="true" />

    <RadioButton
        android:id="@+id/radioFemale"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/radio_female" />

</RadioGroup>

活動

// get selected radio button from radioGroup
 int selectedId = radioGroup.getCheckedRadioButtonId();

// find the radiobutton by returned id
radioButton = (RadioButton) findViewById(selectedId);

Toast.makeText(MainActivity.this,
            radioButton.getText(), Toast.LENGTH_SHORT).show();
//Check whether get the text or not from using Toast

這是我從單選按鈕添加數據(性別)並將其發送到firebase並得到結果的方式。

xml

<RadioGroup
   android:layout_width="0dp"
   android:layout_height="wrap_content"
   tools:ignore="MissingConstraints"
   app:layout_constraintTop_toBottomOf="@id/et_score"
   app:layout_constraintStart_toStartOf="@id/et_score"
   app:layout_constraintEnd_toEndOf="@id/et_score"
   android:id="@+id/radiogroup"
   android:layout_marginTop="5dp"
   >
   <RadioButton
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="@string/female"
       android:id="@+id/rb_female"
       />
   <RadioButton
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:id="@+id/rb_male"
       android:text="@string/male"
       />

活動

class AddMembersActivity : AppCompatActivity() {
private lateinit var binding : ActivityAddMembersBinding
private lateinit var dbRef : DatabaseReference
private var gender = "female"
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityAddMembersBinding.inflate(layoutInflater)
    setContentView(binding.root)
        dbRef = FirebaseDatabase.getInstance().getReference("Users")
        binding.btnSave.setOnClickListener {
            saveData()
            startActivity(Intent(this , MainActivity::class.java))
            finish()
        }
    binding.rbMale.setOnClickListener {
        gender = "male"
        binding.rbFemale.isChecked = false
    }
    binding.rbFemale.setOnClickListener {
        gender = "female"
        binding.rbMale.isChecked = false
    }
}
private fun saveData() {
    Log.d("testtest","gender is $gender")
    val studentName = binding.etName.text.toString()
    val studentClass = binding.etClass.text.toString()
    val studentPhone = binding.etPhone.text.toString()
    val studentScore :Int = binding.etScore.text.toString().toInt()
    val temp = gender
    val user = Users(studentName , studentClass , studentPhone , studentScore , temp )

    dbRef.child(studentPhone.toString()).setValue(user).addOnCompleteListener {
        Toast.makeText(this , "Add Successfully" ,Toast.LENGTH_LONG).show()
    }.addOnFailureListener {
        Toast.makeText(this , "Add Failed" ,Toast.LENGTH_LONG).show()
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM