How should I store permanent variables [closed] - android

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am making an app that my wife can use to check if a certain IC friendly or not. The problem is that I need 5 columns if you will (foodName, safe, try, avoid, foodCategory. Each may or may not have a description of the food name under safe, try, avoid. Should I use a database an .xls file or can I do it in xml?

It depends on your requirement/ useage
use sharedPreferences or sqlite database
if you want to store data for long term use sqlite
and if you want to maintain sessions use SharedPreferences.
SharedPreference
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.commit();
Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value. and it requires API 11
}
And for using Sqlite #Sri Hari have shown you an example..

Create a new SQLite database and store it. her you can store multiple tables safely.
public class DictionaryOpenHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DICTIONARY_TABLE_NAME = "dictionary";
private static final String DICTIONARY_TABLE_CREATE =
"CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" +
KEY_WORD + " TEXT, " +
KEY_DEFINITION + " TEXT);";
DictionaryOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DICTIONARY_TABLE_CREATE);
}
}

For storing data in android you can use:
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
SQLite Databases - Store structured data in a private database
Network Connection - Store data on the web with your own network
server.
IMO for your purposes the most efficient option can be Shared Prefeerences or SQLite Database
More details for storing data you can find here.
Please note that you can look also for some ORMs to make it easier with SQLite Database - GreenDAO, OrmLite,...

Related

how to store notifications from firebase to android app using shared preferences [duplicate]

This question already has answers here:
Append more values to Shared Preferences rather than overwriting the existing values
(3 answers)
Closed 5 years ago.
I want to store notifications received from Firebase in my android app. I am using SharedPreferences for that. The problem is when I send notification more then 1 time it overwrites the previous one.
String[] notif={"","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""};
ListAdapter yo = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,notif);
ListView yup = findViewById(R.id.list1);
yup.setAdapter(yo);
SharedPreferences sharedPref = getSharedPreferences("notification", Context.MODE_PRIVATE);
String y = sharedPref.getString("notify","");
notif[1]=y;
just create another class AppCache. In which you have to do all sharedPreference related work like storing/retrieving the data from/into sharedPreference. Here is the class
public class AppCache {
private static final String PREF = "notificationApp";
private static final String COUNT_KEY = "count_key";
public static void saveNotification(Context context, String notification) {
SharedPreferences sharedPref = context.getSharedPreferences(PREF, Context.MODE_PRIVATE);
int count = sharedPref.getInt(COUNT_KEY , 0);
count++;
sharedPref.edit().putString("notification"+count, notification).apply();
//saving count in prefs
sharedPref.edit().putInt(COUNT_KEY , count).apply();
}
}
1 -> In SharedPreferences create another integer for count that will hold the number of notifications in sharedPreferences.
2 -> While saving the notification in sharedpreference, use a unique key for every notification,for example you can use a combination of any string and the count which you declared before like "notification"+(count++). count++ will create a new key for every new notification.
3 -> Now you can retrieve all notification by using count.

How to write a database for an android app [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
In my app I need a database with different tables that I would write before and then just read in the app. I know how to create a new database, write and read it in the app using SQL but I actually don't know with what program (and in which format) I can write the database before adding it in the assets folder.
Would anyone help me with that, please?
You can use http://sqlitebrowser.org/ It run on Mac OS , Windows and Linux
You can use SQLite, which is an on-device SQL implementation. Be aware that this will only support a subset of SQL operations found in most traditional relational DBs. If you need full SQL support you'll have to write back-end web services hosted elsewhere.
You can use SQLiteOpenHelper for creating your database.
Here is my example to create simple database that have store City with 2 filed is City_ID and City_Name:
public class DiLiBusDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "DiLiBusDB";
private static final String TBL_CITY = "City";
private static final String CITY_ID_FIELD = "City_ID";
private static final String CITY_NAME_FIEDL = "City_Name";
private SQLiteDatabase database;
private static DiLiBusDatabaseHelper mInstance = null;
Context context;
//synchronized to make sure have only one thread is run at the same time
public static DiLiBusDatabaseHelper getInstance(Context context){
if(mInstance == null){
mInstance = new DiLiBusDatabaseHelper(context.getApplicationContext());
}
return mInstance;
}
private DiLiBusDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 2);
this.context = context;
this.database = getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE"+" "+TBL_CITY+"("+CITY_ID_FIELD+" "+"TEXT PRIMARY KEY,"+CITY_NAME_FIEDL+" "+"TEXT"+");";
String queryIndex = "CREATE INDEX city_name_idx ON"+ " "+TBL_CITY +"("+CITY_NAME_FIEDL+");";
db.execSQL(query);
db.execSQL(queryIndex);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
p/s: I using Singleton pattern to create my database. Moreover, if you want to save your db in SDCard, u can check this link
There are many libraries for database:
Realm
Active Android
Green DAO
This is the simplest way for creating database because you operates on your defined data models.

