Handle Toggle States in onResume() using Intent and SharedPreferences - java

I have written a program in which i am using Timer and controlling that timer using Toggle states,
Like: My Toggle's default state is OFF, once i make changes in toggle state from OFF to ON TIMER starts, and when i again change to OFF it stops the timer as per requirement.
But problem starts when my Timer is ON and I switch to other activity and then again come back to Toggle activity and then do changes in toggle state from ON to OFF - it still runs Timer...
ToggleActivity.java:
public class ToggleActivity extends Activity implements OnCheckedChangeListener {
ToggleButton toggleButton;
TextView text;
Timer timer;
TimerTask timerTask;
final Handler handler = new Handler();
Button btnSwitchActivity;
boolean toggleState;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toggle);
toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
text = (TextView) findViewById(R.id.textView1);
btnSwitchActivity = (Button) findViewById(R.id.btnSwitchActivity);
sharedPreferences = getApplicationContext().getSharedPreferences("toggleState",0);
toggleButton.setOnCheckedChangeListener(this);
btnSwitchActivity.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intentSwitchActivity = new Intent(ToggleActivity.this, SwitchActivity.class);
startActivity(intentSwitchActivity);
}
});
}
#Override
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
if(isChecked)
{
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("toggleState", true);
editor.commit();
text.setText("ON");
startTimer();
} else
{
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("toggleState", false);
editor.commit();
text.setText("OFF");
if (timer != null) {
timer.cancel();
timer = null;
}
}
}
public void startTimer() {
timer = new Timer();
initializeTimerTask();
timer.schedule(timerTask, 1000, 5000);
}
public void stoptimertask(View v) {
if (timer != null) {
timer.cancel();
timer = null;
}
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
final String strDate = simpleDateFormat.format(calendar.getTime());
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(), strDate, duration);
toast.show();
}
});
}
};
}
public void onResume() {
super.onResume();
toggleState = sharedPreferences.getBoolean("toggleState", false);
Log.v("toggleState-onResume()", Boolean.toString(toggleState));
if (toggleState) {
toggleButton.setChecked(true);
} else {
toggleButton.setChecked(false);
}
}
}
SwitchActivity.java:
public class SwitchActivity extends Activity {
Button btnToggleActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_switch);
btnToggleActivity = (Button) findViewById(R.id.btnToggleActivity);
btnToggleActivity.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(SwitchActivity.this, ToggleActivity.class);
startActivity(intent);
/**
* if i use finish() instead of Intent to switch to ToggleActivity
* my Timer works fine
*/
// finish
}
});
}
}
activity_toggle.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:gravity="center"
android:background="#ffffff"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".ToggleActivity" >
<ToggleButton
android:id="#+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/toggle_selector"
android:checked="false"
android:text=""
android:textOff=""
android:textOn="" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:text="#string/string_toggle_off"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/btnSwitchActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/string_btn_switch"/>
</LinearLayout>
activity_switch.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="#ffffff"
android:orientation="vertical" >
<Button
android:id="#+id/btnToggleActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/string_btn_goback"
/>
</LinearLayout>

You should probably save the state of the toggle button in the savedInstanceState bundle by overriding onSaveInstanceState.
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outstate.putBoolean("KEY", yourButton.isToggle())
}
And then you can access it by reading the savedInstanceState bundle given to you in onCreate of your activity or onCreateView/onViewCreated if you work in a fragment.
Hope this helps.

Related

My app crashes after clicking button

When I click the button my app crashes and I have no idea why. I've looked up my code a lot of times but can't seem to find any "major flaws". The purpose of the app is just clicking the button twice as fast as possible and it displays the amount of time needed from the first tap to the second tap. Some sort of reaction thing. I used a timer because I didn't know what else to use.
(Value of start time) - (value of current timer) = (time between first and second click).
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
tools:context="com.keklabs.reactiontimer.MainActivity">
<TextView
android:id="#+id/scoreText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="78dp"
android:text="Click below to start!"
android:textColor="#39FF14"
android:textSize="30dp" />
<Button
android:id="#+id/startStopButton"
android:layout_width="match_parent"
android:layout_height="350dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#000000"
android:text="Start / Stop"
android:textSize="25dp"
android:textColor="#39FF14" />
</RelativeLayout>
public class MainActivity extends AppCompatActivity {
private final long startTime = 0;
private final long interval = 100;
private boolean buttonClicked;
private Button startStopButton;
private TextView scoreText;
CountDownTimer timer = new CountDownTimer(30000, 100) {
#Override
public void onTick(long millisUntilFinished) {
scoreText.setText("kek"); //displayed text is value of starttime (30000) - current value of timer,
} //some sort of reaction game thing
#Override
public void onFinish() {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView scoreText = (TextView) findViewById(R.id.scoreText);
Button startStopButton = (Button) findViewById(R.id.startStopButton);
startStopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!buttonClicked) {
timer.start();
buttonClicked = true;
}
else {
timer.cancel();
buttonClicked = false;
}
}
});
}
}
EDIT
How do i do it the right way in the line scoreText.setText(startTime - millisUntilFinished); to display startTime-current timer value?
CountDownTimer timer = new CountDownTimer(startTime, interval) {
#Override
public void onTick(long millisUntilFinished) {
scoreText.setText(startTime - millisUntilFinished);
}
#Override
public void onFinish() {
}
};
Actually, you are declaring your TextView scoreText twice. One gloabally and other locally. You can replace TextView scoreText = (TextView) findViewById(R.id.scoreText);
to scoreText = (TextView) findViewById(R.id.scoreText);
in your onCreate()

