dancingbush dancingbush -4 years ago 38
Android Question

How to save latitude and longitude (location) in Shared Preference

I want to get the longitude and latitude co-ordinates of a location and save in a ArrayList, then commit this list to SharedPreference file so when the Map loads all previous locations could be set with a marker using data from the SharedPreference file.

I only know realise that SharedPreference will only store primitive data types and not arrays.

My question does is anybody know of a way to persist this data either via shared pref technique or by any alternate means?

Any input appreciated.

Answer Source

1- create a class and put everything you want to store for example arraylist of your latitude and longitude and make that class implement Serializable interface.

class MyBundle  implements Serializable {

   ArrayList<Double> mLat;
   ArrayList<Double> mLan;

   MyBundle( ArrayList<Double> latitude, ArrayList<Double> longitude ){

    mLat = latitude;
    mLan = longitude;

   }

}

2- write it to file:

 ObjectOutputStream oos = null;
 FileOutputStream fout = null;
 try{
        FileOutputStream fout = new FileOutputStream("Your file path");
        ObjectOutputStream oos = new ObjectOutputStream(fout);
        oos.writeObject(mb); // mb is an instance of MyBundle
 } catch (Exception ex) {
        e.printStackTrace();
 }finally {
   if(oos  != null){
     oos.close();
   } 
 }

and to get back everything:

 ObjectInputStream objectinputstream = null;
 try {
        streamIn = new FileInputStream("Your file address");
        objectinputstream = new ObjectInputStream(streamIn);
        MyBundle mb = (MyBundle) objectinputstream.readObject();

   } catch (Exception e) {
        e.printStackTrace();
   }finally {
     if(objectinputstream != null){
        objectinputstream .close();
     } 
   }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download