SharedPreferences not loading in onCreate() - android

I'm trying to change the style of my Activity when the user clicks on a menu item.
When the user clicks on the NightMode menu item:
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.night_mode:
SharedPreferences sharedPrefStyle = getSharedPreferences(SAVE_TO, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPrefStyle.edit();
editor.putInt(SAVE_STYLE, R.style.nightMode);
editor.apply();
recreate();
Toast.makeText(this, "Night Mode is on", Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Then, in my onCreate(),
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPrefStyle = getSharedPreferences(SAVE_TO, Context.MODE_PRIVATE);
int style = sharedPrefStyle.getInt(SAVE_STYLE, 0);
Log.e("style", "oncreate saved style is " + style);
if (style != 0) {
setTheme(style);
}
setContentView(R.layout.my_activity);
// more code
}
But in my LogCat, this Log.e always outputs "oncreate saved style is 0," meaning nothing could be extracted from SharedPreferences.
The thing is, I tried extracting the style in onStop() and onResume(). Both successfully output the value of R.style.nightMode. So how come SharedPreferences does not work in onCreate()? Here is my LogCat for reference: So after recreate() is called,
E/style: onStop style: 2131755703 (this is R.style.nightMode)
E/style: onCreate style: 0
E/style: onResume style: 2131755703
Is there a better way to be setting the theme of an Activity at runtime? I have read through many other questions regarding this issue but cannot implement it myself. I am very new to Android so I apologize if this is trivial. Thanks in advance.

Related

Popupmenu is closing when screen rotated

I am using a popupmenu like below;
popupMenu = PopupMenu(view.context,view);
val menuInflater:MenuInflater = popupMenu!!.menuInflater;
menuInflater.inflate(R.menu.profil_image_degistir_menu,popupMenu!!.menu);
this.profilImage = profilImage as ImageView;
popupMenu!!.setOnMenuItemClickListener(object:PopupMenu.OnMenuItemClickListener{
override fun onMenuItemClick(item: MenuItem?): Boolean {
if(item?.itemId == R.id.action_cam){
camContext = view.context;
kameraIzin = ContextCompat.checkSelfPermission(view.context,Manifest.permission.CAMERA);
if(kameraIzin != PackageManager.PERMISSION_GRANTED){
requestPermissions(arrayOf(Manifest.permission.CAMERA), CAMERA_REQUEST_CODE);
}else{
val intent: Intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,CAMERA_REQUEST_CODE);
}
}else if(item?.itemId == R.id.action_localStorage){
}
return true;
}
});
popupMenu!!.show();
But when I rotate the screen menu is closing? How to prevent this?Can u help me.
When you rotate the device a configuration change takes place; this causes the activity to be recreated again. To control configuration changes you should use the onSaveInstanceState method. This method execute when a configuration change occur. In this case you should save a boolean value indicating if your popup is open or not.
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean("shouldShowPopup", isPopupOpen);
}
Then, on your onCreate method, you should check if the Bundle param is null. If is not null you can get the value we have saved before and show (or not) the popup.
In manifest file you need to add android:configChanges="orientation" in the activity that hosts this popup menu.

How to know the last button clicked in android using sharedpreference?