EditText being overlapped by keyboard with custom animation

My EditText are being covered by my keyboard when trying to input into it.
Here's a screenshot without the Keyboard
Here's a screenshot with the Keyboard
When it comes to the code, I tried everything I could find here I think it comes from the fact that I use a custom animations. Here's the XML part of the code :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary"
android:paddingTop="25dp">
<!--French Flag !-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="65dp"
android:orientation="vertical"
android:id="#+id/linearLayout">
<View
android:layout_width="match_parent"
android:layout_height="12dp"
android:background="#color/flagBlue">
</View>
<View
android:layout_width="match_parent"
android:layout_height="12dp"
android:background="#color/flagWhite">
</View>
<View
android:layout_width="match_parent"
android:layout_height="12dp"
android:background="#color/flagRed">
</View>
</LinearLayout>
<ImageView
android:layout_width="250dp"
android:layout_height="250dp"
android:id="#+id/logo"
android:src="#drawable/logo_text"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<com.facebook.login.widget.LoginButton
android:id="#+id/button_facebook_sign_in"
android:layout_width="200dp"
android:layout_height="45dp"
android:layout_marginTop="100dp"
android:layout_below="#+id/logo"
android:layout_centerHorizontal="true" />
<com.petitchef.petitchef.views.customviews.CustomButton
android:id="#+id/button_sign_in"
android:layout_marginTop="20dp"
android:layout_width="180dp"
android:layout_height="35dp"
android:text="#string/sign_in_petitchef"
android:textColor="#color/flagWhite"
android:background="#drawable/petitchef_background_button"
android:layout_below="#+id/button_facebook_sign_in"
android:textSize="15sp"
android:layout_centerHorizontal="true" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="75dp"
android:src="#drawable/fork_and_knife"
android:layout_centerHorizontal="true" />
<include layout="#layout/signup_form"
android:id="#+id/sign_up_form"
android:layout_marginTop="50dp"
android:layout_width="match_parent"
android:layout_height="800dp"/>
<include layout="#layout/signin_form"
android:id="#+id/sign_in_form"
android:layout_marginTop="50dp"
android:layout_width="match_parent"
android:layout_height="800dp"/>
</RelativeLayout>
</RelativeLayout>
And the Java part
public class SignUpActivity extends AppCompatActivity {
private static final String TAG = "SignUpActivity";
View sliderView;
TextView switchToSignIn;
TextView switchToSignUp;
CallbackManager callbackManager;
EditText usernameSignIn;
EditText passwordSignIn;
EditText usernameSignUp;
EditText mailSignUp;
EditText passwordSignUp;
Button buttonSignIn;
Button buttonFacebook;
Button buttonConfirmSignIn;
Button buttonConfirmSignUp;
LoginButton loginButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_login_signup);
//Testing if user already logged in
callbackManager = CallbackManager.Factory.create();
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
if (sharedPref.contains(this.getString(R.string.token_shared_string))) {
Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
sliderView = findViewById(R.id.slider_layout);
loginButton = (LoginButton) findViewById(R.id.button_facebook_sign_in);
loginButton.setReadPermissions("email");
buttonSignIn = (Button) findViewById(R.id.button_sign_in);
buttonSignIn.setTransformationMethod(null);
buttonConfirmSignIn = (Button) findViewById(R.id.button_confirm_sign_in);
buttonConfirmSignIn.setTransformationMethod(null);
buttonConfirmSignUp = (Button) findViewById(R.id.button_confirm_sign_up);
buttonConfirmSignUp.setTransformationMethod(null);
switchToSignIn = (TextView) findViewById(R.id.switch_to_login_text);
switchToSignIn.setText(Html.fromHtml(getString(R.string.signup_switch_to_signin)));
switchToSignUp = (TextView) findViewById(R.id.switch_to_signup_text);
switchToSignUp.setText(Html.fromHtml(getString(R.string.signin_switch_to_signup)));
switchToSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
findViewById(R.id.sign_up_form).setVisibility(View.INVISIBLE);
findViewById(R.id.sign_in_form).setVisibility(View.VISIBLE);
}
});
switchToSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
findViewById(R.id.sign_up_form).setVisibility(View.VISIBLE);
findViewById(R.id.sign_in_form).setVisibility(View.INVISIBLE);
}
});
usernameSignIn = (EditText) findViewById(R.id.username_sign_in);
passwordSignIn = (EditText) findViewById(R.id.password_sign_in);
usernameSignUp = (EditText) findViewById(R.id.username_sign_up);
mailSignUp = (EditText) findViewById(R.id.mail_address_sign_up);
passwordSignUp = (EditText) findViewById(R.id.password_sign_up);
buttonSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Resources resources = SignUpActivity.this.getResources();
DisplayMetrics displayMetrics = resources.getDisplayMetrics();
sliderView.animate()
.translationY(-0.8f * displayMetrics.heightPixels / 2)
.setDuration(600)
.setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
findViewById(R.id.sign_up_form).setVisibility(View.INVISIBLE);
findViewById(R.id.sign_in_form).setVisibility(View.VISIBLE);
buttonSignIn.animate().alpha(0.0f)
.setDuration(300);
buttonSignIn.setEnabled(false);
loginButton.animate().alpha(0.0f)
.setDuration(300);
loginButton.setEnabled(false);
}
#Override
public void onAnimationEnd(Animator animation) {
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
}
});
buttonConfirmSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(usernameSignIn.getText()) || TextUtils.isEmpty(passwordSignIn.getText()))
Toast.makeText(SignUpActivity.this, getResources().getString(R.string.error_field_empty), Toast.LENGTH_SHORT).show();
String username = usernameSignIn.getText().toString();
String password = passwordSignIn.getText().toString();
APIManager.getInstance().login(username, password, new APIListener<Boolean>() {
#Override
public void onResult(Boolean hasSignUpSucceeded) {
if (hasSignUpSucceeded) {
Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
else {
Toast.makeText(SignUpActivity.this,
getResources().getString(R.string.error_password_or_username),
Toast.LENGTH_LONG)
.show();
}
}
});
}
});
buttonConfirmSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(usernameSignUp.getText()) || TextUtils.isEmpty(passwordSignUp.getText()) || TextUtils.isEmpty(mailSignUp.getText()))
Toast.makeText(SignUpActivity.this, getResources().getString(R.string.error_field_empty), Toast.LENGTH_SHORT).show();
String username = usernameSignUp.getText().toString();
String password = passwordSignUp.getText().toString();
String mail = mailSignUp.getText().toString();
APIManager.getInstance().register(username, password, mail, new APIListener<Boolean>() {
#Override
public void onResult(Boolean hasSignUpSucceeded) {
if (hasSignUpSucceeded) {
Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
else {
Toast.makeText(SignUpActivity.this,
getResources().getString(R.string.error_password_or_username),
Toast.LENGTH_LONG)
.show();
}
}
});
}
});
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
}
#Override
public void onBackPressed() {
usernameSignIn.setText("");
usernameSignIn.clearFocus();
passwordSignIn.setText("");
passwordSignIn.clearFocus();
usernameSignUp.setText("");
usernameSignUp.clearFocus();
mailSignUp.setText("");
mailSignUp.clearFocus();
passwordSignUp.setText("");
passwordSignUp.clearFocus();
sliderView.animate()
.translationY(0)
.setDuration(600)
.setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
buttonSignIn.animate().alpha(1.0f)
.setDuration(300);
buttonSignIn.setEnabled(true);
loginButton.animate().alpha(1.0f)
.setDuration(300);
loginButton.setEnabled(true);
}
#Override
public void onAnimationEnd(Animator animation) {
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
}
}
I tried android:windowSoftInputMode="stateAlwaysHidden|adjustResize", I treid to put everything in a ScrollView (It just breaks the whole view)

