Home > Blockchain >  How to save data entered by user in Andoid app (Java)
How to save data entered by user in Andoid app (Java)

Time:01-17

I'm doing a meal tracker app, where you can track what you eat and also upload images of your meals to be stored on your phone and then used in the app to display your past meals.

This is the track fragment where the user can add the details to their meal they want to track.Screenshot

Once the user clicks on "save" I want the details from that saved somewhere so I can use that data to represent the different meals in a RecyclerView later.

// handling "save"-button: get data from fragment, store it as mealmodel and then locally
        saveBtn = view.findViewById(R.id.track_buttonSave);
        saveBtn.setOnClickListener(view12 -> {

            String form_typeOfMeal = view.findViewById(R.id.mealType_textView).getEditableText().toString();

// ...

My plan was to take the data and save it as Objects of type MealModel and then keep track of them with a list. This is the MealModel class:

/**
 * This class holds the data to represent one meal item
 */
public class MealModel {
    String mealtype;
    String healthyness;
    String date;
    String pathtoimage; // path in phone gallery
    boolean favorised;

    public MealModel(String mealtype, String healthyness, String date, boolean favorised, String pathtoimage) {
        this.mealtype = mealtype;
        this.healthyness = healthyness;
        this.date = date;
        this.favorised = favorised;
        this.pathtoimage = pathtoimage;
    }

    public String getMealtype() {
        return mealtype;
    }

    public String getHealthyness() {
        return healthyness;
    }

    public String getPathtoimage() {
        return pathtoimage;
    }

    public boolean getFavorised() {
        return favorised;
    }

    public String getDate() { return date; }
}

How can I now save the list of the MealModels containing the data, permanently, so that they are still available after closing and reopening the app and I can use the data to display the tracked meal items?

Help is appreciated a lot :)

CodePudding user response:

You can use android's local database(SQLite) to achieve this. Apps that handle non-trivial amounts of structured data can use the local database.

For persisting your data into an SQLite database you can use the Room persistence library, part of the Android Architecture Components. It makes it easier to work with SQLiteDatabase objects in your app, decreasing the amount of boilerplate code and verifying SQL queries at compile time.

https://developer.android.com/training/data-storage/room

  • Related