How to reset the step count from android - java

public class speedDetection extends Activity implements SensorEventListener {
private TextView textView;
private SensorManager mSensorManager;
private Sensor mStepCounterSensor;
private Sensor mStepDetectorSensor;
// boolean flag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speed_detection);
//pass in the level from time to time.
//int level = this.getIntent().getIntExtra("Level",0);
textView = (TextView) findViewById(R.id.textView);
//Toast.makeText(getApplicationContext(), level, Toast.LENGTH_LONG).show();
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mStepCounterSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
mStepDetectorSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
}
#Override
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
float[] values = event.values;
int stepsInSensor = -1;
/*if (!flag) {
//Reset the count when reset the apps
int initValue = (int) values[values.length - 1];
stepsInSensor = stepsInSensor - initValue;
}*/
if (values.length > 0) { //some values was inside
stepsInSensor = (int) values[0]; //the latest value added will be at value[0]
}
if (sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
textView.setText("Step Counter Detected : " + stepsInSensor);
} else if (sensor.getType() == Sensor.TYPE_STEP_DETECTOR) {
textView.setText("Step Detector Detected : " + stepsInSensor);
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) { }
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mStepCounterSensor, SensorManager.SENSOR_DELAY_FASTEST);
mSensorManager.registerListener(this, mStepDetectorSensor,SensorManager.SENSOR_DELAY_FASTEST);
}
protected void onStop() {
super.onStop();
mSensorManager.unregisterListener(this, mStepCounterSensor);
mSensorManager.unregisterListener(this, mStepDetectorSensor);
}
}
Anyone have idea how to reset the stepInSensor started with 0 everytime the apps started?
the Sensor.TYPE_STEP_COUNTER can only reset when the device reboot.
I found a post answering this question was like "store the first value returned as initial value, then subtract subsequent value by it."
but how exactly it can be done?

Use the following code
private static final String Initial_Count_Key = "FootStepInitialCount";
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// Initialize if it is the first time use
if(!prefs.contains(Initial_Count_Key)){
Editor editor = prefs.edit();
editor.putInt(Initial_Count_Key, stepsInSensor);
editor.commit();
}
How to get the step count
// return -1 if it is not initialize
int startingStepCount = prefs.getInt(Initial_Count_Key, -1);
int stepCount = stepsInSensor - startingStepCount;
How to reset (Reset the starting value)
Editor editor = prefs.edit();
editor.putInt(Initial_Count_Key, stepsInSensor);
editor.commit();

It's just math, right?
Store the initial step count when the app starts. When you try to get the new step value, simply subtract the initial value from the current step sensor value. That tells you exactly how many steps have been taken since the app started.

Related

how to show a dialog after 1 or 2 min after opning app for first time

