android shared preferences implementation - android

hi i have tried to implement a shared preference and everything i try doesn't seem to work. i'm wanting when someone clicks on an item in a list view it stores data about that selection in a shared prerference. when the app loads up i want it to check for a shared preference ie: if there are no preferences go to this activity else go to another activity. i also would like to know if there are some preferences when i get sent to another activity how to retrieve them. its not the first time i have asked this question but i thought id re ask as i wasn't very clear
heres what i have tried so far
protected void onListItemClick (ListView l, View v, int position, long id) {
Intent intent = new Intent(this, HomeActivity.class);
try {
Log.v("lc", "try1");
JSONObject singleTeamDictionary = teamNamesArray.getJSONObject(position);
Log.v("lc", "dictionary:" + singleTeamDictionary);
Log.v("lc", "try2");
ChosenTeam = (String) singleTeamDictionary.get("name");
ChosenTeamId = (String) singleTeamDictionary.get("team_id");
ChosenLeagueId = (String) singleTeamDictionary.get("league_id");
ChosenDivisionID = (String) singleTeamDictionary.get("division_id");
Log.v("lc", "try3");
Log.v("lc", "ChosenTeam: " + ChosenTeam);
Log.v("lc", "ChosenTeamId: " + ChosenTeamId);
Log.v("lc", "ChosenLeagueId: " + ChosenLeagueId);
Log.v("lc", "ChosenDivisionID: " + ChosenDivisionID);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.v("lc", "catch");
}
String curPos = Integer.toString(position);
Log.v("lc", "teamPos: " + curPos);
SharedPreferences preferences = getSharedPreferences("prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("ChosenMethod", "Team");
editor.putString("ChosenTeam", ChosenTeam);
editor.putString("ChosenTeamId", ChosenTeamId);
editor.putString("ChosenLeagueId", ChosenLeagueId);
editor.putString("ChosenDivisionID", ChosenDivisionID);
editor.commit();
//or just use the position:
intent.putExtra("itemIndex", curPos);
intent.putExtra("fullData", fulldata); //or just the part you want
startActivity(intent);
}
then in the intro activity
public void checkPreferences(){
SharedPreferences preferences = getSharedPreferences("prefs", Context.MODE_PRIVATE);
String ChosenMethod = preferences.getString("chosenTeam", ChosenTeam);
//String ChosenMethod = preferences.getString("ChosenMethod", null);
//getPWDFromSP()
//SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
//Log.v("myapp", "prefs = " + preferences);
//String ChosenMethod = preferences.getString("ChosenMethod", chosenMethod);
Log.v("myapp", "ChosenMethod = " + ChosenMethod);
if (ChosenMethod != null){
Intent intent = new Intent(TheEvoStikLeagueActivity.this,Activity.class);
}
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
checkPreferences();

"chosenTeam" is not the same as "ChosenTeam".

hope this code helps you
private SharedPreferences sp;
private Editor e;
//create methods
//save method(string)
private void savePreferences(String key,String val){
sp = getSharedPreferences("prefs", 0);
e = sp.edit();
e.putString(key , val);
e.commit();
}
//get method
private String getPreferences(String key){
sp = getSharedPreferences("prefs", 0);
String value = sp.getString(key, "");
return value;
}
//save String
savePreferences("yourKey","yourString");
//get Preferences
getPreferences("yourKey")
//check value saved or not
if(getPreferences("yourKey").equals(null)){
//do something
Log.i("value","null");
}
else{
//do something
Log.i("value","exists");
}
if you want to save integers or boolean,you can edit methods
and let return values as you wish.

Related

how to make the number stay in the latest number instead of going back to the default?

my TxnNo(A0010001) came from Unitcode(A001) + LastTxnNo(0001). This is my button click.
Db_Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Model txn = new Model();// initialize your model class first
BigDecimal paidAmt = new BigDecimal(D_Amount.getText().toString()).setScale(2, RoundingMode.HALF_UP);
txn.setName(D_Name.getText().toString());
txn.setTxnNo(D_Txn.getText().toString());
txn.setTxnDate(Select_Date.getText().toString());
txn.setAmount(paidAmt);
txn.setDescription1(D_Description.getSelectedItem().toString());
txn.setDescription2(Ds_Description.getText().toString());
try {
SQLiteDatabase db = mSQLiteHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("name", txn.getName());
cv.put("TxnNo", txn.getTxnNo());
cv.put("TxnDate", txn.getTxnDate());
cv.put("Amount", txn.getAmount().toPlainString());
cv.put("Description1", txn.getDescription1());
cv.put("Description2", txn.getDescription2());
db.insert("Donation_Details", null, cv);
db.close();
increaseNumber++;
populate_TxnNo();
Toast.makeText(Donation_Page.this, "Add successfully", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
I put increaseNumber++; to make sure it will increase automatically. So Everytime I click the button. the number will change "A0010001" to "A0010002" and so on. But once I leave this page, and go in again. It will back to "A0010001". How to make it stay at the latest number instead of going back to "A0010001".
This is the method to set the numbering.
private void populate_TxnNo() {
int lastNumber = Integer.valueOf(txn.getLastTxnNo());
lastNumber = lastNumber + increaseNumber;
String stringLast = String.format("%04d", lastNumber);
String txnNo = txn.getUnit_Code() + stringLast;
//increaseNumber++;
D_Txn.setText(txnNo);
}
UPDATE
So for me to understand the Shared preference I put those code to the button new.
Db_New.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
increaseNumber++;
populate_TxnNo();
}
});
But I don't know how to use Shared preference even though I see the example of code... Can anyone explain it for me? How to use this code?
SharedPreferences prefs;
SharedPreferences.Editor edit;
prefs=this.getSharedPreferences("yourPrefsKey",Context.MODE_PRIVATE);
edit=prefs.edit();
edit.putString("yourKey", txnNo);
edit.commit();
String txnNo = prefs.getString("yourKey", null);
Firstly, declare these two variables
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
int count;
Next add these in onCreate method
sharedPreferences = getApplicationContext().getSharedPreferences("counters", MODE_PRIVATE);
editor = sharedPreferences.edit();
count = sharedPreferences.getInt("counter", 0);
Finally modify populate_TxnNo methods
private void populate_TxnNo() {
int a = count++;
int lastNumber = Integer.valueOf(txn.getLastTxnNo());
lastNumber = lastNumber + a;
String stringLast = String.format("%04d", lastNumber);
String txnNo = txn.getUnit_Code() + stringLast;
D_Txn.setText(txnNo);
editor.putInt("counter", ++a);
editor.commit();
}
Try using Shared Preference
these two lines before onCreate()
SharedPreferences prefs;
SharedPreferences.Editor edit;
these two lines in onCreate()
prefs=this.getSharedPreferences("yourPrefsKey",Context.MODE_PRIVATE);
edit=prefs.edit();
and on onPause() save the string
#Override
protected void onPause() {
super.onPause();
edit.putString("yourKey", txnNo);
edit.commit();
}
and to access it back simply write in onStart
#Override
protected void onStart() {
super.onStart();
String txnNo = prefs.getString("yourKey", null);
}
simply add yourNumber to shared preferences
int yourNumber;
SharedPreferences number = getSharedPreferences("number", MODE_PRIVATE);
to save your number
number.edit.putInt("number",yourNumber).apply;
and read the number next time
int savedNumber = number.getInt("number",0);

I am trying to pass the values in shared preference from one Activity to another

I am trying to pass the values from one activity to another using shared preference but am getting null value.In the first activity i printed values in console and its getting printed but in that i couldn't retrieve the values.please help me to come out of this error
First activity: values are passed
sharedpreferences.edit().putString("CHECKPASS","changepass").commit();
editor.putString("FOOD",food1);
editor.putString("PLACE",place1);
editor.putString("COLOR",colour1);
editor.putString("BUY",buy1);
editor.commit();
Second Activity: where I am retrieving
Log.d("succ", "reached");
String yourpass = sharedpreferences.getString("CHECKPASS","changepass");
Log.d("succ", "yournext" + yourpass);
if (yourpass.equals("changepass")) {
{
final String foodshared = sharedpreferences.getString("FOOD","NULL");
Log.d("succ", "foodshared" + foodshared);
final String colorshared = sharedpreferences.getString("COLOR", "NULL");
Log.d("succ", "colorshared" + colorshared);
final String buyshared = sharedpreferences.getString("BUY", "NULL");
Log.d("succ", "buyshared" + buyshared);
final String placeshared = sharedpreferences.getString("PLACE", "NULL");
Log.d("succ", "placeshared" + placeshared);
}
Use this code
//For writing data
SharedPreferences.Editor
editor=getSharedPreferences("nameOFSharedPref",MODE_PRIVATE).edit();
editor.putString("CHECKPASS","changepass");
editor.putString("FOOD",food1);
editor.putString("PLACE",place1);
editor.putString("COLOR",colour1);
editor.putString("BUY",buy1);
editor.apply();
//For Reading Data
SharedPreferences sharedPreferences=getSharedPreferences("nameOFSharedPref",MODE_PRIVATE);
String foodshared = sharedPreferences.getString("FOOD","NULL");
String colorshared = sharedPreferences.getString("COLOR", "NULL");
final String buyshared = sharedPreferences.getString("BUY", "NULL");
final String placeshared = sharedPreferences.getString("PLACE", "NULL");
Also while writing data don't use editor.commit() instead use editor.apply() because it handles data in background.
UPDATE:
in your first activity
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);//or MODE_PRIVATE
Editor editor = pref.edit();
editor.putString("CHECKPASS","changepass")
editor.putString("FOOD",food1);
editor.putString("PLACE",place1);
editor.putString("COLOR",colour1);
editor.putString("BUY",buy1);
editor.commit();
IN your secondActivity
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
final String foodshared = pref.getString("FOOD",null);
Log.d("succ", "foodshared" + foodshared);
final String colorshared = pref.getString("COLOR",null);
Log.d("succ", "colorshared" + colorshared);
final String buyshared = pref.getString("BUY",null);
Log.d("succ", "buyshared" + buyshared);
final String placeshared = pref.getString("PLACE",null);
Log.d("succ", "placeshared" + placeshared);
edit:
Initialization
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
Editor editor = pref.edit();
STORE THE DATA
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.commit(); // commit changes
Retrieving Data
pref.getString("key_name", null); // getting String
pref.getBoolean("key_name", null); // getting boolean

Activity calling itself -: Shared Preferences being cleared on pressing back button

I am using the following activity that keeps on calling itself. Things are working fine when I go in the forward direction but as soon as I click the back button, the shared preferrences is cleared.
SharedPreferences userLocalDatabase;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paper_dashboard);
userLocalDatabase = PreferenceManager.getDefaultSharedPreferences(this);
name = userLocalDatabase.getString("name", "");
subject = userLocalDatabase.getString("subject", "");
timeLeft = userLocalDatabase.getInt("timeLeft", -1);
quesNo = userLocalDatabase.getInt("quesNo", -1);
no_of_ques = userLocalDatabase.getInt("no_of_ques", -1);
score = userLocalDatabase.getInt("score", -1);
currentLine = quesNo+1;
Log.i("TAG2", "Krishna the score returned from Shared Preferences is -: " +score);
myQuesTitle = (TextView)findViewById(R.id.myQuesTitle);
myTimer = (TextView)findViewById(R.id.myTimer);
myQuestion = (TextView)findViewById(R.id.myQuestion);
myFinish = (ImageButton)findViewById(R.id.myFinish);
myPrevious = (ImageButton)findViewById(R.id.myPrevious);
myAnswer = (ImageButton)findViewById(R.id.myAnswer);
myHint = (ImageButton)findViewById(R.id.myHint);
myNext = (ImageButton)findViewById(R.id.myNext);
myAnswer1 = (CheckBox)findViewById(R.id.myAnswer1);
myAnswer2 = (CheckBox)findViewById(R.id.myAnswer2);
myAnswer3 = (CheckBox)findViewById(R.id.myAnswer3);
myAnswer4 = (CheckBox)findViewById(R.id.myAnswer4);
String line = setLayout(name, timeLeft, quesNo, no_of_ques);
Log.i("TAG2", "Krishna the line returned is -: " + line);
}
this is the method for calling -:
public void clickPrevious(View v){
calculateScore();
SharedPreferences.Editor spEditor = userLocalDatabase.edit();
spEditor.putString("name", name);
spEditor.putString("subject", subject);
spEditor.putInt("timeLeft", timeLeft);
spEditor.putInt("no_of_ques", no_of_ques);
spEditor.putInt("quesNo", 0);
spEditor.putInt("score", 0 );
spEditor.commit();
Log.i("TAG2", "Baladeva score is -: " + score);
finish();
startActivity(new Intent(paper_dashboard.this, paper_dashboard.class));
}
posting the Next method-:
public void clickNext(View v){
calculateScore();
SharedPreferences.Editor spEditor = userLocalDatabase.edit();
spEditor.putString("name", name);
spEditor.putString("subject", subject);
spEditor.putInt("timeLeft", timeLeft);
spEditor.putInt("no_of_ques", no_of_ques);
spEditor.putInt("quesNo", quesNo+1);
spEditor.putInt("score", score);
spEditor.commit();
Log.i("TAG2", "Baladeva score is -: " + score);
Intent intent = new Intent(new Intent(this, paper_dashboard.class));
//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}

Android: How to store array of strings in SharedPreferences for android

I'm building an app which searches the web using search engine. I have one edittext in my app from which user will search the web. I want to save the search keywords just like browser history does. I'm able to save and display it with the last keyword but I can't increase the number of searches result. I want to display the last 5 searhes. Here is my code :
public class MainActivity extends Activity implements OnClickListener {
Button insert;
EditText edt;
TextView txt1, txt2, txt3, txt4, txt5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt = (EditText) findViewById(R.id.search_word);
txt1 = (TextView) findViewById(R.id.txt1);
txt1.setOnClickListener(this);
insert = (Button) findViewById(R.id.insert);
insert.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if ((edt.getText().toString().equals(""))) {
Toast.makeText(
getBaseContext(),
"Whoa! You haven't entered anything in the search box.",
Toast.LENGTH_SHORT).show();
} else {
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = app_preferences.edit();
String text = edt.getText().toString();
editor.putString("key", text);
editor.commit();
Toast.makeText(getBaseContext(), text, Toast.LENGTH_LONG)
.show();
}
}
});
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(this);
String text = app_preferences.getString("key", "null");
txt1.setText(text);
}
public void onClick(View v) {
String text = txt1.getText().toString();
Toast.makeText(getBaseContext(), text, Toast.LENGTH_SHORT).show();
}
}
Please help me in overcoming this problem.
SAVE ARRAY
public boolean saveArray(String[] array, String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(arrayName +"_size", array.length);
for(int i=0;i<array.length;i++)
editor.putString(arrayName + "_" + i, array[i]);
return editor.commit();
}
LOAD ARRAY
public String[] loadArray(String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(arrayName + "_size", 0);
String array[] = new String[size];
for(int i=0;i<size;i++)
array[i] = prefs.getString(arrayName + "_" + i, null);
return array;
}
Convert your array or object to Json with Gson library and store your data as String in json format.
Save;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(arrayList);
editor.putString(TAG, json);
editor.commit();
Read;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Gson gson = new Gson();
String json = sharedPrefs.getString(TAG, null);
Type type = new TypeToken<ArrayList<ArrayObject>>() {}.getType();
ArrayList<ArrayObject> arrayList = gson.fromJson(json, type);
Original answer: Storing Array List Object in SharedPreferences

