How to save added google maps overlays in an android app? - android

I created an app in which users can add various markers on google maps using overlays. I want the app to save the overlay when the user creates it so that when they re-open the app later the markers will still be present.
Currently anytime the app is re-opened the created markers are gone. I have searched the internet and have not gotten a clear understanding of how to save my markers/overlays offline for later use.

As mentioned, you need to use some persistent storage. Perhaps, database would be an excess in your particular case (if you simply need to save a bunch of longitude-latitude pairs), and Shared Preferences would fit your needs. If you rarely need to read/store this data, then putting JSONArray as a String to Shared Preferences would be the simplest (in terms of reading and extracting data) solution:
SharedPreferences.Editor editor = getSharedPreferences("name", 0).edit();
JSONArray jsonArr = new JSONArray();
JSONObject json;
for (int i = 0; i < user_markers.size(); i++) { // here I assume that user_markers is a list where you store markers added by user
json = new JSONObject();
json.put("lat", user_markers.get(i).getLat());
json.put("long", user_markers.get(i).getLong());
jsonArr.put(json);
}
editor.putString("markers", jsonArr.toString());
editor.commit();
If you need to read/store this data a bit more often, then you may assign ids/indexes to separate SharedPreferences's values, but this may require more complicated extraction method. For example:
SharedPreferences.Editor editor = getSharedPreferences("name", 0).edit();
int id;
for (int i = 0; i < user_markers.size(); i++) { // here I assume that user_markers is a list where you store markers added by user
id = user_markers.get(i).getId(); // some Id here
// or simply id = i;
editor.putString("markers_lat_" + id, user_markers.get(i).getLat());
editor.putString("markers_long_" + id, user_markers.get(i).getLong());
}
editor.commit();
After all, you should consider using database if you plan to store big amount of data or data of complicated structure.

It just an idea, but you can save your markers in database and when you reopen your map just query database and put it on the map again...

You should use some persistent storage. SQLite would probably be the best option here. Overlays have their lat and lng. Just get them and whatever data you need along with them and put all these in the SQLite database. Then on Activity start get the points from database and show them on the map.

Use a SQLite database to save the user data. They are simple and for a large amount of data they are better than SharedPreferences.
More Info
Example

Related

Store data in android studio by using sharedPreferences

When storing data in android studio using SharedPreferences. it store did not store the Newest value at first. I mean the data location does not update.
I want to newest store data in 1st location and the previously stored data automatics shift to the next location.
Example>
I enter/store first time a value in Edit Text. it stores in the first location but when I store the Second value. It did not update the first value location it store data in the second location.
btnSaved.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("id", item.getId());
editor.putString("name", item.getName());
editor.putString("image", item.getImge());
editor.putString("status", item.getStatus());
editor.putString("timeStamp", item.getTimeStamp());
editor.putString("URL", item.getUrl());
editor.commit();
if you are new to android studio understand data storage options clearly.
this one will help.
if you are going to use id like "status", "email", "name" multiple times save them in a separate class as static final variables.
don't save variables like that make a separate class as User or something, set the value there, and save it as a JSON object.
like this
getAppPrefsEditor().putString("user", provideGson().toJson(object of YourClass)).apply();
and get them like this
String userStr = getAppPrefs().getString("user", null);
user = provideGson().fromJson(userStr, YourClass.class);
and you can get the value inside "user"
also there is some free cloud storage if you want to try you can check,
firebase is quite easy to start with.firebase web link

Android Saving Information To Device