NullPointerException when trying to open ZXingScannerView

I'm new to Android development so please bear with me.
I have the code inside an activity that implements qr scanning. Basically there is an activity before this segments of codes, but its just clicking of a button to go here. and whenever I do that, my app crashes and that is the error that returns. The idea of the app is once the user click the button, it will first display a qr scanner, once it has been scanned, it will now call this XML File
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_scan"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#drawable/scanbg"
tools:context=".ScanActivity">
<RelativeLayout
android:layout_width="300dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp"
android:layout_marginTop="62dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Question Here"
android:textSize="22dp"
android:id="#+id/questionhere"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/questionhere"
android:hint="Answer"
android:id="#+id/answerhere"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Correct or not indicator"
android:id="#+id/indicator"
android:layout_below="#id/answerhere"
android:textSize="18dp"/>
<!--this textview will be programmed to be changed as correct or not-->
<!--if answer == correct then "correct!" else "wrong answer"-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Point(s):"
android:id="#+id/userpoints"
android:layout_below="#id/indicator"
android:textSize="18dp"/>
<Button
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/userpoints"
android:layout_alignParentEnd="true"
android:text="Go"
android:textSize="14dp"
android:background="#B0DAD5"
android:id="#+id/gosagot"/>
</RelativeLayout>
and Here is the java file
public class ScanActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler{
Button validateanswer;
ProgressDialog progress;
private ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
validateanswer = (Button)findViewById(R.id.gosagot); //Im having error here
validateanswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progress.setMessage("Connecting...");
progress.setCancelable(false);
progress.show();
EditText theanswer = (EditText)findViewById(R.id.answerhere);
String sagotdito = theanswer.getText().toString();
RequestFactory.confirmanswer(ScanActivity.this, sagotdito, new RequestCallback<Boolean>() {
#Override
public void onSuccess(Boolean response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
finish();
//load new question
progress.dismiss();
}
});
}
#Override
public void onFailed(String message) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ScanActivity.this, "Wrong Answer. Try Again!", Toast.LENGTH_LONG).show();
progress.dismiss();
}
});
}
});
}
});
}
continuation...
#Override
protected void onPause() {
super.onPause();
mScannerView.stopCamera();
}
#Override
public void handleResult(final Result result) {
Log.w("handleResult",result.getText());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final EditText answertoQuestion = new EditText(this);
answertoQuestion.setHint("answer");
builder.setTitle("Scan Result");
builder.setMessage(result.getText());
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
setContentView(R.layout.activity_scan);
TextView j = (TextView)findViewById(R.id.questionhere);
EditText k = (EditText)findViewById(R.id.answerhere);
String n = k.getText().toString();
j.setText(result.getText());
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
please help me.
If you check the examples of ZXing...
In your activity XML, you can add a region for the QR scanner.
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Grab that and add the scanner view there.
public class ScannerActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.activity_simple_scanner);
ViewGroup contentFrame = (ViewGroup) findViewById(R.id.content_frame);
mScannerView = new ZXingScannerView(this);
contentFrame.addView(mScannerView);
}
Your error is that you can't findViewById on your button when you replaced the content view with some other view that doesn't have the ID you want to find.
And even if you "switched" findViewById and setContentView around, your code wouldn't crash, but you would no longer have a button in the content view, so having the click action would be pointless.
The problem is that the button is a part of activity_scan and you set setContentView(mScannerView) to other layout.You are bound to get this error as the activity does not have a refernce to the view(button) you are refering.
What you can do is make the mScannerView a part of your main layout and then get it with findViewById();

