Android将数据添加到当前用户firebase RTD

时间:2018-02-10 17:49:03

标签: java android firebase firebase-realtime-database

我正在创建一个Android应用程序,用户登录并输入食物点击添加的名称并将其添加到他们的冰箱。我有登录工作,我有添加,编辑,删除功能。我不确定如何确保添加的数据仅添加到登录用户冰箱。 有人可以帮忙吗?

添加食物代码:

public class addFood extends AppCompatActivity {
//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";

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


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

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

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

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

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

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

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

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

        //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) {
    //getting the specified artist reference
    DatabaseReference dR = FirebaseDatabase.getInstance().getReference("foods").child(id);

    //updating artist
    Food food = new Food(id, name, category);
    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 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();
            if (!TextUtils.isEmpty(name)) {
                updateFood(foodId, name, category);
                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(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;
  }

}

数据库架构

{
    "foods":{
        "-L30jqWgsXDUOsTlLgEE":{
            "bestBefore":"22/03/2018",
            "foodCategory":"Fruit",
            "foodId":"-L30jqWgsXDUOsTlLgEE",
            "foodName":"Banana"
        },
        "-L30js70gQ2tjCBA9aCJ":{
            ...
        },
        "-L30js70gQ2tjCBA9aCJ":{
            ...
        }
    },
    "nutritions":{
        "-L30jqWgsXDUOsTlLgEE":{
            "calories":"50",
            "id":"-L30jqWgsXDUOsTlLgEE",
            "rating":0
        },
        "-L30js70gQ2tjCBA9aCJ":{
            ...
        },
        "-L30js70gQ2tjCBA9aCJ":{
            ...
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我建议您更改结构,为每个用户提供不同的食物清单。像这样:

{
    "foods":{
        "user1":{
            "-L30jqWgsXDUOsTlLgEE":{
                "bestBefore":"22/03/2018",
                "foodCategory":"Fruit",
                "foodId":"-L30jqWgsXDUOsTlLgEE",
                "foodName":"Banana"
            },
            "-L30js70gQ2tjCBA9aCJ":{
                ...
            },
            "-L30jtpi1OCPPXrhbmqP":{
                ...
            }
        },
        "user2":{
            "-L30js70gQ2tjCBA9aCJ":{
                "bestBefore":"22/03/2018",
                "foodCategory":"Fruit",
                "foodId":"-L30js70gQ2tjCBA9aCJ",
                "foodName":"Apple"
            },
            "-L30jtpi1OCPPXrhbmqP":{
                ...
            }
        }
    }
}

其中“user1”和“user2”是2个不同用户的ID。您可以在addFood活动中从Firebase Auth获取此内容:

public class addFood extends AppCompatActivity {

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

...

然后在从uid方法中读取数据时使用此onCreate

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

    ...
}

并且不要忘记分别更新updateFooddeleteFood方法:

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

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

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