I'm making an Android application and want to create a "Favorites" list for some objects in the app. I wanna make the list accessible and editable in all my activities and I can't really figure out the best way to do this.
Shared preferences? Writing a small txt file to the device? What's the fastest way to do this?
Thanks in advance!
dependencies {
compile 'com.google.code.gson:gson:2.3.1'
}
Then when you want to save, convert your array into String:
ArrayList<Type> yourData = new ArrayList<Type>();
String dataStr = new Gson().toJson(yourData);
//put this dataStr in your shared preferences as String
To retrieve and convert back to an object is also simple:
String str = "";
//you need to retrieve this string from shared preferences.
Type type = new TypeToken<ArrayList<Type>>() { }.getType();
ArrayList<Type> restoreData = new Gson().fromJson(str, type);
If you want to create a Favorites list, use a SQLite Database.
There's really only four ways to store data.
Shared Preferences
Databases
Local files
Remote Server - Slowest since it depends on network connection, so let's skip this.
Between the remaining 3, SharedPreferences is a great option when used to store a single value. However, it's not a good option for storing a Favorites list, mainly because you can only store a single String.
You can still store it by combining all items in your list into one string, then splitting it each time. However, as your Favorites list gets larger, this single long String will too. Splitting and combining all the time isn't efficient.
SharedPreferences is still a decent option if you only have to store the Favorite's list, but since you want to edit it too, it becomes a less attractive solution.
Local Files and Databases are the better options, however local files require you to read in the file each time you want to use it. This process of reading and writing to a file isn't as efficient as using a Database, especially if you want to edit. For example, let's say you want to remove an item from the middle of your Favorite's list. This would require you to read in the file, edit it, then write the change into the file again. Not too pleasant when compared with the ease of the final solution.
Databases are the best option for this, mainly because it's designed to manage data. You can create a single Favorite's table and add each item as it's own individual row. Fetching the entire table becomes quick and easy. Fetching a single item becomes quick and easy. Adding a new item or removing a new item is also quick and easy.

Android - Storing data without a database

My application records user movement with Geofence boundaries, if the user exits the Geofence, alerts are appropriately escalated. These alert are counted and displayed in a summary at the end of the activity. However I would like to create a stats page where it displays the last week or month of activities as well as the number of alerts so that I can display these in a chart. Is there anyway to do this effectively without using a database?
I had thought of writing data to a log file and reading it but curious as to if there is a better option.
You can use SharedPreferences but it will require a lot of controls, probably more then creating a database. If you insist not to use a database, put an integer to your shared preferences saving the count of your data, also that integer will become your id. Then you can store your data with a loop depending on your data.
Here is to write your data to shared preferences
SharedPreferences mSharedPrefs = getSharedPreferences("MyStoredData",
MODE_PRIVATE);
private SharedPreferences.Editor mPrefsEditor = mSharedPrefs.edit();
int count = mSharedPrefs.getInt("storedDataCount", 0);
for(int i = 0 ; i < yourCurrentDataCount ; i++) {
mPrefsEditor.putInt("data" + count, yourData.get(i));
count++;
}
mPrefsEditor.putInt("storedDataCount", count);
And to get your data,
int count = mSharedPrefs.getInt("storedDataCount", 0);
for(int i = 0 ; i < count ; i++) {
yourData.add(mSharedPrefs.getString("data" + i, "defaultData"));
count++;
}
Edit:
I should have added some explaining. The idea is to save the count of your data to generate an id, and save the tag according to it. This code will work like this, lets say you have 5 strings. Since you don't have a MyStoredData xml, it will get created. Then since you don't have the "storedDataCount" tag, you will get 0 as a count. Your loop will iterate 5 times and in each iteration, you will add a tag to your xml like "<.data0>your first data<./data0><.data1>your second data <./data1>... After your loop is done, you will modify your storedDataCount and it will become <.storedDataCount>5<./ storedDataCount>. And the next time you use your app, your count will start from 5 so your tag will start from <.data5>. For reading, you will iterate through tags by checking "data0", "data1" and so on.
You can use java serialization if you dont want to use database.
You can also use XML/JSON for storing data.
I support already mentioned favoritism towards using a DB for this task. Nevertheless, if I were to do it via FS, I would use a transactional async library like Square's tape is.
In your case I would keep the data during a session in JSON object (structure) and persist it (in onPause()) and restore it (in onRestore()) with tape's GSON Object Converter.
Should be easy out of the box, I believe.
Tape website: http://square.github.io/tape/
Alternatively to manually persisting a file or using a 3rd party library like tape, you could always (de)serialize your JSON to SharedPreferences.

