Save nightMode using switch - switch-statement

I've just started Android studio for about a month now and come across a lot of problems but always have managed to find a solution.
This time I've red and tried a lot of things but now for 4 days I can't proceed, so finally I've decided to ask for help of the community.
What I'm trying to do is save nightmode and switch state in java.
So all I got right now is a switch and darkmode on my settings.java
AppCompatDelegate.setDefaultNightmode(AppCompatDelegate.MODE_NIGHT_YES);
So far I figured out that you can save, write and read from sharedPreferences
//Save
SharedPreferences savePreferences = getSharedPreferences("filename", MODE_PRIVATE);
SharedPreferences.Editor editor = savePreferences.edit();
editor.putInt("value", Nightmode);
editor.apply();
//read
SharedPreferences savePreferences = getSharedPreferences("filename", MODE_PRIVATE);
savePreferences.getInt("value", Nightmode);
Already red the android docs but it didn't help, tried multiple tutorials, checked other topics but they did not provide the solution.
I tried putting AppcompatDelegate inside an int to use it inside SharedPreferences but I can't seem to get the full string/int inside it so I can work with it. Tried it with the switch and it worked but then I can't get it to work with Nightmode.
Help would be appreciated !! Here is my settings.java
public class Settings extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
setTitle("settings");
SwitchCompat switch2 = findViewById(R.id.switch2);
// saves switch state + night mode
SharedPreferences savePreferences = getSharedPreferences("saveState", 0);
switch2.setChecked(savePreferences.getBoolean("value",false));
int night = savePreferences.getInt("NightModeInt", 2);
AppCompatDelegate.setDefaultNightMode(night);
switch2.setOnClickListener(v->{
if (switch2.isChecked()) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
//save
SharedPreferences.Editor edit = savePreferences.edit();
edit.putBoolean("value", true);
edit.putInt("NightModeInt", 2 );
edit.apply();
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_NO);
SharedPreferences.Editor edit = savePreferences.edit();
edit.putBoolean("value", false);
edit.putInt("NightModeInt", 1 );
edit.apply();
}
});
}
}
(This is now working !!)

public class Settings extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
setTitle("settings");
SwitchCompat switch2 = findViewById(R.id.switch2);
// saves switch state + night mode
SharedPreferences savePreferences = getSharedPreferences("saveState", 0);
switch2.setChecked(savePreferences.getBoolean("value",false));
int night = savePreferences.getInt("NightModeInt", 2);
AppCompatDelegate.setDefaultNightMode(night);
switch2.setOnClickListener(v->{
if (switch2.isChecked()) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
//save
SharedPreferences.Editor edit = savePreferences.edit();
edit.putBoolean("value", true);
edit.putInt("NightModeInt", 2 );
edit.apply();
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_NO);
SharedPreferences.Editor edit = savePreferences.edit();
edit.putBoolean("value", false);
edit.putInt("NightModeInt", 1 );
edit.apply();
}
});
}
}

Related

How to add numbers together using and If statement?