getString from a few SharedPreferences file and create listView

First - sorry for my english;) I'am writing profile manager for Android and i want getString from a few SharedPreferences file and create listView. It's part of my code:
private static final String PN = "profile_name";
private EditTextPreference editText;
private SharedPreferences preferences;
public class Profile_Preferences extends PreferenceActivity {
...
private void SavePreferences() {
String text= editText.getText().toString();
preferences = getSharedPreferences("Profile_" + text, Activity.MODE_PRIVATE); //Here we created SharedPreferences file with name "Profile_"+ this what user write in editText
SharedPreferences.Editor preferencesEditor = preferences.edit();
preferencesEditor.putString(PN, editText.getText());
preferencesEditor.commit();
Ok. The user was doing a few profile, so we have file for example: Profile_home.xml, Profile_work.xml, Profile_something.xml. Now i wan't create listView with profile name from this file. It's my next Activity:
public class Tab_profiles extends ListActivity {
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice, listItems);
setListAdapter(adapter);
...
public void LoadList() {
//It's a good idea to getString "profile_name" form every xml file with name "Profile_" + "" ?
preferences = getSharedPreferences("Profile_"+ "", Activity.MODE_PRIVATE);
String take_profile_name = preferences.getString("profile_name", null);
listItems.add(take_profile_name );
adapter.notifyDataSetChanged();
}
But this doesn't work... logcat log:
FATAL EXCEPTION: MAIN
java.land.Null.PointerException
at android.widget.ArrayAdaper.createViewFromResource(ArrayAdapter.java:355)
...
I don't now whoat it's wrong...
Please help my:) Thank you for any answers and sorry for my errors in writing and code;)
There are a few problems in your code:
String text = editText.getText().toString();
preferences = getSharedPreferences("Profile_" + text, Activity.MODE_PRIVATE);
SharedPreferences.Editor preferencesEditor = preferences.edit();
preferencesEditor.putString(PN, editText.getText());
If a user types "home" in the EditText, you create a preference file called "Profile_home" and save its name in the same file? You need to save the user generated file names in a different file which has a name you know, so you can access it in your code.
Second problem:
preferences = getSharedPreferences("Profile_" + "", Activity.MODE_PRIVATE);
String take_profile_name = preferences.getString("profile_name", null);
You're trying to open "Profile_" settings. This file does not exist(?). The second parameter of getString must not be null, otherwise you'll add a null-reference to your list of string, which fails. Replace it with an empty string "".
Edit: Here's a little workaround to get all custom named preferences:
private void SavePreferences() {
String text = editText.getText().toString();
preferences = getSharedPreferences("ProfileNames", Activity.MODE_PRIVATE);
SharedPreferences.Editor preferencesEditor = preferences.edit();
// increment index by 1
preferencesEditor.putInt("profile_count", preferences.getInt("profile_count", 0) + 1);
// save new name in ProfileNames.xml with key "name[index]"
preferencesEditor.putString("name" + (preferences.getInt("profile_count", 0) + 1), editText.getText());
preferencesEditor.commit();
}
public void LoadList() {
preferences = getSharedPreferences("ProfileNames", Activity.MODE_PRIVATE);
List<String> profileNames = new LinkedList<String>();
int profileCount = preferences.getInt("profile_count", 0);
for (int i = 1; i <= profileCount; i++) {
profileNames.add(preferences.getString(name + i, ""));
}
listItems.addAll(profileNames);
adapter.notifyDataSetChanged();
}

Categories

Resources