Android - Saving Player data - Comparison of 3 different options [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Welcome everyone!
I'm programming a mobile game on Anroid.
I really want to know how to save Player Data.
It will be a game that can be run on different devices without loss of data.
Using SharedPreferences
Using JSONObject, JSONArray and save it into file in Internal Storage and upload it to the external server
SQLite, MySQL
What would you choose? What are the pros and cons of each option?
I would like to save data for example:
Highscore
Life
Mana
Count of steps
Level of character
Amount of money
and more...
SharedPreferences should be the way to go for such a small amount of data. There are many benefits to using them over SQLite in this example.
I would discourage using external server because I personally would not like my game to require internet for playing.
It depends on how much player data there will be. But unless there is a lot of player data, I would suggest using shared preferences, especially if there is something simple like a Player object, or a list of Player objects. that will cover it.
You could use something like the following for a list of Players, and change any reference to that list to just a Player object if you only want to save 1. If you have a lot of data, players, or would need extra security you may want to go with SQLLite.
public class PlayerPrefs {
private static final String PLAYERS_PREF_FILE = "PLAYERS_PREF_FILE";
private static final String PLAYERS = "PLAYERS";
private static SharedPreferences getPrefs(){
final Context context = ApplicationData.getAppContext();
return context.getSharedPreferences(PLAYERS_PREF_FILE, Context.MODE_PRIVATE);
}
public static List<Player> getPlayers() {
final Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<Player>>() {}.getType();
SharedPreferences prefs = getPrefs();
String players = prefs.getString(PLAYERS, null);
if (players == null){
return new ArrayList<Player>();
}
return gson.fromJson(players, listType);
}
public static void setPlayers(List<Player> players) {
final Gson gson = new Gson();
if (players != null) {
final SharedPreferences prefs = getPrefs();
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PLAYERS, gson.toJson(players));
editor.apply();
}
}
}
Also, you'll need to include the following in your Gradle file:
compile 'com.google.code.gson:gson:2.5'

How do i use shared pref file for my app's log in page [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
In my application I got user info in shared pref file. When user enter their details on the log in page, I want only users whose info is in shared pref file to log in. How can I do that?
You can use your apps shared preferences. The prefs can be accessed anytime using the key you set for these prefs.
static final String KEY_USERNAME = "username";
static final String KEY_PASSWORD = "password";
if (saveLogInDetail) { //save username and pw to prefs
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor ed = prefs.edit();
ed.putString(KEY_USERNAME, theUsername);
ed.putString(KEY_PASSWORD, thePW);
ed.commit();
}
To access the information or check the valid username and password use this:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String storedUsername = prefs.getString(KEY_USERNAME, "Default Value if not found");
String storedPassword = prefs.getString(KEY_PASSWORD, ""); //return nothing if no pass saved
Store your login data in sharedpreferences:
String username="dipali";
String pass="1111";
SharedPreferences.Editor editor = viewLoginScreen
.getSharedPreferences(
"prefernce",
Context.MODE_PRIVATE).edit();
editor.putString(
"username",
user);
editor.commit();
SharedPreferences.Editor editor = viewLoginScreen
.getSharedPreferences(
"prefernce",
Context.MODE_PRIVATE).edit();
editor.putString(
"pass",
pass);
editor.commit();
get shared prefences data:
SharedPreferences shar = viewLoginScreen
.getSharedPreferences(
"prefernce",
Context.MODE_PRIVATE);
String username=shar.getString("username","");
String pass=shar.getString("pass","");
you should use SQlite Database instead of using share preference. Once you set up database then insert user credentials to database if user is a not register. And in your case check if current user is in database if exits authenticate him other wise you can force him to register to application. You can see sqlite in detail here http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html

