Elad Karni Elad Karni - 1 year ago 56
Android Question

Best way to store small amounts of data in android

I have a very basic application that uses the Maps API to display a map, and after a long press it will put a marker down at that location. If you select a different location, it will delete the current marker and make a new one.

The app does what I want it to at the moment, but I can get the data to persist after the app it closed.

This is what I'm currently trying to do:

protected void onCreate(Bundle savedInstanceState) {
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()

BufferedReader reader;

try {
final InputStream file = getAssets().open("userLatLng");
reader = new BufferedReader(new InputStreamReader(file));
String line = reader.readLine();
line = reader.readLine();
System.out.print("Getting Data");
} catch (IOException ioe) {

That is used for reading the data after the application has started

String filename = "userLatLng";
FileOutputStream outputStream;

try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);

} catch (Exception e) {

that should be how it saves the data. I have yet to get this to work, so any help would be appreciated!

Answer Source

Use SharedPreference API for small data storage.

SharedPreferences sharedPref = context.getSharedPreferences(
        "lat_pref", Context.MODE_PRIVATE);

    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putString(KEY_LAT, "12.7333");   // your lat and lng
    editor.putString(KEY_LNG, "12.7333");

You can retrieve it like below

SharedPreferences sharedPref = context.getSharedPreferences("lat_pref",Context.MODE_PRIVATE);

String slat = sharedPref.getString(KEY_LAT, "0.0");  //0.0 is default value, you can change it to any value you like. This default value is applied when the key is not present in SharedPrefernce

String slng = sharedPref.getString(KEY_LNG, "0.0");

//Convert String Lat and Lng to double values
double lat = Double.parseDouble(slat);
double lng = Double.parseDouble(slng);

You can declare KEY_LAT & KEY_LNG in some constant file.

public static final String KEY_LAT = "latitude";
public static final String KEY_LNG = "longitude";

If you are in Activity then use this as context, if in Fragment then use getActivity()


editor.putLong(KEY_LAT, Double.doubleToLongBits(location.getLatitude()));

Retrieve it like,

double lat = Double.longBitsToDouble(sharedPref.getLong(KEY_LAT, 0); 

Do the same for Longitude

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download