How to use the SharedPreferences of Android? Can I choose multiple file names?

0

I'm learning how to use android making an example application with various types of Android Studio functions. At the moment I have a list presented in a ListView and would like to save it. I use SharedPreferences and it works fine: saved and I can read the file later in the ListView itself. I would like to know if there is any way to save multiple files of the same type, with filename being the date (for example), and then to open let the user choose which one he wants. I do not know if I have to switch to internal storage or to SharedFiles. Thanks M.Lagua

    
asked by anonymous 18.03.2016 / 11:48

1 answer

0

You can try the following:

 public static void saveMyPlace(Context context, MyPlace myPlaces) {
        SharedPreferences prefs = context.getSharedPreferences(Constants.MY_PLACES, Context.MODE_PRIVATE);
        ArrayList<MyPlace> mp = getMyPlaces(context);
        if (mp == null)
            mp = new ArrayList<>();
        mp.add(myPlaces);
        String places = new Gson().toJson(mp);
        prefs.edit().putString(Constants.MY_PLACES, places).apply();
    }

    public static ArrayList<MyPlace> getMyPlaces(Context context) {
        SharedPreferences prefs = context.getSharedPreferences(Constants.MY_PLACES, Context.MODE_PRIVATE);
        String myPlaces = prefs.getString(Constants.MY_PLACES, "");
        return new Gson().fromJson(myPlaces, new TypeToken<ArrayList<MyPlace>>() {
        }.getType());
    }

Replace MyPlaces with the class representing the data you need

This is the Myplace class:

public class MyPlace implements Serializable {
    private double latitude;
    private double longitude;
    private String city;
    private Date date;
    public double getLatitude() {
        return latitude;
    }

    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }


    @Override
    public String toString() {
        return "MyPlace{" +
                "latitude=" + latitude +
                ", longitude=" + longitude +
                ", city='" + city + '\'' +
                ", date=" + date +
                '}';
    }
}
    
21.03.2016 / 05:07