I have two buttons, Now how I can know the last button clicked using sharedpreference when start the activity again ?
the code:
private SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
init in onCreate:
sharedPreferences = getSharedPreferences("MyPref", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
I tried to do this but absolutely wrong way
if (sharedPreferences.getString("lamp", "on")) {
Toast.makeText(this, "onnnn", Toast.LENGTH_SHORT).show();
}
if (sharedPreferences.getString("lamp", "off")){
Toast.makeText(this, "offfff", Toast.LENGTH_SHORT).show();
}
first button
public void lampOff(View view) {
Log.d(tag, "lampOFF");
lamp_notConnected_Image.setVisibility(View.INVISIBLE);
lamp_Connected_Image.setVisibility(View.VISIBLE);
editor.putString("lamp", "off");
editor.commit();
}
seconde button:
public void lampOn(View view) {
Log.d(tag, "lampO");
lamp_notConnected_Image.setVisibility(View.VISIBLE);
lamp_Connected_Image.setVisibility(View.INVISIBLE);
editor.putString("lamp", "on");
editor.commit();
}
The problem lies in your condition if (sharedPreferences.getString("lamp", "on")), you aren't comparing this string to anything, either use
if (sharedPreferences.getString("lamp", "on").equals("on"))
or
save the value as boolean editor.putBoolean("lamp", true);, then you can compare the way you were doing: if (sharedPreferences.getString("lamp", true))
Note that here ("lamp", "on") the fist parameter is the identification, and the second is the default value, in case nothing is stored there yet.
See more in SharedPreferences
You need to check the shared preference value in onCreate method like:
if (sharedPreferences.getString("lamp", "off").equals("on")) { //assumed "off" as default
Toast.makeText(this, "onnnn", Toast.LENGTH_SHORT).show();
// on button is pressed last time
}
else{
Toast.makeText(this, "offfff", Toast.LENGTH_SHORT).show();
// off button is pressed last time or no button press so far
}

Create a function that fires only once after app is installed on phone

I'm developing a mobile app using ApacheCordova/Phonegap.
I need a function that sends a SMS to me once per install. If I put my function on "DeviceReady" it will be run each time the app opens.
Is there any solution for a function to be run when app is installed OR when it runs for first time?
Any suggestion would be appreciated.
Check if it is the first time with a method and then perform the action if that method determines that it is the first time.
Ex:
isFirstTime() Method
private boolean isFirstTime()
{
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean ranBefore = preferences.getBoolean("RanBefore", false);
if (!ranBefore) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("RanBefore", true);
editor.commit();
// Send the SMS
}
return ranBefore;
}
You may want to add it to your onCreate()
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
topLevelLayout = findViewById(R.id.top_layout);
if (isFirstTime()) {
topLevelLayout.setVisibility(View.INVISIBLE);
}
I added a field to the localstorage and on startup just check if that field exists. So something like this:
if (window.localStorage.getItem("installed") == undefined) {
/* run function */
window.localStorage.setItem("installed", true);
}
Edit: The reason I prefer this over the other methods is that this works on iOS, WP, etc as well, and not only on android
This should be what u are searching for:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.getBoolean("firstTime", false))
{
// run your one time code
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
Use some boolean value if its true don't call that function other wise call that function example is here
if(smssent!=true)
{
//call sms sending method
}
else
{
//just leave blank or else notify user using some toast message
}
Note:-the boolean value store in some database like sharedprefernce or sqllite, files....

Why doesn't “setContentView” work in if statement? [duplicate]

This question already exists:
why "setContentView" can't work in " if " ??? thx [closed]
Closed 9 years ago.
the code is in onCreate! when setContentView(R.layout.manual); is outside the if it works. But I moved setContentView(R.layout.manual); into if can’t work!
The followign:
if (settings.getBoolean("my_first_time", true)) {
setContentView(R.layout.manual); // can not work
}
But Log.d("Comments1", "First time"); always works
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String PREFS_NAME = "MyPrefsFile";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getBoolean("my_first_time", true)) {
//the app is being launched for first time, do something
Log.d("Comments1", "First time");//this can be showed on logCat!
setContentView(R.layout.manual);// this can not work
// record the fact that the app has been started at least once
settings.edit().putBoolean("my_first_time", false).commit();
}
}
Your condition is not getting satisfied because
settings.getBoolean("my_first_time", true)
is not returning true.
Hence your
setContentView(R.layout.manual)
is not called inside the “if” block.
You need to know what you are doing if you set a if-else loop, because no matter what is the outcome setContentView() must be supplied with a valid layout id. If you have a condition to check before setting the layout, you can just check the id:
int layoutId=0;
if(condition) {
layoutId = R.layout.manual;
} else {
layoutId = R.layout.other;
}
setContentView(layoutId);

SharedPreferences lost on force quit?

I've added the SharedPreferences functionality to my App to launch a specific activity once the App starts after it has been quited.
I use the following code to save the string:
final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
SharedPreferences.Editor editor = pref1.edit();
editor.putString("Stringval", "view1");
editor.commit();
Then the following to load the last used activity, this code is below OnCreate
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
String str1= pref1.getString("Stringval", null);
if(str1 == "view0")
{
setContentView(R.layout.activity_view0);
}
else if(str1 == "view1")
{
setContentView(R.layout.activity_view1);
}
else
{
setContentView(R.layout.activity_no_setup);
}
}
The code works if the user just quits the App, then relaunches it (Only tested it in the Simulator so far) but whenever I use the task manager to force quit the app like this:
The App just relaunches without using the SharedPreferences.
What's the reason for the App to not load the SharedPreferences or is this just a simulator bug?
You can write
if(str1 != null && str1.equals("view0"))
{
setContentView(R.layout.activity_view0);
}
else if(str1 != null && str1.equals("view1"))
{
setContentView(R.layout.activity_view1);
}
else
{
setContentView(R.layout.activity_no_setup);
}
try this, May be helpful for you......

Categories

Resources