简体   繁体   English

将数据从TextView保存到Firebase数据库

[英]Saving data from a textview to a firebase database

I have a datepicker that writes the selected date to a text view. 我有一个日期选择器,将所选日期写入文本视图。 I want to add the data from this textview to my existing firebase database. 我想将文本视图中的数据添加到我现有的Firebase数据库中。 I an not sure what data I need to change to add in the date. 我不确定在日期中需要更改哪些数据。 Do I need to add it everywhere I have the name and category? 我有名字和类别的地方都需要添加吗? and is the process different when adding string from a text view . 和从文本视图添加字符串的过程是不同的。

Also in the future I will be using the date to give a push notification when the food is about to expire ...is it okay if the date is saved as a string? 同样在将来,我将使用该日期在食物即将过期时发出推送通知...如果将日期另存为字符串,可以吗?

Add food class: 添加食品分类:

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
}

Date picker and adding food to firebase : 日期选择器并将食物添加到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;
}

and the list where food adds: 以及食物添加的清单:

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;
}

} }

I would really appreciate the help I am really new to this thank you 我真的很感谢我的帮助,我真的很陌生,谢谢

UPDATE: I added code for the best before date but when I click add to the DB the firebase database is adding "android.support.v7.widget.AppCompatTextView{413768 V.ED..... ........ 0,235-720,273 #7f090004 app:id/DateText}" instead of the date entered in the textview. 更新:我添加了代码以获得最佳的日期,但是当我单击添加到数据库时,firebase数据库正在添加"android.support.v7.widget.AppCompatTextView{413768 V.ED..... ........ 0,235-720,273 #7f090004 app:id/DateText}"而不是在"android.support.v7.widget.AppCompatTextView{413768 V.ED..... ........ 0,235-720,273 #7f090004 app:id/DateText}"输入的日期。

UPDATE 2: I made the changes and this is now my addFood method: 更新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();
    }
}

Instead of doing this: 而不是这样做:

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

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

Do this: 做这个:

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);

The problem is this line: 问题是这一行:

String bestBefore = dateText.toString();

You're simply casting the existing TextView to String and not getting it's value. 您只是将现有的TextView强制转换为String而不获取其值。 To get the value, you should use: 要获得价值,您应该使用:

String bestBefore = dateText.getText();

And you can keep your previous code: 您可以保留以前的代码:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM