Reading/Writing user preferences file in Android internal memory

checklistOften an app needs to save user preferences or related information. This can be easily saved in the device internal memory as a persistent file. This file can be used to read and write as required.

In the sample code, we define a class called UserData which stores and retrieves various data fields. The actual purpose of the fields is not important – it just serves to show how various data types can be handled viz.String, boolean and int.

The preferred format of data storage is generally xml or json since these are formats which are lightweight and extremely portable across platforms. Here we will use the json format to store data.

THE ACTUAL CODE

Userdata.java has only two main methods: one for writing all the data and the other to retrieve all the data. The other methods are all get/set functions to work with the data fields.

One important point to note is that for files to be read or written , the current application Context must be passed. This is being passed as an argument in the relevant methods.

We use Context.MODE_PRIVATE while accessing the file system so that this file is not accessible to any other app. This also means that if you go looking for this file on your device using the File Manager, you wont find it, because the FileManager is not allowed access to this file.

// handle user data

package com.example.dummy;

import java.io.*;
import java.lang.StringBuilder;
import org.json.*;


import android.content.Context;
import android.util.Log;



public class UserData {

				
	
	private final String FILENAME = "userdata.json";
	
	
	private boolean firstRunDone=false;	// true once app runs the first time
	private boolean dontShowWelcome=true; // dont show welcome message flag
	private int countryId=0;			// selected country id
	private String countryName="";		// selected country name
	private String locationsId="";		// selected locations id list
	private boolean nationalFlag=false;	// show national deals flag
	private String categoryIds = "";	// category ids list
	private String merchantIds = "";	// merchant ids list
	
	
	// constructor
	public UserData() {
		
		
	}
	
	// get methods
	public boolean isFirstRunDone() {
		return firstRunDone;
	}
	
	public boolean getdontShowWelcome() {
		return dontShowWelcome;
	}
	
	public int getCountryId(){
		return countryId;
	}
	
	public String getCountryName(){
		return countryName;
	}
	
	public String getLocations(){
		return locationsId;
	}
	
	public boolean getNational(){
		return nationalFlag;
	}
	
	public String getCategoryIds() {
		return categoryIds;
	}
	
	public String getMerchantIds() {
		return merchantIds;
	}
	
	
	// set methods
	public void setFirstRunDone(boolean v) {
		firstRunDone = v;
	}
	
	public void setdontShowWelcome(boolean v) {
		dontShowWelcome = v;
	}
	
	public void setCountryId(int c){
		countryId = c;
	}
	
	public void setCountryName(String c){
		countryName = c;
	}
	
	public void setLocations(String locations){
		locationsId = locations;
	}
	
	public void setNational(boolean n){
		nationalFlag = n;
	}
	
	public void setCategoryIds(String c) {
		categoryIds = c;
	}
	
	public void setMerchantIds(String m) {
		merchantIds = m;
	}
	
		
	// 
	// read data from file
	// param context - application context 
	// return true if not error, otherwise false
	public boolean loadData(Context context){
		boolean retVal = true;
		
		try {
			InputStream input = context.openFileInput(FILENAME);
			if (input != null) {
				
				InputStreamReader in = new InputStreamReader(input);
				BufferedReader in2 = new BufferedReader(in);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = in2.readLine()) != null){
					sb.append(line);
					
				}
				in2.close();
				in.close();
				
	
				
				try {
				// fill data from json object
				JSONObject json = new JSONObject(sb.toString());

				
				if (json.get("firstrundone").equals("1"))
					firstRunDone = true;
				else
					firstRunDone = false;
			
				if (json.get("dontshowwelcome").equals("1"))
					dontShowWelcome = true;
				else
					dontShowWelcome = false;

				countryId = Integer.parseInt((String)json.get("countryid"));			
				countryName = (String) json.get("countryName");		
				locationsId = (String) json.get("locationsid");
				if (json.get("nationalflag").equals("1"))
					nationalFlag = true;
				else
					nationalFlag = false;
					
				categoryIds  = (String) json.get("categoryids"); 
				merchantIds = (String) json.get("merchantids");				
				
				} catch (JSONException je) {
					
					Log.e("json error reading data", je.toString());
                                        retVal = false;
				}
				
			} // if (input != null)
			else
				retVal = false;
			
		} catch (IOException ie) {
			Log.e("File reading error", ie.toString());
			retVal = false;
		}
		
		
		
		return retVal;
	}
	
	//
	// write data to file
	// param context - application context
	// return true if not error, otherwise false
	//
	public boolean writeData(Context context) {
		boolean retVal = true;
		
		//make json array of all fields
		JSONObject json = new JSONObject();
		
		try {
			if (firstRunDone)
				json.put("firstrundone", "1");
			else
				json.put("firstrundone", "0");
			if (dontShowWelcome)
				json.put("dontshowwelcome", "1");
			else
				json.put("dontshowwelcome", "0");
			json.put("countryid", String.valueOf(countryId));			
			json.put("countryName", countryName);		
			json.put("locationsid", locationsId);
			if (nationalFlag)
				json.put("nationalflag", "1");	
			else
				json.put("nationalflag", "0");
				
			json.put("categoryids", categoryIds); 
			json.put("merchantids", merchantIds);
		
		} catch (JSONException je) {
			Log.e("JSON Error", je.toString());
                       retVal = false;
		}
		
		// write data
		try {
			OutputStreamWriter out = new OutputStreamWriter(
					context.openFileOutput(FILENAME, Context.MODE_PRIVATE));
			
			out.write(json.toString());
			out.close();
			
		} catch (IOException ie) {
			
			Log.e("File creation error", ie.toString());
                        retVal = false;
		}	
		
		return retVal;
		
	}
	
}

THE CALLING CODE

The sample code below shows how to call the UserData class to get and set data.

protected void test() {
             UserData user = new UserData();
                         // if file is present 
             if (user.loadData(this)) {
				
			if (user.isFirstRunDone()) {
				if (user.getdontShowWelcome())
					// do something
				else
					// do something else
			}
				
		}
		else {
				// write new data
                          user.setCategoryIds("1,4,5");
                          user.setMerchantIds("50");
                          user.writeData();
		}
}

1 Comment

Leave a Reply

Your email address will not be published.


*