Текст переключателя передан в Firebase - PullRequest
0 голосов
/ 27 мая 2018

Я создаю приложение, в котором я хотел бы, чтобы пользователи могли загружать различные продукты питания или напитки в firebase.Информация, которую запрашивает пользователь для ввода, представляет собой изображение, название продукта, описание, цену и категорию (еда или напиток).Я использовал ImageButton для изображения и EditText для имени, описания и цены.Для категории я использую RadioGroup / RadioButton.Изображение, описание, цена и название увеличиваются до firebase;

однако я борюсь с RadioButtons.Я хочу подтолкнуть текст RadioButton «Еда или напитки» в 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>

1 Ответ

0 голосов
/ 27 мая 2018

можете попробовать это, один из моих маленьких проектов.Это работает для меня.

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...