Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save data in an android app

Tags:

android

I recently coded an Android app. It's just a simple app that allows you to keep score of a basketball game with a few simple counter intervals. I'm getting demand to add a save feature, so you can save your scores and then load them back up. Currently, when you stop the app, your data is lost. So what I was wondering is what I would have to add to have the app save a label (score) and then load it back up. Thanks guys sorry I don't know much about this stuff.

like image 922
user1446371 Avatar asked Jun 09 '12 15:06

user1446371


People also ask

How do you store app data?

If the data is very, very simple, and you need it to be readable by other applications or users (with appropriate permissions), I would probably choose to store it in an XML file or even a plain-text file inside the user's Application Data folder, which would be obtained via Environment.

How many ways can Android apps store data?

Android provides two types of physical storage locations: internal storage and external storage. On most devices, internal storage is smaller than external storage. However, internal storage is always available on all devices, making it a more reliable place to put data on which your app depends.

How can I persist information in an Android device?

Android supports the following ways of storing data in the local file system: Files - You can create and update files. Preferences - Android allows you to save and retrieve persistent key-value pairs of primitive data type. SQLite database - instances of SQLite databases are also stored on the local file system.

How to save application data in Android system?

The Android system provides different options to save application data: Let us go through these all one by one. 1. Android Application-specific storage In this, the stored data is meant only for a specific application’s use. It is stored either in a dedicated directory inside the internal storage or in external storage.

How do I preserve my app and user data?

Learn how to preserve your app and user data either as files on the device, in key-value pairs, in a database, or with other data types, and share data between other apps and devices. You can also add a backup service to let users store information in the cloud, sync it across devices, and recover it when they get a new device.

Where are files saved on Android phone?

Internal Storage in Android Files can be saved directly in the “internal” storage of the device. When the files are saved in the internal storage, they are automatically set to private. These files are set to private so they cannot be used by other applications.

What are the different storage options in Android?

There is a lot of options to store your data and Android offers you to chose anyone Your data storage options are the following: Shared Preferences Store private primitive data in key-value pairs. Internal Storage Store private data on the device memory. External Storage Store public data on the shared external storage.


2 Answers

You have two options, and I'll leave selection up to you.

  1. Shared Preferences

    This is a framework unique to Android that allows you to store primitive values (such as int, boolean, and String, although strictly speaking String isn't a primitive) in a key-value framework. This means that you give a value a name, say, "homeScore" and store the value to this key.

    SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putInt("homeScore", YOUR_HOME_SCORE);  // Apply the edits! editor.apply();  // Get from the SharedPreferences SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0); int homeScore = settings.getInt("homeScore", 0); 
  2. Internal Storage

    This, in my opinion, is what you might be looking for. You can store anything you want to a file, so this gives you more flexibility. However, the process can be trickier because everything will be stored as bytes, and that means you have to be careful to keep your read and write processes working together.

    int homeScore; byte[] homeScoreBytes;  homeScoreBytes[0] = (byte) homeScore; homeScoreBytes[1] = (byte) (homeScore >> 8);  //you can probably skip these two  homeScoreBytes[2] = (byte) (homeScore >> 16); //lines, because I've never seen a                                                                  //basketball score above 128, it's                                               //such a rare occurance.  FileOutputStream outputStream = getApplicationContext().openFileOutput(FILENAME, Context.MODE_PRIVATE); outputStream.write(homeScoreBytes); outputStream.close(); 

Now, you can also look into External Storage, but I don't recommend that in this particular case, because the external storage might not be there later. (Note that if you pick this, it requires a permission)

like image 51
gobernador Avatar answered Oct 03 '22 02:10

gobernador


OP is asking for a "save" function, which is more than just preserving data across executions of the program (which you must do for the app to be worth anything.)

I recommend saving the data in a file on the sdcard which allows you to not only recall it later, but allows the user to mount the device as an external drive on their own computer and grab the data for use in other places.

So you really need a multi-point system:

1) Implement onSaveInstanceState(). In this method, you're passed a Bundle, which is basically like a dictionary. Store as much information in the bundle as would be needed to restart the app exactly where it left off. In your onCreate() method, check for the passed-in bundle to be non-null, and if so, restore the state from the bundle.

2) Implement onPause(). In this method, create a SharedPreferences editor and use it to save whatever state you need to start the app up next time. This mainly consists of the users' preferences (hence the name), but anything else relavent to the app's start-up state should go here as well. I would not store scores here, just the stuff you need to restart the app. Then, in onCreate(), whenever there's no bundle object, use the SharedPreferences interface to recall those settings.

3a) As for things like scores, you could follow Mathias's advice above and store the scores in the directory returned in getFilesDir(), using openFileOutput(), etc. I think this directory is private to the app and lives in main storage, meaning that other apps and the user would not be able to access the data. If that's ok with you, then this is probably the way to go.

3b) If you do want other apps or the user to have direct access to the data, or if the data is going to be very large, then the sdcard is the way to go. Pick a directory name like com/user1446371/basketballapp/ to avoid collisions with other applications (unless you're sure that your app name is reasonably unique) and create that directory on the sdcard. As Mathias pointed out, you should first confirm that the sdcard is mounted.

File sdcard = Environment.getExternalStorageDirectory(); if( sdcard == null || !sdcard.isDirectory()) {     fail("sdcard not available"); } File datadir = new File(sdcard, "com/user1446371/basketballapp/"); if( !datadir.exists() && !datadir.mkdirs() ) {     fail("unable to create data directory"); } if( !datadir.isDirectory() ) {     fail("exists, but is not a directory"); } // Now use regular java I/O to read and write files to data directory 

I recommend simple CSV files for your data, so that other applications can read them easily.

Obviously, you'll have to write activities that allow "save" and "open" dialogs. I generally just make calls to the openintents file manager and let it do the work. This requires that your users install the openintents file manager to make use of these features, however.

like image 20
Edward Falk Avatar answered Oct 03 '22 02:10

Edward Falk