将数据从textview保存到firebase数据库

时间:2018-02-11 11:49:57

标签: android firebase textview

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

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

添加食物类:

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

2 个答案:

答案 0 :(得分:0)

而不是这样做:

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

答案 1 :(得分:0)

问题在于这一行:

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