The timer not let the user to edit

I'm a begginer and i build a timer app and i want the app to allow the user to edit the time. like in the android build in timer. and i wrote the code and it not really works it's show like it can be edit but when i'm trying to write something, it's change for a sec and go back to what it's been before..
xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_stopwatch"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.adir.stopwatch.StopwatchActivity"
android:background="#000000"
>
<Button
android:id="#+id/reset_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickReset"
android:text="#string/reset"
android:textColor="#FFFFFF"
android:layout_below="#+id/stop_button"
android:layout_alignLeft="#+id/stop_button"
android:layout_alignStart="#+id/stop_button" />
<EditText
android:id="#+id/time_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="17dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="92sp"
android:textColor="#FFFFFF"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:inputType="time"
/>
<Button
android:id="#+id/start_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickStart"
android:text="#string/start"
android:textColor="#FFFFFF"
android:layout_below="#+id/time_view"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp" />
<Button
android:id="#+id/stop_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickStop"
android:text="#string/stop"
android:textColor="#FFFFFF"
android:layout_alignLeft="#+id/start_button"
android:layout_alignStart="#+id/start_button"
android:layout_below="#+id/start_button"></Button>
</RelativeLayout>
Java:
public class StopwatchActivity extends Activity {
private int seconds=0;
private boolean running;
private boolean wasRunning;
public String time;
public int hours=seconds/3600;
public int minutes=(seconds%3600)/60;
public int secs=seconds%60;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stopwatch);
if(savedInstanceState!=null){
seconds=savedInstanceState.getInt("seconds");
running=savedInstanceState.getBoolean("running");
wasRunning=savedInstanceState.getBoolean("wasRunning");
}
runTimer();
}
public void onClickStart(View view) {
running = true;
}
protected void onStop(){
super.onStop();
wasRunning=running;
running=false;
}
protected void onStart() {
super.onStart();
if(wasRunning){
running=true;
}
}
public void onClickStop(View view) {
running = false;
}
public void onClickReset(View view) {
running = false;
seconds = 0;
}
private void runTimer() {
final EditText timeView = (EditText) findViewById(R.id.time_view);
time=timeView.getText().toString();
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
time = String.format("%d:%02d:%02d",hours, minutes, secs);
timeView.setText(time);
if (running) {
seconds--;
}
handler.postDelayed(this, 1000);
}
});
}
public void onSaveInstanceState(Bundle savedInstanceState){
savedInstanceState.putInt("seconds",seconds);
savedInstanceState.putBoolean("running",running);
savedInstanceState.putBoolean("wasRunning",wasRunning);
}
protected void onPause(){
super.onPause();
wasRunning=running;
running=false;
}
protected void onResume(){
super.onResume();
if(wasRunning){
running=true;
}
}
}
What do i need to fix?
The code below will give you a good idea of what to do. When you click the button, it will get the text of the EditText and put it into string. Then it will convert into int. Then you can put the new int variable time into your CountDownTimer function's 1st parameter to set the length of the timer.
Button submit;
TextView timerText;
EditText editTextTime;
CountdownTimer yourTimer;
String timeString;
int time;
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timeString = String.valueOf(editTextTime.getText());
time = Integer.valueOf(timeString);
}
});
yourTimer = new CountDownTimer(time, 1000) {
#Override
public void onTick(long millisUntilFinished) {
int seconds = (int) millisUntilFinished / 1000;
int minutes = seconds / 60;
seconds %= 60;
minutes %= 60;
if (seconds < 10 && seconds >= 1) {
timerText.setText("" + seconds);
}
}
#Override
public void onFinish() {
}
}.start();

Android Shared Preferences not working when relaunch app

I have 4 activities: MainActivity, p1, p2, p3.
My app works fine but problem here is that when app force stop or flick up app in home button to close, when the app is opened again, seems shared performance is cleared and my resume button just exit from app .
MainActivity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
final Button resume = (Button) findViewById(R.id.resume);
Button next = (Button) findViewById(R.id.next);
Button exit = (Button) findViewById(R.id.exit);
resume.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String PREFS_NAME = "MyPrefsFile";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getBoolean("my_first_time", true)) {
resume.setEnabled(false);
Log.d("Comments", "First time");
settings.edit().putBoolean("my_first_time", false).commit();
}else
{
MainActivity.this.finish();
}
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, p1.class);
startActivity(intent);
}
});
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
Xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="resume"
android:layout_width="wrap_content"
android:id="#+id/resume"
android:layout_height="wrap_content" />
<Button
android:text="next"
android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/exit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="exit"/>
</LinearLayout>
p1:
public class p1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.p1);
Button next = (Button) findViewById(R.id.next);
Button home=(Button)findViewById(R.id.home);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(p1.this, p2.class);
startActivity(intent);
}
});
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(p1.this, MainActivity.class);
startActivity(intent);
}
});
}
private void storeCurrentActivity(){
SharedPreferences myPref =getSharedPreferences("APP_SHARED_PREF", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=myPref.edit();
editor.putString("lastactivity", p1.this.getClass().getSimpleName());
editor.commit();
}
#Override
public void onResume(){
super.onResume();
storeCurrentActivity();
}
}
XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/next"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="page 1"/>
<Button
android:text="go in main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/home"/>
</LinearLayout>
and p2, p3 like p1.
I have experiences in non-shared only but 0 may is a wrong flag!
getSharedPreferences(PREFS_NAME, 0); <-- Please use the Constant Context.MODE_WORLD_READABLE
Analysis:
once you have pressed the resume button it is stored as setting["MyPrefsFile", "my_first_time"] = true and resume-button is disabled in current activity instance.
when the activity gets destroyed and is recreated the resumebutton is not initialized from the settings so it is enabled.
to fix add this to you onCreate
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0)
resume.setEnabled(settings.getBoolean("my_first_time", true));

Categories