I'm trying to make a program in android studio that when sellected a higher education it automatically adds 200$ to the pay that was previously entered. But instead of getting 500+200=700, I get 500200. I ran trough the code numerous times and just can't seem to find the error. I'm still new on Java. This is the second window that appears when submitting the information, It shows all the info entered in the first window, but for some reason it can't 200 to the entered pay
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rezultatas);
Intent duom = getIntent();
String pavarde = duom.getStringExtra("pavarde");
String issilavinimas = duom.getStringExtra("issilavinimas");
int pay = duom.getIntExtra("atlyginimas", 0);
String laikas = duom.getStringExtra("laikas");
TextView rez = findViewById(R.id.rezultatas);
rez.setText("Pavardė: "+pavarde+"\n");
rez.append("Išsilavinimas: "+issilavinimas+"\n");
if(issilavinimas.equals("Aukštasis")){
rez.append("Gaunamas atlyginimas: " +pay+ 200 + "\n");
} else{
rez.append("Gaunamas atlyginimas: "+pay+ "\n");
}
rez.append("Keliasi: "+laikas+"\n");
}
This is the first window where all the information is entered:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void saugoti(View v){
EditText txt = findViewById(R.id.lastName);
String pavarde = txt.getText().toString();
Spinner issilavinimas = findViewById(R.id.issilavinimas);
String issilav = issilavinimas.getSelectedItem().toString();
EditText atl = findViewById(R.id.pay);
int pay = Integer.parseInt(atl.getText().toString());
TextView txt2 = findViewById(R.id.time);
String laikas = txt2.getText().toString();
Intent duom = new Intent(this, rezultatas.class);
duom.putExtra("pavarde", pavarde);
duom.putExtra("issilavinimas", issilav);
duom.putExtra("laikas", laikas);
duom.putExtra("atlyginimas", pay);
startActivity(duom);
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
Try this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rezultatas);
Intent duom = getIntent();
String pavarde = duom.getStringExtra("pavarde");
String issilavinimas = duom.getStringExtra("issilavinimas");
int pay = duom.getIntExtra("atlyginimas", 0);
int total=pay+ 200;
String laikas = duom.getStringExtra("laikas");
TextView rez = findViewById(R.id.rezultatas);
rez.setText("Pavardė: "+pavarde+"\n");
rez.append("Išsilavinimas: "+issilavinimas+"\n");
if(issilavinimas.equals("Aukštasis")){
rez.append("Gaunamas atlyginimas: " + total + "\n");
} else{
rez.append("Gaunamas atlyginimas: "+pay+ "\n");
}
rez.append("Keliasi: "+laikas+"\n");
}
when you + with String concatination is actually working there instead of addition

need to check first time opened app or not if yes go to direct main activity otherwise go to intro screen

I need to check my app intro screen is it opened first time or it's not work properly every time i opened my app it display it's not checking the app is first time opened or not...
sorry for my bad English need your help
This is my checking code:
intromanager = new Intromanager(this);
if(!intromanager.Check()){
intromanager.setFirst(false);
Intent i = new Intent(IntroActivity.this,MainActivity.class);
startActivity(i);
finish();
}
class:
public class Intromanager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context context;
public Intromanager(Context context){
this.context = context;
pref = context.getSharedPreferences("first", 0);
editor = pref.edit();
}
public void setFirst(boolean isFirst){
editor.putBoolean("check",isFirst);
editor.commit();
}
public boolean Check(){
return pref.getBoolean("check",true);
}
}
Try below code :
intromanager =new Intromanager(this);
if(intromanager.Check()){
intromanager.setFirst(false);
} else {
Intent i = new Intent(IntroActivity.this, MainActivity.class);
startActivity(i);
finish();
}
public class Intromanager {
SharedPreferences pref;
Context context;
public Intromanager(Context context){
this.context = context;
pref = context.getSharedPreferences("first", Activity.MODE_PRIVATE);
}
public void setFirst(boolean isFirst){
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("check",isFirst);
editor.apply();
}
public boolean Check(){
return pref.getBoolean("check",true);
}
}

Counting number of times android app goes into background

