How to use Sharedpreferencesfrom Android? Can I choose several filenames?

Asked

Viewed 121 times

0

I’m learning to use android by making an example application with various types of functions of Android Studio. At the moment I have a list presented in a Listview and I would like to save it. I use Sharedpreferences and it works well: saved and I can read the file later in Listview itself. I wonder if there is any way to save several files of the same type, with the filename being the date (for example), and then to open let the user choose which one he wants. I don’t know if I have to switch to Interstate or Sharedfiles. Thank you M.Lagua

  • Try to leave at least one snippet of the code that you mentioned and it’s working. So people can help you better.

1 answer

0

You can try to do 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());
    }

Substitute MyPlaces by the class representing the data you need

This is the class Myplace:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.