Saving persistent text file in internal storage

This question his perhaps more a request for some advice how to save some data in the best way. I'm doing an app where I tag images from the device with contacts from the ContactsContract in the device by saving the filepath for the image together with the selected contact, and by contact, I guess it's enough to save the ID or the name of that contact?
I need some advice how I should use the FileOutputStream to write this data. Should I, and can I save the strings like "filepath, id" for each row in the file or what's the best way? I also need to search if the filepath and contact is already in the file aswell as be able to tag several contacts to an image. First I thought I could use a file for each image and add all the contacts that are tagged with it, but that is perhaps not a good way to do it?!
Preciate some advice!
EDIT:
If I use Shared Preferences then I could use the contacts ID as a key and the image path as the value? Then I can add several unique ID keys with different values? But I guess, I can't add more than one value to a key?
You need some kind of structured data system.
Have you tried SQLite? - SQLite seems good for the job.
CREATE TABLE `contact`('id' INT , 'contact_id' TEXT, 'image_file_path' TEXT, TEXT, PRIMARY KEY('id'))
You search feature is easy then;
SELECT * FROM contact WHERE contact_id ='1'
I would start here.
Edit:
You can insert the contact details by converting it to jsonstring and put in a sharedPreferences.
Example:
JSONObject obj=new JSONObject();
obj.put("Contactid", 1);
obj.put("ImagePath", "/sdcard/download/a.png");
String jsonstring=obj.toString();
if you have multiple contacts than use json Array Like this
JSONArray array=new JSONArray("ContactDetails");
for(int i=0;i<noofcontacts;i++)
{
JSONObject obj=new JSONObject();
obj.put("Contactid", 1);
obj.put("ImagePath", "/sdcard/download/a.png");
array.put(obj);
}
jsonstring= array.toString();
save contact details in the SharedPreferences like this
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("contactDetails", jsonstring);
editor.commit();
Now get SharedPreference values
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String jsoncontactdetails= sharedPreferences.getString("contactDetails", null);
I hope you know Json Parsing.
Using Database is the best option in this case. Because it is hard to maintain each file in the internal storage and it also consume some processing time. Best is the contact the image path of the contact in the database .

Android daily update text app

I'm currently trying to think of the best way to program an app which simply has text and images that update every day to different content. Would the best way to do this be to store all of the items in an array and then call upon each according to the phone's clock? Or is there a better or simpler way of doing this?
If you need to know I'm using Eclipse to program the app.
You could have the app check for updates each day or you could make a mobile website and use a webview to display the site ,and just update the site daily
Since you are using text and images, I would recommend storing them in your app's SharedPreferences. These keep data stored that your app can easily access to view or change. You can store text and bitmaps easily. For text:
SharedPreferences prefs = getSharedPreferences("MySharedPreferences", Activity.MODE_PRIVATE);
SharedPreferences.Editor preferences = prefs.edit();
String firstString = prefs.getString("MyFirstString");
//check if firstString has changed on the server
//for example, set a new String that you retrieve from the server to firstStringMaybe
if (firstString != firstStringMaybe) { //meaning you need to update firstString
prefs.putString("MyFirstString", firstStringMaybe);
prefs.commit();
}
Bitmaps storage is much more complicated, because you need to first Serialize the bitmap, then store it as a String. This probably means creating a new class that contains the bitmap object and implements Serializable. There are many examples available for how to do this:
http://www.johnwordsworth.com/2011/06/serializing-and-de-serializing-android-graphics-bitmap/
android how to save a bitmap - buggy code

Categories

Resources