I'm developing an app which counts number of times the app goes to the background. It also retains the values when the orientation is changed. Though I have it working of all use cases, I have one use case which does not work.
Case : When I press the home button, change the phone's orientation and reopen the app, It does open in landscape mode but, the background count does not increase.
I have tried setting values in all the life cycle methods. It doesn't work. Hope somebody can help me with this.
`
public class MainActivity extends AppCompatActivity {
private int clickCount =0, backgroundCount = 0;
TextView tvClickCountValue, tvBackgroundCountValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if( savedInstanceState != null){
clickCount = savedInstanceState.getInt("COUNT");
backgroundCount = savedInstanceState.getInt("BGCOUNT");
}
setContentView(R.layout.activity_main);
tvClickCountValue = (TextView) this.findViewById(R.id.tvClickCountValue);
tvBackgroundCountValue = (TextView) this.findViewById(R.id.tvBackgroundCountValue);
setView(MainActivity.this);
}
public void onClick(View v){
clickCount += 1;
tvClickCountValue.setText(Integer.toString(clickCount));
}
public void setView(Context ctx){
tvClickCountValue.setText(Integer.toString(clickCount));
tvBackgroundCountValue.setText(Integer.toString(backgroundCount));
}
#Override
protected void onStop() {
super.onStop();
backgroundCount += 1;
}
#Override
protected void onResume() {
super.onResume();
tvClickCountValue.setText(Integer.toString(clickCount));
tvBackgroundCountValue.setText(Integer.toString(backgroundCount));
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("COUNT", clickCount);
outState.putInt("BGCOUNT", backgroundCount);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
clickCount = savedInstanceState.getInt("COUNT");
backgroundCount = savedInstanceState.getInt("BGCOUNT");
}
}
This article contains useful information: https://developer.android.com/guide/topics/resources/runtime-changes.html especially in the section about Handling The Change.
Try handling it on onConfigurationChanged() of you have disabled Activity restarts on orientation changes. Otherwise, probably through this article you will find which case applies to your scenario.
By reading the problem description, I am assuming that if you don't rotate the device the application works as intended.
you need to persist the count in the SharedPreferences. each time you reopen the app read the last value from the SharedPreferences. And increment and save to SharedPreferences each time the app is hidden.
Then you can count the with #kiran code:
public class BaseActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
public static boolean isAppInFg = false;
public static boolean isScrInFg = false;
public static boolean isChangeScrFg = false;
#Override
protected void onStart() {
if (!isAppInFg) {
isAppInFg = true;
isChangeScrFg = false;
onAppStart();
}
else {
isChangeScrFg = true;
}
isScrInFg = true;
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
if (!isScrInFg || !isChangeScrFg) {
isAppInFg = false;
onAppPause();
}
isScrInFg = false;
}
public void onAppStart() {
// app in the foreground
// show the count here.
}
public void onAppPause() {
// app in the background
// start counting here.
}
}

Convert Switch state to Boolean

I'm trying to get the value of a switch (on/off) and tell the data to another class.
I'm not using a switch statement, I have a physical switch which the user can check or uncheck.
I need to get the value of this switch in order to use the data in another class.
Here's what I've tried to use:
Switch vibeBlocker = (Switch) findViewById(R.id.hideVibeSwitch);
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Boolean vibeHider = Boolean.valueOf(vibeBlocker);
}
I receive an error on the line Boolean vibeHider = Boolean.valueOf(vibeBlocker);. I'm not sure how to get the value of my switch and convert it to a boolean. I know I can use methods like .toString(); and such, but is there something similar for booleans?
I need to transfer the value of the switch between two classes, and I think this will work. If anyone knows the correct statement here, or a better way to do this, please let me know.
Thanks!
Nathan
I was declaring the Switch and finding it by Id, which didn't work for me. Instead, I had to use a SharedPreferenceManager to put the boolean into my bundle:
#Override
public void onSaveInstanceState(#NonNull Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
SharedPreferences mSharedPreferencesManager = PreferenceManager.getDefaultSharedPreferences(this);
vibeBlock = mSharedPreferencesManager.getBoolean("vibration_checkbox", false);
savedInstanceState.putBoolean("myBoolean", vibeBlock);
}
That worked to put the boolean into the bundle. Here's how I pulled it out in the MainActivity:
#Override
public void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
hideVibe = savedInstanceState.getBoolean("myBoolean");
}
I also added this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate();
(Creation code)
SharedPreferences mSharedPreferencesManager = PreferenceManager.getDefaultSharedPreferences(this);
hideVibe = mSharedPreferencesManager.getBoolean("vibration_checkbox", false);
if (hideVibe) {
switchConv.setVisibility(View.GONE);
} else if (!hideVibe) {
switchConv.setVisibility(View.VISIBLE);
}
}
And this as well:
#Override
protected void onResume() {
super.onResume();
SharedPreferences mSharedPreferencesManager = PreferenceManager.getDefaultSharedPreferences(this);
hideVibe = mSharedPreferencesManager.getBoolean("vibration_checkbox", false);
if (hideVibe) {
switchConv.setVisibility(View.GONE);
} else if (!hideVibe) {
switchConv.setVisibility(View.VISIBLE);
}
}
And that did the trick :)

Loading spinner not showing correctly

I am trying to put a spinner while my data is loaded and UI updated so for this task I do this:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_road_details);
setTitle("Details");
startButt = (Button)findViewById(R.id.BeginJourney);
Map = (Button)findViewById(R.id.map_btn1);
boolean GreenButtState = getIntent().getBooleanExtra("GreenButtState", false);
boolean FastButtonState = getIntent().getBooleanExtra("FastButtonState", false);
AsyncTask<Void, Void, Void> LoadingTask = new AsyncTask<Void, Void, Void>()
{
ProgressDialog dialog = new ProgressDialog(RoadDetails.this);
#Override
protected void onPreExecute()
{
this.dialog.setMessage("Message");
this.dialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
final HashMap<String, Object> trip1;
Intent intent = getIntent();
mXmlRpcUrl = intent.getStringExtra("XmlRpcUrl");
mSessionID = intent.getStringExtra("SessionID");
mGetSavedTripFunc = intent.getStringExtra("GetSavedTripFunc");
newTripID = intent.getIntExtra("newTripID", 0);
variantID = intent.getIntExtra("VariantID", 0);
Week = intent.getIntExtra("WeekState", 0);
CityName = intent.getStringExtra("NameOfCity");
Flag = intent.getIntExtra("Flag", 0);
startLatitude = intent.getDoubleExtra("startLatitude", 0.0);
startLongitude = intent.getDoubleExtra("startLongitude", 0.0);
endLatitude = intent.getDoubleExtra("endLatitude", 0.0);
endLongitude = intent.getDoubleExtra("endLongitude", 0.0);
trip1 = (HashMap<String, Object>) intent.getSerializableExtra("Variant");
variant = new Variant();
variant.Read(trip1);
startButt.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(RoadDetails.this, Localisation.class);
intent.putExtra("SessionID", mSessionID);
intent.putExtra("XmlRpcUrl", mXmlRpcUrl);
intent.putExtra("NewTripID", newTripID);
intent.putExtra("VariantID", variantID);
intent.putExtra("WeekState", Week);
intent.putExtra("NameOfCity", CityName);
intent.putExtra("Variant", (Serializable)trip1);
intent.putExtra("Flag", Flag);
intent.putExtra("startLatitude", startLatitude);
intent.putExtra("startLongitude", startLongitude);
intent.putExtra("endLatitude", endLatitude);
intent.putExtra("endLongitude",endLongitude);
startActivity(intent);
}
});
Map.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
//Intent intent1 = new Intent (RoadDetails.this, MapDraw.class);
Intent intent1 = new Intent (RoadDetails.this, OSMActivity.class);
intent1.putExtra("SessionID",mSessionID);
intent1.putExtra("endLatitude", endLatitude);
intent1.putExtra("endLongitude",endLongitude);
intent1.putExtra("startLatitude", startLatitude);
intent1.putExtra("startLongitude", startLongitude);
intent1.putExtra("Variant", (Serializable)trip1);
startActivity(intent1);
}
});
return null;
}
#Override
protected void onPostExecute(Void result)
{
GettingData();
this.dialog.dismiss();
}
};
LoadingTask.execute((Void[])null);
}
However when I do this there is a delay before opening the the activity that contains this code (I want the spinner to be there while the data is loaded) the spinner is not showing. There is just a delay (for the data to be loaded - lets also call it screen freeze for a 1 - 3 seconds) and thats it. What am I doing wrong? I want the spinner to show while the data is loaded and after that to be dismissed. I also what to mention that in the method GettingData(); I am changing the UI - adding Layouts dynamically, adding images etc.
try this...this will work
ProgressDialog dialog = new ProgressDialog(RoadDetails.this);
this.dialog.setMessage("Message");
this.dialog.show();
//start your asynchronous task here
load your data here
//end asynchronous task
this.dialog.dismiss();
write ProgressDialog dialog; outside AsyncTask then
call
dialog = new ProgressDialog(RoadDetails.this);
dialog.setMessage("Message");
dialog.show();
inside onPreExecute().
Hope it will help you..

Resources