android - 将数据从 TextView 保存到 firebase 数据库

标签 android firebase textview

我有一个日期选择器,可以将所选日期写入 TextView 。我想将此 TextView 中的数据添加到我现有的 firebase 数据库中。 我不确定我需要更改哪些数据才能添加到日期中。我是否需要在有名称和类别的任何地方添加它?从 TextView 添加字符串时,过程是否不同。

另外,将来我将使用日期在食物即将过期时发出推送通知......如果将日期保存为字符串可以吗?

添加食物类:

public class Food {
    private String foodId;
    private String foodName;

    private String foodCategory;
private String bestBefore;

public Food(String foodId,  String foodName, String foodCategory, String bestBefore) {
    this.foodId = foodId;
    this.foodName = foodName;
    this.foodCategory = foodCategory;
    this.bestBefore = bestBefore;
}

public String getFoodId() {
    return foodId;
}

public String getBestBefore() { return  bestBefore;}

public String getFoodName() {
    return foodName;
}

public String getFoodCategory() {
    return foodCategory;
}

public Food(){
    //this constructor is required
}

日期选择器和添加食物到 firebase :

public class addFood extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();

//we will use these constants later to pass the artist name and id to another activity
public static final String FOOD_NAME = "net.simplifiedcoding.firebasedatabaseexample.artistname";
public static final String FOOD_ID = "net.simplifiedcoding.firebasedatabaseexample.artistid";
public static final String FOOD_DATE = "net.simplifiedcoding.firebasedatabaseexample.fooddate";

//view objects
EditText editTextName;
Spinner spinnerCategory;
Button buttonAddFood;
ListView listViewFoods;
Button buttonScan;
Button buttonSearch;
TextView dateText;


//a list to store all the foods from firebase database
List<Food> foods;

//our database reference object
DatabaseReference databaseFoods;


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

    //getting the reference of artists node
    databaseFoods = FirebaseDatabase.getInstance().getReference("foods").child(uid);

    //getting views
    editTextName = (EditText) findViewById(R.id.editTextName);
    spinnerCategory = (Spinner) findViewById(R.id.spinnerCategories);
    listViewFoods = (ListView) findViewById(R.id.listViewFoods);
    buttonScan = (Button) findViewById(R.id.buttonScan);
    buttonSearch = (Button) findViewById(R.id.buttonSearch);
    final Button dateButton = (Button) findViewById(R.id.DateButton);
    dateText = (TextView) findViewById(R.id.DateText);

    buttonAddFood = (Button) findViewById(R.id.buttonAddFood);

    //list to store artists
    foods = new ArrayList<>();



    //adding an onclicklistener to button
    buttonAddFood.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //calling the method addArtist()
            //the method is defined below
            //this method is actually performing the write operation
            addFood();
        }
    });

    dateButton.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            android.support.v4.app.DialogFragment datePicker = new DatePickerFragment();
            datePicker.show(getSupportFragmentManager(), "date picker");
        }
    });

    buttonScan.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(addFood.this, BarcodeDetect.class);

            //starting the activity with intent
            startActivity(intent);
        }
    });
    buttonSearch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(addFood.this, SearchBar.class);

            //starting the activity with intent
            startActivity(intent);
        }
    });

    //attaching listener to listview
    listViewFoods.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            //getting the selected artist
            Food food = foods.get(i);

            //creating an intent
            Intent intent = new Intent(getApplicationContext(), nutritionalInfo.class);

            //putting artist name and id to intent
            intent.putExtra(FOOD_ID, food.getFoodId());
            intent.putExtra(FOOD_NAME, food.getFoodName());
            intent.putExtra(FOOD_DATE, food.getBestBefore());

            //starting the activity with intent
            startActivity(intent);
        }
    });

    listViewFoods.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
            Food food = foods.get(i);
            showUpdateDeleteDialog(food.getFoodId(), food.getFoodName());
            return true;
        }
    });
}

@Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
    Calendar c = Calendar.getInstance();
    c.set(Calendar.YEAR, i);
    c.set(Calendar.MONTH, i1);
    c.set(Calendar.DAY_OF_MONTH, i2);
    String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.getTime());

//        TextView dateText = (TextView) findViewById(R.id.DateText);
        dateText.setText(currentDateString);
    }

protected void onStart() {
    super.onStart();
    //attaching value event listener
    databaseFoods.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            //clearing the previous artist list
            foods.clear();

            //iterating through all the nodes
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                //getting artist
                Food food = postSnapshot.getValue(Food.class);
                //adding artist to the list
                foods.add(food);
            }

            //creating adapter
            FoodList foodAdapter = new FoodList(addFood.this, foods);
            //attaching adapter to the listview
            listViewFoods.setAdapter(foodAdapter);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

/*
* This method is saving a new artist to the
* Firebase Realtime Database
* */
private void addFood() {
    //getting the values to save
    String name = editTextName.getText().toString().trim();
    String category = spinnerCategory.getSelectedItem().toString();
    String bestBefore = dateText.toString();

    //checking if the value is provided
    if (!TextUtils.isEmpty(name)) {

        //getting a unique id using push().getKey() method
        //it will create a unique id and we will use it as the Primary Key for our Artist
        String id = databaseFoods.push().getKey();

        //creating an Artist Object
       // Food food = new Food(id, name, category, bestBefore);

        //Saving the Artist
       // databaseFoods.child(id).setValue(food);
        Map<Object, String> food = new HashMap<>();
        food.put("id", food.getId());
        food.put("name", food.getName());
        food.put("category", food.getCategory());
        food.put("bestBefore", food.getbestBefore());

        databaseFoods.child(id).push(map);

        //setting edittext to blank again
        editTextName.setText("");

        //displaying a success toast
        Toast.makeText(this, "food added", Toast.LENGTH_LONG).show();
    } else {
        //if the value is not given displaying a toast
        Toast.makeText(this, "Please enter a food", Toast.LENGTH_LONG).show();
    }
}

private boolean updateFood(String id, String name, String category, String bestBefore) {
    //getting the specified artist reference
    DatabaseReference dR = FirebaseDatabase.getInstance().getReference("foods").child(uid).child(id);

    //updating artist
    Food food = new Food(id, name, category, bestBefore);
    dR.setValue(food);
    Toast.makeText(getApplicationContext(), "Food Updated", Toast.LENGTH_LONG).show();
    return true;
}

private void showUpdateDeleteDialog(final String foodId, String foodName) {

    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
    LayoutInflater inflater = getLayoutInflater();
    final View dialogView = inflater.inflate(R.layout.update_dialog, null);
    dialogBuilder.setView(dialogView);

    final EditText editTextName = (EditText) dialogView.findViewById(R.id.editTextName);
    final Spinner spinnerCategory = (Spinner) dialogView.findViewById(R.id.spinnerCategories);
    final EditText editTextDate = (EditText) dialogView.findViewById(R.id.editTextDate);
    final Button buttonUpdate = (Button) dialogView.findViewById(R.id.buttonUpdateFood);
    final Button buttonDelete = (Button) dialogView.findViewById(R.id.buttonDeleteFood);

    dialogBuilder.setTitle(foodName);
    final AlertDialog b = dialogBuilder.create();
    b.show();


    buttonUpdate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String name = editTextName.getText().toString().trim();
            String category = spinnerCategory.getSelectedItem().toString();
            String bestBefore = editTextDate.getText().toString().trim();

            if (!TextUtils.isEmpty(name)) {
                updateFood(foodId, name, category, bestBefore);
                b.dismiss();
            }
        }
    });


    buttonDelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            deleteFood(foodId);
            b.dismiss();
        }
    });
}
private boolean deleteFood(String id) {
    //getting the specified artist reference
    DatabaseReference dR = FirebaseDatabase.getInstance().getReference("foods").child(uid).child(id);

    //removing artist
    dR.removeValue();

    //getting the tracks reference for the specified artist
    DatabaseReference drNutritions = FirebaseDatabase.getInstance().getReference("nutritions").child(id);

    //removing all tracks
    drNutritions.removeValue();
    Toast.makeText(getApplicationContext(), "Food Deleted", Toast.LENGTH_LONG).show();

    return true;
}