I want to show a custom XML dialog dialogue that will appear after a specific time in the first run, let's say after a min
how can I do it
but I'm confused about what should I do in a situation like below
if the user open the app for the first time and just spent 30 sec and just pause the app(screen lock or in onPause) or just close the app completely
Just as a note - I have already implemented a one time show dialog(directly in main activity without any layout file ) when the app runs for the first time already
Code
To view the already implemented dialog(shows up on the first run) please
go to the // Caution dialog (showDialog method)
MainActivity.java
public class MainActivity extends AppCompatActivity {
MediaPlayer player1;
MediaPlayer player2;
SeekBar seekBar1;
SeekBar seekBar2;
TextView elapsedTimeLable1;
TextView elapsedTimeLable2;
TextView remainingTimeLable1;
TextView remainingTimeLable2;
ImageView play1;
ImageView play2;
int totalTime1;
#SuppressLint("HandlerLeak")
private final Handler handler1 = new Handler() {
#SuppressLint("SetTextI18n")
#Override
public void handleMessage(#NonNull Message msg) {
int currentPosition1 = msg.what;
//Update SeekBar
seekBar1.setProgress(currentPosition1);
// Update Timelable
String elapsedTime1 = createTimerLable1(currentPosition1);
elapsedTimeLable1.setText(elapsedTime1);
String remainingTime1 = createTimerLable1(totalTime1 - currentPosition1);
remainingTimeLable1.setText("- " + remainingTime1);
}
};
int totalTime2;
#SuppressLint("HandlerLeak")
private final Handler handler2 = new Handler() {
#SuppressLint("SetTextI18n")
#Override
public void handleMessage(#NonNull Message msg) {
int currentPosition2 = msg.what;
// Update SeekBar
seekBar2.setProgress(currentPosition2);
// Update Timelable
String elapsedTime2 = createTimerLable2(currentPosition2);
elapsedTimeLable2.setText(elapsedTime2);
String remainingTime2 = createTimerLable2(totalTime2 - currentPosition2);
remainingTimeLable2.setText("- " + remainingTime2);
}
};
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#SuppressLint("ObsoleteSdkInt")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window w = getWindow();
// clear FLAG_TRANSLUCENT_STATUS flag:
w.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
w.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// finally change the color
w.setStatusBarColor(ContextCompat.getColor(this, R.color.Card_Elevation_Color));
}
// PlayButton * The ButtonClick is in the last if you want to jump directly there *
play1 = findViewById(R.id.playbtn1);
play2 = findViewById(R.id.playbtn2);
// TimeLables
elapsedTimeLable1 = findViewById(R.id.cTime1);
elapsedTimeLable2 = findViewById(R.id.cTime2);
remainingTimeLable1 = findViewById(R.id.tTime1);
remainingTimeLable2 = findViewById(R.id.tTime2);
// MediaPlayer
player1 = MediaPlayer.create(this, R.raw.dog_howl);
player1.setLooping(true);
player1.seekTo(0);
totalTime1 = player1.getDuration();
player2 = MediaPlayer.create(this, R.raw.dog_bark);
player2.setLooping(true);
player2.seekTo(0);
totalTime2 = player2.getDuration();
//SeekBar
seekBar1 = findViewById(R.id.seekbar1);
seekBar2 = findViewById(R.id.seekbar2);
seekBar1.setMax(totalTime1);
seekBar2.setMax(totalTime2);
seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress1, boolean fromUser1) {
if (fromUser1) {
player1.seekTo(progress1);
seekBar1.setProgress(progress1);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress2, boolean fromUser2) {
if (fromUser2) {
player2.seekTo(progress2);
seekBar2.setProgress(progress2);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
// Thread (Update SeekBar & TimeLabel)
new Thread(() -> {
while (player1 != null) {
try {
Message msg = new Message();
msg.what = player1.getCurrentPosition();
handler1.sendMessage(msg);
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
}
}).start();
new Thread(() -> {
while (player2 != null) {
try {
Message msg = new Message();
msg.what = player2.getCurrentPosition();
handler2.sendMessage(msg);
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
}
}).start();
// Admob Banner Ad
MobileAds.initialize(this, initializationStatus -> {
});
AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
// Caution dialog
SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
boolean firstStart = preferences.getBoolean("firstStart", true);
if (firstStart) {
showDialog();
}
}
// Caution dialog
private void showDialog() {
new AlertDialog.Builder(this)
.setTitle("Caution!")
.setMessage("In case you're wearing any kind of headphones please remove it before playing the ' Howl ' audio")
.setPositiveButton("ok", (dialogInterface, i) -> dialogInterface.dismiss())
.create().show();
SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("firstStart", false);
editor.apply();
}
public String createTimerLable1(int duration) {
String timerLabel1 = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel1 += min + ":";
if (sec < 10) timerLabel1 += "0";
timerLabel1 += sec;
return timerLabel1;
}
public String createTimerLable2(int duration) {
String timerLabel2 = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel2 += min + ":";
if (sec < 10) timerLabel2 += "0";
timerLabel2 += sec;
return timerLabel2;
}
public void playBtnClick1(View view) {
if (player2.isPlaying()) {
player2.pause();
play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
if (!player1.isPlaying()) {
// Stoping
player1.start();
play1.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
} else {
// Playing
player1.pause();
play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
}
public void playBtnClick2(View view) {
if (player1.isPlaying()) {
player1.pause();
play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
if (!player2.isPlaying()) {
// Stoping
player2.start();
play2.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
} else {
// Playing
player2.pause();
play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
}
#Override
protected void onPause() {
super.onPause();
if (player1 != null) {
player1.pause();
play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
if (player2 != null) {
player2.pause();
play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
}
}
but I'm confused about what should I do in a situation like below
if the user open the app for the first time and just spent 30 sec and just pause the app(screen lock or in onPause) or just close the
app completely
This is impossible to do if your app is closed.My suggestion would be to create a service on another process that does this dialog such that even if the app process is closed,the service process will still be running unless it is stopped explicitly.
Defining a Process of a Service
The android:process field defines the name of the process where the
service is to run. Normally, all components of an application run in
the default process created for the application. However, a component
can override the default with its own process attribute, allowing you
to spread your application across multiple processes.
If the name assigned to this attribute begins with a colon (':'), the
service will run in its own separate process.
<service android:name="com.example.appName" android:process=":externalProcess" />
This is of course in the manifest file .
You might also need to show a system dialog thus you will need a system Alert Window permission i your manifest and request for the permision on runtime.
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
Then on runtime request like this:
public static void openOverlaySettings(Activity activity) {
final Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + activity.getPackageName()));
try {
activity.startActivityForResult(intent, 6);
} catch (ActivityNotFoundException e) {
Log.e("Drawers permission :", e.getMessage());
}
}
To check if granted use :
if(!Settings.canDrawOverlays(context)) {
openOverlaySettings(context);
ok=false;
}
Then in your service you should create the dialog like below
View aldv= LayoutInflater.from(act).inflate(R.layout.your_layout,null);
ald=new AlertDialog.Builder(act,R.style.AppTheme)
.setView(aldv)
.setCancelable(true)
.create();
ald.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);

Java code to show action on x amount of presses?

I have an iOS app that I worked on some time ago, and the function it uses I like, and would like to somehow get it to work on some Android code I have.
At the top of my MainActivity I have
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "nShownLobby";
on my onCreate I have
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
And I am calling this method
changeTextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
long nb_shown_lobby = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).getLong("nShownLobby", 0);
++nb_shown_lobby;
if ((nb_shown_lobby % 20) == 0) {
this.turnAround();
}
int random = (int) (Math.random() * manyDifferentStrings.length);
if (random == oldVaue) {
random = (int) (Math.random() * manyDifferentStrings.length);
}
changingText.setText(manyDifferentStrings[random]);
oldVaue = random;
try {
mySound.start();
} catch (NullPointerException e) {
mySound = MediaPlayer.create(MainActivity.this, R.raw.sound);
}
}
private void turnAround() {
//Do something here
Log.i("Do Something ", "");
}
});
The intention is that after every 20 presses, the turnAround() method is called but it does not... It just gets ignored - I am guessing I have missed something?
**According to your question your code should be like this**
private SharedPreferences sharedpreferences;
private SharedPreferences.Editor editor;
private static final String MyPREFERENCES = "nShownLobby";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
editor = sharedpreferences.edit();
changeTextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
int nb_shown_lobby = sharedpreferences.getInt("nShownLobby", 0);
if ((nb_shown_lobby % 20) == 0) {
turnAround();
}
nb_shown_lobby += 1;
editor.putInt("nShownLobby", nb_shown_lobby);
editor.commit();
int random = (int) (Math.random() * manyDifferentStrings.length);
if (random == oldVaue) {
random = (int) (Math.random() * manyDifferentStrings.length);
}
changingText.setText(manyDifferentStrings[random]);
oldVaue = random;
try {
mySound.start();
} catch (NullPointerException e) {
mySound = MediaPlayer.create(MainActivity.this, R.raw.sound);
}
}
});
}
//created this in activity, not in the button onclick
private void turnAround() {
//Do something here
Log.i("Do Something ", "");
}

