I'm quite new to Android Prorgramming and have a problem understandig SharedPreferences.
I have a Main Activity and a Settings Activity.
I want to be able to change a SharedPreference (here called firstWaitTime) in the Settings Activity and work with it in the Main Activity.
I can Set the new value in the settings, but in the Main Activity i only see the new value when i close and reopen the app.
I Think i would need a OnPrefrenceChanged Listender but i have no idea how to implement it...
The Main one looks like this:
public class MainActivity extends ActionBarActivity {
//Radio Button
private int stufe;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences settings = this.getSharedPreferences("settings", Context.MODE_PRIVATE);
int firstWaitTime = settings.getInt("firstWaitTime", 12);
int secondWaitTime = settings.getInt("secondWaitTime", 8);
int thirdWaitTime = settings.getInt("thirdWaitTime", 6);
//TEST
final TextView test = (TextView) findViewById(R.id.test);
test.setText("" + firstWaitTime);
}
The Settings Activity looks like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
final SharedPreferences settings = this.getSharedPreferences("settings", MODE_PRIVATE);
//BUTTON
final EditText edit1 = (EditText) findViewById(R.id.edit1);
Button save=(Button) findViewById(R.id.savebtn);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//prefs = getSharedPreferences(prefName, MODE_PRIVATE);
//SharedPreferences.Editor editor = prefs.edit();
SharedPreferences.Editor editor = settings.edit();
//---save the values in the EditText view to preferences---
editor.putInt("firstWaitTime", Integer.parseInt(edit1.getText().toString()));
//---saves the values---
editor.commit();
Toast.makeText(getBaseContext(), "Saved", Toast.LENGTH_SHORT).show();
}
});
}
What is the best way to achieve this?
onCreate() will not be called as Android hasn't killed the Activity. Try putting your code in onResume() instead. For more info read up on the Android Activity lifecycle.
Related
I set the Button Text trough editText and a long Button Click. Afterwards the editText is set to an emptyString again. How do i save the Button name in SharedPreferances (as a String i guess) and read it when i restart the app?
package com.example.myapplication;
import ...
public class MainActivity<button1> extends AppCompatActivity {
Button button
EditText editText1
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button3);
button.setOnClickListener(v -> opensecondone());
button.setOnLongClickListener(v -> naming());
editText1 = (EditText) findViewById(R.id.tv_textView);
}
public boolean naming() {
button = this.findViewById(R.id.button3);
button.setText(editText1.getText().toString());
editText1.setText(" ");
return true;
}
public void opensecondone() {
Intent intent = new Intent(this, firmaeins.class);
startActivity(intent);
}
}
first you store your name in naming function
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("yourMessageKey", message);
editor.commit();
then you get the value inside your oncreate of activity :
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
String message = sharedPref.getString("yourMessageKey", "");
I am trying to save my programmatically created CardView and TextView using OnSaveInstanceState and OnRestoreInstanceState as in the sample code.
While debugging, I notice that values are saved but when I quit the app and reopen it, nothing is being restored.
What am I doing wrong?
**#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("key", userInput.getText().toString());
savedInstanceState.putInt("LayoutId", mConstraintLayout.getId());
super.onSaveInstanceState(savedInstanceState);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
savedInstanceState.getString("key");
savedInstanceState.getInt("LayoutId");
}**
This are the methods I am using after 'OnCreate'
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = getApplicationContext();
mConstraintLayout = findViewById(R.id.top_left);
addButton = findViewById(R.id.add);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View popup = findViewById(R.id.popup);
popup.setVisibility(View.VISIBLE);
}
});
mButton = (Button) findViewById(R.id.create);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final CardView sticker = new CardView(mContext);
CardView.LayoutParams params = new CardView.LayoutParams(
CardView.LayoutParams.WRAP_CONTENT,
CardView.LayoutParams.WRAP_CONTENT
);
params.height=500;
params.width=500;
CheckBox privateCalendar = findViewById(R.id.checkPrivate);
CheckBox workCalendar = findViewById(R.id.checkWork);
CheckBox holidayCalendar = findViewById(R.id.checkHoliday);
if (privateCalendar.isChecked()){
sticker.setCardBackgroundColor(Color.parseColor("#FFCC00"));
}
else if (workCalendar.isChecked()){
sticker.setCardBackgroundColor(Color.parseColor("#FF8080"));
}
else if (holidayCalendar.isChecked()){
sticker.setCardBackgroundColor(Color.parseColor("#66B3FF"));
}
else{
sticker.setCardBackgroundColor(Color.parseColor("#FFCC00"));
}
sticker.setId(CardView.generateViewId());
sticker.getId();
sticker.setTag(CARD_VIEW_TAG);
sticker.setLayoutParams(params);
sticker.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
ClipData.Item item = new ClipData.Item((CharSequence) sticker.getTag());
String[] mimeTypes = {ClipDescription.MIMETYPE_TEXT_PLAIN};
ClipData data = new ClipData(sticker.getTag().toString(), mimeTypes, item);
View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(sticker);
sticker.startDrag(data
, shadowBuilder
, sticker
, 0
);
sticker.setVisibility(View.INVISIBLE);
return true;
}
});
TextView tv = new TextView(mContext);
tv.setLayoutParams(params);
tv.setBackgroundColor(Color.TRANSPARENT);
tv.setGravity(Gravity.CENTER);
userInput = findViewById(R.id.editText);
tv.setText(userInput.getText());
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
tv.setTextColor(Color.BLACK);
sticker.addView(tv);
mConstraintLayout.addView(sticker);
View popup = findViewById(R.id.popup);
popup.setVisibility(View.GONE);
}
});
}
SavedInstanceState and RestoreInstanceState will work if activity is recreated due to config change like orientation change or android system killed that activity due to memory issue, Then only savedInstanceState and restoreInstanceState comes in role.
If you finish activity by yourself and start activity again then there is no use of these methods.
Try to save data in SharedPreference instead savedInstanceState.
SharedPreferences pref =
getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
For Storing data:-
editor.putString("key", userInput.getText().toString());
editor.putInt("LayoutId", mConstraintLayout.getId());
editor.apply();
For retriving data:-
editor.getString("key", null); // getting String
editor.getInt("LayoutId", 0); // getting Integer
First of all if by "close the app" you mean destroy it, this will never work for you.
Second of all in onRestoreInstanceState you don't do anything with those values, you simply read them but don't store them anywhere.
If you mean to recreate the old form after switching back and forth between apps, with your app being destroyed in the background then, you need to only set values in onSaveInstanceState like you did, and in onCreate(Bundle savedInstance), you should do something like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstance == null) {
//read values from getIntent()
key = getIntent().getString("key);
LayoutId = getIntent().getInt("LayoutId");
} else {
//read values from savedInstanceState
key = savedInstanceState.getString("key");
LayoutId = savedInstanceState.getInt("LayoutId");
}
}
So, my Activity A is :
public class imei extends AppCompatActivity {
//variables
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_imei);
...
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(Long.parseLong(IMEI) == IMEI2){
IMEI .equals(IMEI2);
textView.setText("IMEI NUMBER : " + IMEI);
Bundle bundle = new Bundle();
bundle.putBoolean("key", true);
Intent intent = new Intent(imei.this, menu_utama.class);
intent.putExtras(bundle);
imei.this.startActivity(intent);
}else{}
now i want to pass value the Boolean value from bundle to Activity B :
public class MyApplication extends Application {
private BeaconManager beaconManager;
//variables
#Override
public void onCreate() {
super.onCreate();
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
final boolean success = bundle.getBoolean("key");
..code
if(success){
do something
}else{do something
but the getIntent() is red, but when i change to extends AppCompatActivity, getIntent() correct. somehow it has to do with onCreate(Bundle savedInstanceState) and extends Application what should i do to fix this
so my problem is how to passing value between activity class to aplication class, first try i'm using Bundle which is using getIntent(), but it did not work because getIntent() is in activity class, because i want to using in application class, so i'm using shared Preference and it works.
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("masuk", true);
// Save the changes in SharedPreferences
editor.apply(); // commit changes
put it in activity class and get the shared preferences in application class:
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("masuk", true);
// Save the changes in SharedPreferences
editor.apply(); // commit changes
and then just use if(masuk){do what you want here}else{do what you want here}
Solved.
i have my first activity with two EditText fields with hint's as first name and last name, when ever i go to my second activity and return to my first activity by a widget button the EditText fields in my first activity gets reset.
SIMPLY i want my EditText fields to remain same in my first activity as i re-visit my first activity from my second activity.
MY MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButton1Click(View v)
{
Intent intent = new Intent (this,MainActivity2.class);
startActivity(intent);
}
}
My MainActivity2.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
}
SOLUTION - i changed my second activity to this. just added reference to my Button and applied an onClickListener with onBackPressed(); code.
setContentView(R.layout.activity_main2);
Button button = (Button)findViewById(R.id.button3); //gave reference of button in second activity
button.setOnClickListener(new View.OnClickListener() { //and applied an onClickListener with code onBackpressed();
public void onClick(View v) {
onBackPressed();
// Code here executes on main thread after user presses button
}
});
}
Really Really thnx to #Narendra Sorathiya for his guidance.
Open secondActivity like below,
Intent i = new Intent(A.this,B.class);
startActivity(i);
finish();
to
Intent i = new Intent(A.this,B.class);
startActivityForResult(i,1);
do not open 1st Activity from 2nd Activity, just need to back press.
try this
declare all variavle at top of activity
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String FNAME = "fname";
public static final String LNAME = "lname";
SharedPreferences sharedpreferences;
write this code when you move to your next activity
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
// store login data in sharedpreferences
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(FNAME, edittext.getText());
editor.putString(LNAME, edittext2.getText());
editor.commit(); //save data in sharedpreferences
write this code in your oncreate method after you bind your controls
and get data from sharedprefrence like this
String fname= prefs.getString(FNAME, "");
String fname= prefs.getString(LNAME, "");
than set it to your editext like this
editext.setText(fname);
editext2.setText(lname);
let me know in case of any query
I am using shared preferences to make the ckeckbox checked for always when button is clicked. But I'm getting errors, unknown type 'getChecked'. , code is givenbellow:
#Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferences sharedPreferences = this.getSharedPreferences("pref", 0);
boolean checkedSearch = sharedPreferences.getBoolean("checkedSearch", false);
Button button = (Button) dialog.findViewById(R.id.button);
final CheckBox checkBox1 = (CheckBox) dialog.findViewById(R.id.checkBox1);
checkBox1.setChecked(checkedSearch ? true : false );
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if(
checkBox1.getChecked()==false){
checkBox1.setChecked(true);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("checkedSearch",true)
.commit();
}
final SharedPreferences sharedPreferences=this.getSharedPreferences("pref", 0);
you have missed = sign