Save and Load strings - android

I used Menu onOptionsItemSelect(MENU) to save and load strings like this
public static String filename = "MySharedString";
SharedPreferences someData;
String s;
someData = getSharedPreferences(filename, 0);
case R.id.save:
Toast.makeText(getApplicationContext(), "Samples saved", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor1 = someData.edit();
editor1.putString("ourString1", s);
and load like this
case R.id.load:
s = someData.getString("ourString1", "Couldn't Load Data");
and it worked well...as android removed MENU button for many devices i made a new activity which extends MainActivity and I put in Save and Load button.
public void bSave (View v){
SharedPreferences.Editor editor1 = someData.edit();
editor1.putString("ourString1", s);
editor1.commit();
and load
public void bLoad (View v){
s = someData.getString("ourString1", "Couldn't Load Data");
For some reason it doesnt work, I repeat i made new activity ( public class Menu extends MainActivity{ ) which i start as Intent and it wont save or load strings from MainActivity

make sure you are using the button listener properly. check if you set android:onClick attreibute like
android:onClick="bSave"

Related

Shared Preferences Appearing On-Screen

I am creating an attendance tracker for a summer camp, where counsellors can input the time their camper signed in by typing into an editText and pressing the save button. This basic string should be saved into a textbox and loaded onto the screen every time the app is loaded. There are multiple boxes like this so the counsellors can track what times each student came in / left every day.
I have used sharedPreferences to save the input from the counsellor when a button is pressed, and then display it using another button. However, I CANNOT GET THE TEXT TO APPEAR ON THE SCREEN WHEN I CLOSE AND REOPEN THE APP. Is my code missing something??
public class AttendancePage extends AppCompatActivity {
EditText mondayMorn;
TextView displayMonMorn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance_page);
String counsellorName = getIntent().getStringExtra("Senior Counsellor Name");
TextView tv = (TextView)findViewById(R.id.counsellorName);
tv.setText(counsellorName + "'s");
mondayMorn = (EditText) findViewById(R.id.editText37);
displayMonMorn = (TextView) findViewById(R.id.displayMonMorn);
}
public void saveInput (View view) {
SharedPreferences checkInMon = getSharedPreferences("LoginTime", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = checkInMon.edit();
editor.putString("mondayIn", mondayMorn.getText().toString());
editor.apply();
Toast.makeText(this, "Saved", Toast.LENGTH_LONG).show();
}
public void updateSettings (View view){
SharedPreferences checkInMon = getSharedPreferences("LoginTime", Context.MODE_PRIVATE);
String time = checkInMon.getString("mondayIn", "");
displayMonMorn.setText(time);
}
Replace:
SharedPreferences.Editor editor = checkInMon.edit();
editor.putString("mondayIn", mondayMorn.getText().toString());
editor.apply();
with:
SharedPreferences.Editor editor = checkInMon.edit();
editor.putString("mondayIn", mondayMorn.getText().toString());
editor.commit();
that should at least save the data in preferences.

Android SharedPreferences is not saving after re-opening the application

I am trying to add a function named removeCard, this function receives an array of strings. This array length is 48 and the strings inside this array contains a name of a card, i.e prince or knight. If a String inside this array is null it means there is no more card to delete (the game contains 48 cards but maybe I want to delete just 2 of them).
All my cards are saved in SharedPreferences with the key key1. This function is supposed to remove from the key all the cards inside the array (if someone accidentally added the prince but he didn't unlock it yet).
However, this function works fine and when I return to the main3.class intent it shows the cards inside the array were removed from the SharedPreferences key but when I close the application and re-open it, they remain like they never were removed.
Here is my code:
public static void removeCard(String[] s) {
Set<String> used;
used = prefs.getStringSet("key1", null);
for (String card : s) {
if (card != null)
used.remove(card);
else
break;
}
editor.putStringSet("key1", used);
editor.commit();
Intent k = new Intent(cont, main3.class);
cont.startActivity(k);
}
Also, the array contains the cards to remove is being created when you click on a ListView item (each item is a card). result[position] is the card name and cards is the array contains values to remove:
#Override
public void onClick(View v) {
if (position == 0) { // back button pressed
main2.removeCard(cards);
main2.cont.finish(); // close main2 activity
} else {
Toast.makeText(context, result[position] + " Picked", Toast.LENGTH_LONG).show(); // Toast the card you picked
if (!Arrays.asList(cards).contains(result[position])) { // if card is not already in array, add it.
cards[count] = result[position];
count++;
}
}
}
This is how I'm getting the editor of the SharedPreferences.
public static SharedPreferences prefs;
public static SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
cont = this;
listView = (ListView) findViewById(R.id.list);
listView.setAdapter(new CustomAdapter(main2.this, mDrawableName, mDrawableImg, n));
prefs = getSharedPreferences("MyPrefs", 0);
editor = prefs.edit();
}
And also, to display the cards you have from the other activity I used:
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
Set<String> cards = pref.getStringSet("key1", null);
tv1.setText("Available cards: " + cards);

last seen activity not save in shared preferences

in first activity i have 3 button firs button go to subject list , second button show last seen activity
Im use this for last seen activity :
in subject list for each item save number in shared preferences and when user click on last seen number in subject list call and show last activity
this code work well but when i turn of phone or app not open for minutes last seen show nothing why?
please help me
in subject list class
shared = getSharedPreferences("count", MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
public static int counter;
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (i == 0) {
Intent intent0 = new Intent(getApplicationContext(),Study.class);
startActivity(intent0);
counter=1;
SharedPreferences.Editor edit = shared.edit();
edit.putInt("count", counter);
edit.commit();
}
if (i == 1) {
counter=2;
SharedPreferences.Editor edit = shared.edit();
edit.putInt("count", counter);
edit.commit();
Intent intent1 = new Intent(getApplicationContext(),Mo.class);
startActivity(intent1);
}
if (i == 2) {
counter=3;
SharedPreferences.Editor edit = shared.edit();
edit.putInt("count", counter);
edit.commit();
Intent intent2 = new Intent(getApplicationContext(),Sa.class);
startActivity(intent2);
}
in fist activity that contain last seen button :
case R.id.last_seen_btn:
if (SubjectActivity.counter==0){
Toast.makeText(getApplicationContext(), " nothing",
Toast.LENGTH_LONG).show();
}
if (SubjectActivity.counter==1){
Intent intent = new Intent(getApplicationContext(),Study.class);
startActivity(intent);
}
if (SubjectActivity.counter==2){
Intent intent = new Intent(getApplicationContext(),Mo.class);
startActivity(intent);
}
if (SubjectActivity.counter==3){
Intent intent = new Intent(getApplicationContext(),Sa.class);
startActivity(intent);
}
You shall use always the "application preferences" and best is to access them via the Application object. There is caching on SharedPreferences aand it's creating some issues some time.
Also update always the SharedPreferences before opening the Activity (if i == 0)
public class MyApp extends Application {
private SharedPreferences mMyPref;
#Override
public void onCreate() {
super.onCreate();
mMyPref = getSharedPreferences("my_pref_name", MODE_PRIVATE);
}
public SharedPreferences getMySharedPreferences(){
return mMyPref;
}
}
In your parts of code where you want to read/write just use
((MyApp)getApplicationContext()).getMySharedPreferences() ....
of of course create a local variable that gives you the possibility to work with it.

how to pass extra intent to two activities

i have an app that on the first activity asks the persons name on the second page it displays the name in a sentence i want to use the name in the third fourth or 9th activity how do i properly declare it (public?) and call it when and where ever i need it? this is my code sending it
Main
public class MainActivity extends Activity {
Button ok;
EditText name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=(EditText)findViewById(R.id.editText);
Typeface font_a = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
name.setTypeface(font_a);
ok=(Button)findViewById(R.id.button);
Typefacefont_b=Typeface.createFromAsset(getAssets(),
"fonts/SignPaintersGothicShaded.ttf");
ok.setTypeface(font_b);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String nameStr = name.getText().toString();
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("NAMEDATA",nameStr);
startActivity(intent);
}
});
}
and this is activity 2 receiving it
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
t = (TextView)findViewById(R.id.textView3);
Typeface font_b = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
t.setTypeface(font_b);
String n = this.getIntent().getStringExtra("NAMEDATA");
t.setText(n);
so please how would i reuse this?
Use SharedPreferences to save the name or whatever variable you need, then read whenever you need it. First, create global in MainActivity which will be used as preference file name:
public static final String PREFS_NAME = "MyPrefsFile";
Then, to save:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", name);
editor.commit();
to load:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String name = settings.getString("name", "John");
Once saved, the prefs are accessible for every activity.
So in your case, save the name when ok button is pressed:
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String nameStr = name.getText().toString();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", nameStr);
editor.commit();
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
}
});
Then read it:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
t = (TextView)findViewById(R.id.textView3);
Typeface font_b = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
t.setTypeface(font_b);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String n = settings.getString("name", "defaultName");
t.setText(n);
You can do similarly in every activity you need it. See docs here.
You have a number of different approaches to share data between activities. I would say which one you use depends on the ultimate source and destination of the data.
Pass through intents - This is the method you are currently using. To proceed, just keep passing the name to the next intent.
Save to SharedPreference - This method you save the information to the "preference" file of the application. This is useful if the the user is setting up a profile or other semi-fixed information.
Write it to a DB - Here you would create a a new SQLite table for user information and write new rows to it for the name, password, and other info. This has way more overhead and is really only useful if you have multiple users in the same application
Save to a singleton - In this case you create a static class with public properties that can be set. This would be least favorable all the information is lost on application close, but could be useful for temporary creation and retention across many activities. Be warned: bad programming can make singletons a nightmare
Create class extending from Application class.
Implement setter and getter inside that class like,
public class GlobalClass extends Application {
//create setters and getters here
public void setUserInfo(String userInfo) {
}
public void getUserInfo() {
return userInfo;
}
}
then you can use this from any activity like,
GlobalClass app = (GlobalClass ) getApplication();
app.getUserInfo();

Shared preferences wont save before closing the app or activity

I am making an activity that will edit the shared preferences just when the activity starts before it executes any functions. I am stuck and dont know how to. My app only edits the shared preferences when i close the app or go back to another activity. I want to edit them when the activity starts without executing any function ie checkpreferences();.Precisely How to edit the shared preferences on start of activity?
public class MyActivity extends Activity {
private SharedPreferences app_preferences;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the app's shared preferences
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
final int id = 42;
int idd = app_preferences.getInt("idd", 0);
// I am Stuck in this part
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("idd", 43);
editor.commit(); // Very important
final int iddd = idd;
checkpreferences(id, iddd);
}
private void checkpreferences(int di, int dii) {
if(di == dii) {
Toast.makeText(AudioActivity.this,"id is same"+dii+"="+di , Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(AudioActivity.this,"id is different"+dii+"!="+di, Toast.LENGTH_SHORT).show();
}
}
}
I think the error is here
you are tryinh to fetvh the value of shared preference before saving it
// Fetching of value
int idd = app_preferences.getInt("idd", 0);
Log.e("value " , " is " + idd);
as at this time there shall be no value in preference
// and commitng after it
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("idd", 43);
editor.commit(); // Very important
you should save preference before fetching
and to assure it print the logs as well

Categories

Resources