Fix the ambient Temperature in Android

I successfully made an app to measure the ambient temperature in Android studio. But the next step doesn't want to work. here's the point:
when I start the app the temperature should be shown in 1 textView (works so far). Then it should stay with this temperature but it changes. I only want to check the temperature once.
when I click on submit it shall do the same with the second textView.
I did this successfully with the time but with the temperature, it won't work. And my second question is, I did a lot of research and it looks like the temperature will always be shown in °c. Can I change that so the people who want it in °F can have it this way?
Code for the temperature without change the value and with the button for getting the temperature on textView2:
MainActivity:
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private TextView textView, textView2;
private Button button;
private SensorManager sensorManager;
private Sensor tempSensor;
private Boolean isTemperatureSensorAvailable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
textView2 = findViewById(R.id.textView2);
button = findViewById(R.id.button);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if(sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE) !=null) {
tempSensor = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
isTemperatureSensorAvailable = true;
}else{
textView.setText("Temperature Sensor is not available");
isTemperatureSensorAvailable = false;
}
}
#Override
public void onSensorChanged(SensorEvent event) {
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
protected void onResume(){
super.onResume();
if(isTemperatureSensorAvailable){
sensorManager.registerListener(this,tempSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
}
#Override
protected void onPause(){
super.onPause();
if(isTemperatureSensorAvailable){
sensorManager.unregisterListener(this);
}
}
private void update_text_unit()//Run from button
{
boolean toogle = false;
float temperature = 0;
float C_temp = 0;
float F_temp =0;
//Get sensor data
Sensor temp = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
F_temp = (C_temp * (9/5) +32);//Convert to °F
if(toogle = true) {
textView2.setText("Temp is:" + C_temp + "°C");
toogle = false;
}
else {
textView2.setText("Temp is:" + F_temp + "°F");
toogle = true;
}
}
}
I hope someone can help me going into a better direction.
Thanks for your help.
In the first code you have a section which is on sensor changed so this will run each time causing your issue. In you oncreate all the API to get the temperature once and chuck it to the text view as a string. For °C to °F you will need to convert. I would just do this manually:
(X°C × 9/5) + 32 = result_°F
Where X is the input temperature and result is the output in °F.
Here is an example of the button temp change feature not exactly sure how you read the temp so the line of Sensor.gettemp will probably need to change. Run this from a button push, it will update your text view
private void update_text_unit()//Run from button
{
boolean toogle = false;
float temperature = 0;
float C_temp = 0;
float F_temp =0;
//Get sensor data
C_temp = Sensor.gettemp();
F_temp = (C_temp * (9/5) +32);//Convert to °F
if(toogle = true) {
yourtextview.setText("Temp is:" + C_temp + "°C");
toogle = false;
}
else {
yourtextview.setText("Temp is:" + F_temp + "°F");
toogle = true;
}
}

How to make the vibrate different according to the significant light value?

I want the app to vibrate accordingly to the light value detected. For example, when the value is higher then the vibration is stronger. But this code seems not working, anyone can help to see where is my mistake? It can detect the light value correctly and the vibration is working but the vibration is not vibrating according to the light value.
public class LightDetection extends AppCompatActivity {
TextView textLight, textOn, textOff;
Button btnStart, btnStop;
float x;
long ambientValue = 16;
long floor_delay = 500;
long ceiling_delay = 80;
long vibrate = 100;
long vibrate_delay;
Vibrator sensorVibrator;
SensorManager sensorManager;
Sensor sensor;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_light_detection);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
textLight = (TextView) findViewById(R.id.textView);
textOn = (TextView) findViewById(R.id.textView2);
textOff = (TextView) findViewById(R.id.textView3);
btnStart = (Button) findViewById(R.id.button3);
btnStop = (Button) findViewById(R.id.button4);
final SensorEventListener lightListener = new SensorEventListener() {
public void onAccuracyChanged(Sensor sensor, int acc) {
}
#SuppressLint("SetTextI18n")
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
Log.i("IE LightDetect.", "Light value: " + x);
textLight.setText((int) x + " lux");
}
};
btnStart.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
public void onClick(View view) {
sensorManager.registerListener(lightListener, sensor,
SensorManager.SENSOR_DELAY_FASTEST);
handler.postDelayed(runnable, vibrate_delay);
textOn.setText("LIGHT DETECTION MODE: ON");
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
public void onClick(View view) {
textOn.setText("LIGHT DETECTION MODE: OFF");
sensorManager.unregisterListener(lightListener);
sensorVibrator.cancel();
handler.removeCallbacks(runnable);
}
});
}
private Runnable runnable = new Runnable() {
#Override
public void run() {
/* do what you need to do */
long luxValue = (long) x;
//Correction Ratio - Ceiling Delay/Most Likely Max Lux
long ratio = 950 / 300;
if (luxValue < ambientValue) {
vibrate = 100;
vibrate_delay = floor_delay + (ratio * luxValue);
} else {
vibrate = 100;
vibrate_delay = floor_delay - (ratio * luxValue);
}
if (vibrate_delay < ceiling_delay) {
long[] pattern = {0, vibrate, ceiling_delay};
sensorVibrator.vibrate(pattern, 1);
} else {
long[] pattern = {0, vibrate, vibrate_delay};
sensorVibrator.vibrate(pattern, 1);
}
Log.i("IE LightDetect.", "Lux: " + luxValue);
handler.postDelayed(this, vibrate_delay);
}
};
}`
After getting the light value in onSensorChanged() you are not saving the value globally, there u r using float x = event.values[0] which is just creating a local variable inside the function, and not the global one..try ditching the float from there, use x = event.values[0] instead of float x = event.values[0]..the it will save the value in the global variable and that you will use where you calculating vibration..

in java code using savedInstanceState to save a reusable value

I am developing an android app and want to save a rand2(Double type) value using savedInstanceState so that i can use rand2 value whenever app is reopened but while retrieving rand2 value it always comes NULL, Either the value is not saving or value is not retrieving . Why it is happening and what should i do to save rand2 value so that i can reuse it when the app is reopened?
public class MainActivity extends AppCompatActivity {
double rand2;
private boolean started = false;
private Handler handler = new Handler();
public Runnable runnable = new Runnable() {
#Override
public void run() {
double rand1 = Math.random() * 5;
rand2 = rand2 + rand1 * 0.04;
DecimalFormat df = new DecimalFormat("0.00");
String message1 = "" + df.format(rand1);
DecimalFormat dff = new DecimalFormat("000000.00");
String message2 = "" + dff.format(rand2);
displayRate(message1);
displaySatoshi(message2);
if (started) {
start(started);
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// recovering the instance state
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
if (savedInstanceState != null) {
rand2 = savedInstanceState.getDouble("abc");
} else {
rand2 = 0.00;
}
setContentView(R.layout.activity_main);
// Find the View that shows the numbers category
TextView numbers = (TextView) findViewById(withdraw);
// Set a click listener on that View
numbers.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View view) {
Intent numbersIntent = new Intent(MainActivity.this, Withdraw.class);
startActivity(numbersIntent);
}
});
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putDouble("abc", rand2);
// call superclass to save any view hierarchy
super.onSaveInstanceState(savedInstanceState);
}
public void Start(View v) {
ToggleButton starStopTogglrButton = (ToggleButton) findViewById(R.id.start_stop);
boolean hasStartStop = starStopTogglrButton.isChecked();
if (hasStartStop) {
start(hasStartStop);
} else {
stop(hasStartStop);
}
}
public void stop(Boolean hasStartStop) {
//Checking start or stop
started = hasStartStop;
handler.removeCallbacks(runnable);
}
public void start(Boolean hasStartStop) {
started = hasStartStop;
handler.postDelayed(runnable, 1000);
}
private void displayRate(String message1) {
TextView orderSummaryTextView = (TextView) findViewById(R.id.rate);
orderSummaryTextView.setText(message1);
}
private void displaySatoshi(String message2) {
TextView orderSummaryView = (TextView) findViewById(R.id.satoshis);
orderSummaryView.setText(message2);
}
}
onSaveInstanceState is called when the app is closed, but onCreate is only called when the app is booted after it's been finished. Remember the acitvity lifecycle:
So since onSaveInstanceState is called at closing and onCreate only is called when the activity is (re)created, it is null because it isn't added at that time.
You're looking for onRestoreInstanceState. Override that method and grab the variable and assign it from there.
Remember that using the savedInstanceState does not save the data if the activity is completely destroyed. For persistent data storage, use sharedprefs, files or SQL

Categories