{"id":1873,"date":"2013-06-13T06:16:50","date_gmt":"2013-06-13T06:16:50","guid":{"rendered":"http:\/\/truelogic.org\/wordpress\/?p=1873"},"modified":"2013-06-13T06:23:25","modified_gmt":"2013-06-13T06:23:25","slug":"readingwriting-user-preferences-file-android-internal-memory","status":"publish","type":"post","link":"https:\/\/truelogic.org\/wordpress\/2013\/06\/13\/readingwriting-user-preferences-file-android-internal-memory\/","title":{"rendered":"Reading\/Writing user preferences file in Android internal memory"},"content":{"rendered":"            <script type=\"text\/javascript\" src=\"https:\/\/truelogic.org\/wordpress\/wp-content\/plugins\/wordpress-code-snippet\/scripts\/shBrushJava.js\"><\/script>\n<p><a href=\"https:\/\/truelogic.org\/wordpress\/wp-content\/uploads\/2013\/06\/checklist.jpeg\"><img loading=\"lazy\" decoding=\"async\" class=\"alignleft size-full wp-image-1903\" alt=\"checklist\" src=\"https:\/\/truelogic.org\/wordpress\/wp-content\/uploads\/2013\/06\/checklist.jpeg\" width=\"225\" height=\"224\" srcset=\"https:\/\/truelogic.org\/wordpress\/wp-content\/uploads\/2013\/06\/checklist.jpeg 225w, https:\/\/truelogic.org\/wordpress\/wp-content\/uploads\/2013\/06\/checklist-150x150.jpeg 150w\" sizes=\"auto, (max-width: 225px) 100vw, 225px\" \/><\/a>Often 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.<\/p>\n<p>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 &#8211; it just serves to show how various data types can be handled viz.String, boolean and int.<\/p>\n<p>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.<\/p>\n<p><strong>THE ACTUAL CODE<\/strong><\/p>\n<p>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.<\/p>\n<p>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.<\/p>\n<p>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.<\/p>\n<p><pre class=\"brush: java\">\/\/ handle user data\r\n\r\npackage com.example.dummy;\r\n\r\nimport java.io.*;\r\nimport java.lang.StringBuilder;\r\nimport org.json.*;\r\n\r\n\r\nimport android.content.Context;\r\nimport android.util.Log;\r\n\r\n\r\n\r\npublic class UserData {\r\n\r\n\t\t\t\t\r\n\t\r\n\tprivate final String FILENAME = &quot;userdata.json&quot;;\r\n\t\r\n\t\r\n\tprivate boolean firstRunDone=false;\t\/\/ true once app runs the first time\r\n\tprivate boolean dontShowWelcome=true; \/\/ dont show welcome message flag\r\n\tprivate int countryId=0;\t\t\t\/\/ selected country id\r\n\tprivate String countryName=&quot;&quot;;\t\t\/\/ selected country name\r\n\tprivate String locationsId=&quot;&quot;;\t\t\/\/ selected locations id list\r\n\tprivate boolean nationalFlag=false;\t\/\/ show national deals flag\r\n\tprivate String categoryIds = &quot;&quot;;\t\/\/ category ids list\r\n\tprivate String merchantIds = &quot;&quot;;\t\/\/ merchant ids list\r\n\t\r\n\t\r\n\t\/\/ constructor\r\n\tpublic UserData() {\r\n\t\t\r\n\t\t\r\n\t}\r\n\t\r\n\t\/\/ get methods\r\n\tpublic boolean isFirstRunDone() {\r\n\t\treturn firstRunDone;\r\n\t}\r\n\t\r\n\tpublic boolean getdontShowWelcome() {\r\n\t\treturn dontShowWelcome;\r\n\t}\r\n\t\r\n\tpublic int getCountryId(){\r\n\t\treturn countryId;\r\n\t}\r\n\t\r\n\tpublic String getCountryName(){\r\n\t\treturn countryName;\r\n\t}\r\n\t\r\n\tpublic String getLocations(){\r\n\t\treturn locationsId;\r\n\t}\r\n\t\r\n\tpublic boolean getNational(){\r\n\t\treturn nationalFlag;\r\n\t}\r\n\t\r\n\tpublic String getCategoryIds() {\r\n\t\treturn categoryIds;\r\n\t}\r\n\t\r\n\tpublic String getMerchantIds() {\r\n\t\treturn merchantIds;\r\n\t}\r\n\t\r\n\t\r\n\t\/\/ set methods\r\n\tpublic void setFirstRunDone(boolean v) {\r\n\t\tfirstRunDone = v;\r\n\t}\r\n\t\r\n\tpublic void setdontShowWelcome(boolean v) {\r\n\t\tdontShowWelcome = v;\r\n\t}\r\n\t\r\n\tpublic void setCountryId(int c){\r\n\t\tcountryId = c;\r\n\t}\r\n\t\r\n\tpublic void setCountryName(String c){\r\n\t\tcountryName = c;\r\n\t}\r\n\t\r\n\tpublic void setLocations(String locations){\r\n\t\tlocationsId = locations;\r\n\t}\r\n\t\r\n\tpublic void setNational(boolean n){\r\n\t\tnationalFlag = n;\r\n\t}\r\n\t\r\n\tpublic void setCategoryIds(String c) {\r\n\t\tcategoryIds = c;\r\n\t}\r\n\t\r\n\tpublic void setMerchantIds(String m) {\r\n\t\tmerchantIds = m;\r\n\t}\r\n\t\r\n\t\t\r\n\t\/\/ \r\n\t\/\/ read data from file\r\n\t\/\/ param context - application context \r\n\t\/\/ return true if not error, otherwise false\r\n\tpublic boolean loadData(Context context){\r\n\t\tboolean retVal = true;\r\n\t\t\r\n\t\ttry {\r\n\t\t\tInputStream input = context.openFileInput(FILENAME);\r\n\t\t\tif (input != null) {\r\n\t\t\t\t\r\n\t\t\t\tInputStreamReader in = new InputStreamReader(input);\r\n\t\t\t\tBufferedReader in2 = new BufferedReader(in);\r\n\t\t\t\tStringBuilder sb = new StringBuilder();\r\n\t\t\t\tString line = null;\r\n\t\t\t\twhile ((line = in2.readLine()) != null){\r\n\t\t\t\t\tsb.append(line);\r\n\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\tin2.close();\r\n\t\t\t\tin.close();\r\n\t\t\t\t\r\n\t\r\n\t\t\t\t\r\n\t\t\t\ttry {\r\n\t\t\t\t\/\/ fill data from json object\r\n\t\t\t\tJSONObject json = new JSONObject(sb.toString());\r\n\r\n\t\t\t\t\r\n\t\t\t\tif (json.get(&quot;firstrundone&quot;).equals(&quot;1&quot;))\r\n\t\t\t\t\tfirstRunDone = true;\r\n\t\t\t\telse\r\n\t\t\t\t\tfirstRunDone = false;\r\n\t\t\t\r\n\t\t\t\tif (json.get(&quot;dontshowwelcome&quot;).equals(&quot;1&quot;))\r\n\t\t\t\t\tdontShowWelcome = true;\r\n\t\t\t\telse\r\n\t\t\t\t\tdontShowWelcome = false;\r\n\r\n\t\t\t\tcountryId = Integer.parseInt((String)json.get(&quot;countryid&quot;));\t\t\t\r\n\t\t\t\tcountryName = (String) json.get(&quot;countryName&quot;);\t\t\r\n\t\t\t\tlocationsId = (String) json.get(&quot;locationsid&quot;);\r\n\t\t\t\tif (json.get(&quot;nationalflag&quot;).equals(&quot;1&quot;))\r\n\t\t\t\t\tnationalFlag = true;\r\n\t\t\t\telse\r\n\t\t\t\t\tnationalFlag = false;\r\n\t\t\t\t\t\r\n\t\t\t\tcategoryIds  = (String) json.get(&quot;categoryids&quot;); \r\n\t\t\t\tmerchantIds = (String) json.get(&quot;merchantids&quot;);\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t} catch (JSONException je) {\r\n\t\t\t\t\t\r\n\t\t\t\t\tLog.e(&quot;json error reading data&quot;, je.toString());\r\n                                        retVal = false;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t} \/\/ if (input != null)\r\n\t\t\telse\r\n\t\t\t\tretVal = false;\r\n\t\t\t\r\n\t\t} catch (IOException ie) {\r\n\t\t\tLog.e(&quot;File reading error&quot;, ie.toString());\r\n\t\t\tretVal = false;\r\n\t\t}\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\treturn retVal;\r\n\t}\r\n\t\r\n\t\/\/\r\n\t\/\/ write data to file\r\n\t\/\/ param context - application context\r\n\t\/\/ return true if not error, otherwise false\r\n\t\/\/\r\n\tpublic boolean writeData(Context context) {\r\n\t\tboolean retVal = true;\r\n\t\t\r\n\t\t\/\/make json array of all fields\r\n\t\tJSONObject json = new JSONObject();\r\n\t\t\r\n\t\ttry {\r\n\t\t\tif (firstRunDone)\r\n\t\t\t\tjson.put(&quot;firstrundone&quot;, &quot;1&quot;);\r\n\t\t\telse\r\n\t\t\t\tjson.put(&quot;firstrundone&quot;, &quot;0&quot;);\r\n\t\t\tif (dontShowWelcome)\r\n\t\t\t\tjson.put(&quot;dontshowwelcome&quot;, &quot;1&quot;);\r\n\t\t\telse\r\n\t\t\t\tjson.put(&quot;dontshowwelcome&quot;, &quot;0&quot;);\r\n\t\t\tjson.put(&quot;countryid&quot;, String.valueOf(countryId));\t\t\t\r\n\t\t\tjson.put(&quot;countryName&quot;, countryName);\t\t\r\n\t\t\tjson.put(&quot;locationsid&quot;, locationsId);\r\n\t\t\tif (nationalFlag)\r\n\t\t\t\tjson.put(&quot;nationalflag&quot;, &quot;1&quot;);\t\r\n\t\t\telse\r\n\t\t\t\tjson.put(&quot;nationalflag&quot;, &quot;0&quot;);\r\n\t\t\t\t\r\n\t\t\tjson.put(&quot;categoryids&quot;, categoryIds); \r\n\t\t\tjson.put(&quot;merchantids&quot;, merchantIds);\r\n\t\t\r\n\t\t} catch (JSONException je) {\r\n\t\t\tLog.e(&quot;JSON Error&quot;, je.toString());\r\n                       retVal = false;\r\n\t\t}\r\n\t\t\r\n\t\t\/\/ write data\r\n\t\ttry {\r\n\t\t\tOutputStreamWriter out = new OutputStreamWriter(\r\n\t\t\t\t\tcontext.openFileOutput(FILENAME, Context.MODE_PRIVATE));\r\n\t\t\t\r\n\t\t\tout.write(json.toString());\r\n\t\t\tout.close();\r\n\t\t\t\r\n\t\t} catch (IOException ie) {\r\n\t\t\t\r\n\t\t\tLog.e(&quot;File creation error&quot;, ie.toString());\r\n                        retVal = false;\r\n\t\t}\t\r\n\t\t\r\n\t\treturn retVal;\r\n\t\t\r\n\t}\r\n\t\r\n}\r\n<\/pre><\/p>\n<p><strong>THE CALLING CODE<\/strong><\/p>\n<p>The sample code below shows how to call the UserData class to get and set data.<br \/>\n<pre class=\"brush: java\">protected void test() {\r\n             UserData user = new UserData();\r\n                         \/\/ if file is present \r\n             if (user.loadData(this)) {\r\n\t\t\t\t\r\n\t\t\tif (user.isFirstRunDone()) {\r\n\t\t\t\tif (user.getdontShowWelcome())\r\n\t\t\t\t\t\/\/ do something\r\n\t\t\t\telse\r\n\t\t\t\t\t\/\/ do something else\r\n\t\t\t}\r\n\t\t\t\t\r\n\t\t}\r\n\t\telse {\r\n\t\t\t\t\/\/ write new data\r\n                          user.setCategoryIds(&quot;1,4,5&quot;);\r\n                          user.setMerchantIds(&quot;50&quot;);\r\n                          user.writeData();\r\n\t\t}\r\n}<\/pre><\/p>\n","protected":false},"excerpt":{"rendered":"<div class=\"mh-excerpt\"><p>Often an app needs to save user preferences or related information. This can be easily saved in the device internal memory as a persistent file. <a class=\"mh-excerpt-more\" href=\"https:\/\/truelogic.org\/wordpress\/2013\/06\/13\/readingwriting-user-preferences-file-android-internal-memory\/\" title=\"Reading\/Writing user preferences file in Android internal memory\">[&#8230;]<\/a><\/p>\n<\/div>","protected":false},"author":1,"featured_media":1903,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[295],"tags":[],"class_list":["post-1873","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-android-dev"],"_links":{"self":[{"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/posts\/1873","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/comments?post=1873"}],"version-history":[{"count":11,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/posts\/1873\/revisions"}],"predecessor-version":[{"id":1905,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/posts\/1873\/revisions\/1905"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/media\/1903"}],"wp:attachment":[{"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/media?parent=1873"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/categories?post=1873"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/tags?post=1873"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}