以及食物添加的列表:

public class FoodList extends ArrayAdapter<Food> {
private Activity context;

    List<Food> foods;

public FoodList(Activity context, List<Food> foods) {
        super(context, R.layout.layout_food_list, foods);
        this.context = context;
        this.foods = foods;
        }

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    View listViewItem = inflater.inflate(R.layout.layout_food_list, null, true);

    TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
    TextView textViewCategory = (TextView) listViewItem.findViewById(R.id.textViewCategory);
    TextView textViewDate = (TextView)listViewItem.findViewById(R.id.textViewDate);

    Food food = foods.get(position);
    textViewName.setText(food.getFoodName());
    textViewCategory.setText(food.getFoodCategory());
    textViewDate.setText(food.getBestBefore());

    return listViewItem;
}

非常感谢您的帮助,我对此很陌生,谢谢

更新:我为最佳使用日期添加了代码,但是当我单击添加到数据库时,firebase 数据库正在添加 "android.support.v7.widget.AppCompatTextView{413768 V.ED.....。 ....... 0,235-720,273 #7f090004 app:id/DateText}" 而不是在 TextView 中输入的日期。

更新 2: 我进行了更改,现在这是我的 addFood 方法:

private void addFood() {
        //getting the values to save
        String name = editTextName.getText().toString().trim();
        String category = spinnerCategory.getSelectedItem().toString();
        String bestBefore = dateText.toString();

        //checking if the value is provided
        if (!TextUtils.isEmpty(name)) {

            //getting a unique id using push().getKey() method
            //it will create a unique id and we will use it as the Primary Key for our Artist
            String id = databaseFoods.push().getKey();

        //creating an Artist Object
       // Food food = new Food(id, name, category, bestBefore);

        //Saving the Artist
       // databaseFoods.child(id).setValue(food);
        Map<Object, String> food = new HashMap<>();
        food.put("id", food.getId());
        food.put("name", food.getName());
        food.put("category", food.getCategory());
        food.put("bestBefore", food.getbestBefore());

        databaseFoods.child(id).push(map);

        //setting edittext to blank again
        editTextName.setText("");

        //displaying a success toast
        Toast.makeText(this, "food added", Toast.LENGTH_LONG).show();
    } else {
        //if the value is not given displaying a toast
        Toast.makeText(this, "Please enter a food", Toast.LENGTH_LONG).show();
    }
}

最佳答案

问题是这一行:

String bestBefore = dateText.toString();

您只是将现有的 TextView 转换为 String 而没有获取它的值。要获取该值,您应该使用:

String bestBefore = dateText.getText();

你可以保留之前的代码:

 Food food = new Food(id, name, category, bestBefore);

 //Saving the Artist
 databaseFoods.child(id).setValue(food);

关于android - 将数据从 TextView 保存到 firebase 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48731166/

相关文章:

android - 带有 drawableTop 和 textcolor 的 TextView

android - TextView文本大小方法

android - ImageView 上的未绑定(bind)前缀错误

Android Instant Run Gradle 实验性插件

angularjs - 我应该总是通过 $push() 将新对象添加到对象列表中吗?

javascript - Firebase 数据库 : Search for Particular Item

android - 广播组 : Horizontal layout and Span multiple lines

android - 如何从 Android 应用程序上传数据库文件到谷歌驱动器?

javascript - 在firebase中同时更新多个用户

android - 如何在 ConstraintLayout 中旋转 TextView 及其约束边界