Storing an arraylist for retrieval in Android

I'm currently working on an Android application that is going to be somewhat like a student planner. My backend is all java and I am currently stuck because i am storing the objects that i create from my backend to arraylist. Being java, these objects dissapear as soon as the programs terminate. Whats the easiest way that i can store my java objects for retrieval the next time i boot my application? Any help is much appreciated! Im developing on 2.3 and eclipse(juno).
One of the data storage options listed in the Android developer tutorial will be the easiest thing to do. Which is the best fit will depend on how much data you're storing and how you need to access it. As the page says, the SharedPreferences class is best for a handful of items; for larger data sets, you could use Java serialization or some other way to write them to a file on the phone's storage; and if your data are large and/or you need structured access to them, an SQLite database is your best bet.
You can use Shared Preferences to store your data. The SharedPreferences lets you persist key-value pairs of primitive data types in you application. You can't store an entire ArrayList with a single key, but you can iterate over the array and systematically generate a key for each value in the list. I usually do something like this:
public class SomeActivity extends Activity {
private ArrayList<Data> list; //We'll persist this array
/* snip */
//These strings can be anything - you just need something you can use to systematically generate distinct keys
public static final String LIST_KEY = "SomeActivity_List";
public static final String LIST_LENGTH_KEY = "SomeActivity_ListLength";
/**
* How this method works: It starts by getting a SharedPreferences object,
* which offers an API for persisting data. It then systematically generates
* Strings like "SomeActivity_List1", "SomeActivity_List2", "SomeActivity_List3",
* and so on to use as keys fot the 1st, 2nd, 3rd, etc. elements in the list. Then
* it Data.saveData(), a method defined below in the Data class, in order to give
* each Data object in the ArrayList an opportunity to persist its primitive
* members in the SharedPreferences.
*
* SomeActivity.restoreList() works similarly.
*/
public void saveList() {
SharedPreferences prefs = getPreferences(); //This method is part of the Activity class
SharedPreferences.Editor editor = prefs.getEditor();
//Save the length of the list so that when we restore it, we know how many
//Data objects to recreate.
editor.putInt(LIST_LENGTH_KEY, list.size());
editor.commit();
//This for loop is important - note how we concatenate i to each of the keys to give each element in list a distinct key
for(int i = 0; i < list.size(); i++)
{
String identifier = LIST_KEY + Integer.toString(i); //generate distinct keys
list.get(i).saveData(identifier, prefs);
}
}
public void restoreList() {
SharedPreferences prefs = getPreferences();
int length = prefs.getInt(LIST_LENGTH_KEY);
for(int i = 0; i < length; i++)
{
String identifier = LIST_KEY + Integer.toString(i); //re-generate distinct keys
Data data = new Data();
data.restoreData(identifier, prefs);
list.addLast(data);
}
}
public static class Data {
private int i;
private double j;
private String s;
public static final String I_KEY = "Data_I"
public static final String J_KEY = "Data_J" //strings can really be whatever, as long as they're distinct.
public static final String S_KEY = "Data_K"
/**
* How this method works: The SomeActivity.saveList() method generates a
* unique String ("identifier") for each of the Data objects it contains.
* This method uses that distinct string and makes some more distinct keys
* to store each of Data's primitive members.
*
* restoreData() works similarly when it rebuilds Data objects
*/
public saveData(String identifier, SharedPreferences prefs) {
SharedPreferences.Editor editor = prefs.getEditor();
editor.putInt(I_KEY + identifier, i);
editor.putDouble(J_KEY + identifier, j);
editor.putString(S_KEY + identifier, s);
editor.commit();
}
public restoreData(String identifier, SharedPreferences prefs) {
i = prefs.getInt(I_KEY + identifier);
j = prefs.getDouble(J_KEY + identifier);
s = prefs.getString(S_KEY + identifier);
}
}
}
This approach work recursively. If Data had an ArrayList as one of its fields, for example, it could systematically store all of the values in that list in SharedPreferences as well.
FYI: One of the implications of using SharedPreferences is that if the user uninstalls your app or clears the app data, the stored list will be deleted. Depending on the nature of your data, you may or may not want this behavior.

Categories

Resources