EditText being overlapped by keyboard with custom animation - java

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)

Related

Edittext is not retrieving data in Android

My problem is that when i try to take data from the edittext fields(uidreg, passwordreg) it fails.
and this if(!uid.equals("") || !password.equals("")) becomes false and prints the toast Toast.makeText(getApplicationContext(),"All fields are required",Toast.LENGTH_LONG).show();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reg);
Button studentbtn = (Button)findViewById(R.id.studentbtn);
EditText textuidreg = (EditText)findViewById(R.id.uidreg);
EditText textpasswordreg = (EditText)findViewById(R.id.passwordreg);
String uid = textuidreg.getText().toString();
String password = textpasswordreg.getText().toString();
Toast.makeText(getApplicationContext(),uid,Toast.LENGTH_LONG).show();
studentbtn.setMovementMethod(LinkMovementMethod.getInstance());
studentbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!uid.equals("") || !password.equals("")) {
}
else {
Toast.makeText(getApplicationContext(),"All fields are required",Toast.LENGTH_LONG).show();
}
}
});
teacherbtn.setMovementMethod(LinkMovementMethod.getInstance());
teacherbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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:orientation="vertical">
<EditText
android:id="#+id/uidreg"
android:layout_width="210dp"
android:layout_height="wrap_content"
android:drawableRight="#drawable/ic_uid"
android:ems="10"
android:hint="uid"
android:importantForAutofill="no"
android:inputType="text"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.482"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.327" />
<EditText
android:id="#+id/passwordreg"
android:layout_width="214dp"
android:layout_height="40dp"
android:drawableRight="#drawable/ic_password"
android:ems="20"
android:hint="password"
android:importantForAutofill="no"
android:inputType="textPassword"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.492"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.528" />
</androidx.constraintlayout.widget.ConstraintLayout>
You need to put
String uid = textuidreg.getText().toString();
String password = textpasswordreg.getText().toString();
inside onClick function
full code should be like
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reg);
Button studentbtn = (Button)findViewById(R.id.studentbtn);
EditText textuidreg = (EditText)findViewById(R.id.uidreg);
EditText textpasswordreg = (EditText)findViewById(R.id.passwordreg);
Toast.makeText(getApplicationContext(),uid,Toast.LENGTH_LONG).show();
studentbtn.setMovementMethod(LinkMovementMethod.getInstance());
studentbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String uid = textuidreg.getText().toString();
String password = textpasswordreg.getText().toString();
if(!uid.equals("") || !password.equals("")) {
}
else {
Toast.makeText(getApplicationContext(),"All fields are required",Toast.LENGTH_LONG).show();
}
}
});
teacherbtn.setMovementMethod(LinkMovementMethod.getInstance());
teacherbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
}

"NaN" error when using operator in my calculator app

So I have been working on a Calculator app off a tutorial I got online. Everything's fine so far but I can't seem work to out what's causing this "NaN" error in my application every time I try to use the operator buttons. I'll attach screenshots of the code and app. Sorry if I'm vague I'm new to coding and just trying to learn.
My MainActivity.java
package com.example.calculator_prjct;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import android.app.Activity;
import com.example.calculator_prjct.databinding.ActivityMainBinding;
import android.os.Bundle;
import android.view.View;
import java.text.DecimalFormat;
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
private static final char ADDITION = '+';
private static final char SUBTRACTION = '-';
private static final char MULTIPLICATION = '*';
private static final char DIVISION = '/';
private char CURRENT_ACTION;
private double valueOne = Double.NaN;
private double valueTwo;
private DecimalFormat decimalFormat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
decimalFormat = new DecimalFormat("#.##########");
final ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.buttonDot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
binding.editText.setText(binding.editText.getText() + ".");
}
});
binding.buttonZero.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
binding.editText.setText(binding.editText.getText() + "0");
}
});
binding.buttonOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
binding.editText.setText(binding.editText.getText() + "1");
}
});
binding.buttonTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
binding.editText.setText(binding.editText.getText() + "2");
}
});
binding.buttonThree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
binding.editText.setText(binding.editText.getText() + "3");
}
});
binding.buttonFour.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
binding.editText.setText(binding.editText.getText() + "4");
}
});
binding.buttonFive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
binding.editText.setText(binding.editText.getText() + "5");
}
});
binding.buttonSix.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
binding.editText.setText(binding.editText.getText() + "6");
}
});
binding.buttonSeven.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
binding.editText.setText(binding.editText.getText() + "7");
}
});
binding.buttonEight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
binding.editText.setText(binding.editText.getText() + "8");
}
});
binding.buttonNine.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
binding.editText.setText(binding.editText.getText() + "9");
}
});
binding.buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
CURRENT_ACTION = ADDITION;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "+");
binding.editText.setText(null);
}
});
binding.buttonSubtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
CURRENT_ACTION = SUBTRACTION;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "-");
binding.editText.setText(null);
}
});
binding.buttonMultiply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
CURRENT_ACTION = MULTIPLICATION;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "*");
binding.editText.setText(null);
}
});
binding.buttonDivide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
CURRENT_ACTION = DIVISION;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "/");
binding.editText.setText(null);
}
});
binding.buttonEquals.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
binding.infoTextView.setText(binding.infoTextView.getText().toString() +
decimalFormat.format(valueTwo) + " = " + decimalFormat.format(valueOne));
valueOne = Double.NaN;
CURRENT_ACTION = '0';
}
});
binding.buttonClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (binding.editText.getText().length() > 0) {
CharSequence currentText = binding.editText.getText();
binding.editText.setText(currentText.subSequence(0, currentText.length() - 1));
} else {
valueOne = Double.NaN;
valueTwo = Double.NaN;
binding.editText.setText("");
binding.infoTextView.setText("");
}
}
});
}
private void computeCalculation() {
if (!Double.isNaN(valueOne)) {
valueTwo = Double.parseDouble(binding.editText.getText().toString());
binding.editText.setText(null);
if (CURRENT_ACTION == ADDITION)
valueOne = this.valueOne + valueTwo;
else if (CURRENT_ACTION == SUBTRACTION)
valueOne = this.valueOne - valueTwo;
else if (CURRENT_ACTION == MULTIPLICATION)
valueOne = this.valueOne * valueTwo;
else if (CURRENT_ACTION == DIVISION)
valueOne = this.valueOne / valueTwo;
} else {
try {
valueOne = Double.parseDouble(binding.editText.getText().toString());
} catch (Exception e) {
}
}
}
}
My activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout>
<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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/infoTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="30dp"
android:textSize="30sp" />
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/infoTextView"
android:enabled="false"
android:gravity="bottom"
android:lines="2"
android:maxLines="2"
android:textSize="20sp" />
<Button
android:id="#+id/buttonSeven"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editText"
android:text="7"
android:textSize="20sp" />
<Button
android:id="#+id/buttonFour"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editText"
android:layout_alignParentStart="true"
android:layout_marginStart="1dp"
android:layout_marginLeft="-87dp"
android:layout_marginTop="47dp"
android:layout_toRightOf="#id/buttonSeven"
android:text="4"
android:textSize="20sp" />
<Button
android:id="#+id/buttonFive"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editText"
android:layout_marginLeft="1dp"
android:layout_marginTop="47dp"
android:layout_toRightOf="#id/buttonSeven"
android:text="5"
android:textSize="20sp" />
<Button
android:id="#+id/buttonSix"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editText"
android:layout_marginLeft="89dp"
android:layout_marginTop="46dp"
android:layout_toRightOf="#id/buttonSeven"
android:text="6"
android:textSize="20sp" />
<Button
android:id="#+id/buttonOne"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editText"
android:layout_alignParentStart="true"
android:layout_marginStart="-1dp"
android:layout_marginLeft="-89dp"
android:layout_marginTop="96dp"
android:layout_toRightOf="#id/buttonSeven"
android:text="1"
android:textSize="20sp" />
<Button
android:id="#+id/buttonTwo"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editText"
android:layout_marginLeft="-1dp"
android:layout_marginTop="95dp"
android:layout_toRightOf="#id/buttonSeven"
android:text="2"
android:textSize="20sp" />
<Button
android:id="#+id/buttonThree"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editText"
android:layout_marginLeft="88dp"
android:layout_marginTop="97dp"
android:layout_toRightOf="#id/buttonSeven"
android:text="3"
android:textSize="20sp" />
<Button
android:id="#+id/buttonDot"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editText"
android:layout_alignParentStart="true"
android:layout_marginStart="2dp"
android:layout_marginLeft="-86dp"
android:layout_marginTop="144dp"
android:layout_toRightOf="#id/buttonSeven"
android:text="."
android:textSize="20sp" />
<Button
android:id="#+id/buttonZero"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editText"
android:layout_alignParentStart="true"
android:layout_marginStart="90dp"
android:layout_marginLeft="2dp"
android:layout_marginTop="144dp"
android:layout_toRightOf="#id/buttonSeven"
android:text="0"
android:textSize="20sp" />
<Button
android:id="#+id/buttonEquals"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editText"
android:layout_alignParentStart="true"
android:layout_marginStart="179dp"
android:layout_marginLeft="91dp"
android:layout_marginTop="145dp"
android:layout_toRightOf="#id/buttonSeven"
android:text="="
android:textSize="20sp" />
<Button
android:id="#+id/buttonClear"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editText"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_marginStart="265dp"
android:layout_marginLeft="177dp"
android:layout_marginTop="197dp"
android:layout_toRightOf="#id/buttonSeven"
android:text="C"
android:textSize="20sp" />
<Button
android:id="#+id/buttonEight"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editText"
android:layout_toRightOf="#id/buttonSeven"
android:text="8"
android:textSize="20sp" />
<Button
android:id="#+id/buttonNine"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editText"
android:layout_toRightOf="#id/buttonEight"
android:text="9"
android:textSize="20sp" />
<Button
android:id="#+id/buttonDivide"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/buttonNine"
android:layout_toRightOf="#id/buttonNine"
android:text="/"
android:textSize="20sp" />
<Button
android:id="#+id/buttonMultiply"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/buttonDivide"
android:layout_marginLeft="-88dp"
android:layout_marginTop="48dp"
android:layout_toRightOf="#id/buttonDivide"
android:text="*"
android:textSize="20sp" />
<Button
android:id="#+id/buttonSubtract"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/buttonMultiply"
android:layout_marginLeft="-86dp"
android:layout_marginTop="53dp"
android:layout_toRightOf="#id/buttonMultiply"
android:text="-"
android:textSize="20sp" />
<Button
android:id="#+id/buttonAdd"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/buttonSubtract"
android:layout_marginLeft="-89dp"
android:layout_marginTop="49dp"
android:layout_toRightOf="#id/buttonSubtract"
android:text="+"
android:textSize="20sp" />
</RelativeLayout>
</layout>
Screenshot of the actual error
"NaN Error on all operator buttons"
This is because you didn't check whether or not the EditText is empty in the respective onClick method of all the operator buttons. Add code like this to all of the operator buttons :
binding.buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(binding.editText.getText().toString().isEmpty()) {
Toast.makeText(MainActivity.this, "Enter number before performing operation", Toast.LENGTH_LONG).show();
return;
}
computeCalculation();
CURRENT_ACTION = ADDITION;
//if editText was empty then valueOne would still be NaN
//and infoTextView will show NaN+ with this line of code
binding.infoTextView.setText(decimalFormat.format(valueOne) + "+");
binding.editText.setText(null);
}
});
Full Activity Code :
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
private static final char ADDITION = '+';
private static final char SUBTRACTION = '-';
private static final char MULTIPLICATION = '*';
private static final char DIVISION = '/';
private char CURRENT_ACTION;
private double valueOne = Double.NaN;
private double valueTwo;
private DecimalFormat decimalFormat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
decimalFormat = new DecimalFormat("#.##########");
binding.buttonDot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
binding.editText.setText(binding.editText.getText() + ".");
}
});
binding.buttonZero.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
binding.editText.setText(binding.editText.getText() + "0");
}
});
binding.buttonOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
binding.editText.setText(binding.editText.getText() + "1");
}
});
binding.buttonTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
binding.editText.setText(binding.editText.getText() + "2");
}
});
binding.buttonThree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
binding.editText.setText(binding.editText.getText() + "3");
}
});
binding.buttonFour.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
binding.editText.setText(binding.editText.getText() + "4");
}
});
binding.buttonFive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
binding.editText.setText(binding.editText.getText() + "5");
}
});
binding.buttonSix.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
binding.editText.setText(binding.editText.getText() + "6");
}
});
binding.buttonSeven.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
binding.editText.setText(binding.editText.getText() + "7");
}
});
binding.buttonEight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
binding.editText.setText(binding.editText.getText() + "8");
}
});
binding.buttonNine.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
binding.editText.setText(binding.editText.getText() + "9");
}
});
binding.buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(binding.editText.getText().toString().isEmpty()) {
Toast.makeText(MainActivity.this, "Enter number before performing operation", Toast.LENGTH_LONG).show();
return;
}
computeCalculation();
CURRENT_ACTION = ADDITION;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "+");
binding.editText.setText(null);
}
});
binding.buttonSubtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(binding.editText.getText().toString().isEmpty()) {
Toast.makeText(MainActivity.this, "Enter number before performing operation", Toast.LENGTH_LONG).show();
return;
}
computeCalculation();
CURRENT_ACTION = SUBTRACTION;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "-");
binding.editText.setText(null);
}
});
binding.buttonMultiply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(binding.editText.getText().toString().isEmpty()) {
Toast.makeText(MainActivity.this, "Enter number before performing operation", Toast.LENGTH_LONG).show();
return;
}
computeCalculation();
CURRENT_ACTION = MULTIPLICATION;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "*");
binding.editText.setText(null);
}
});
binding.buttonDivide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(binding.editText.getText().toString().isEmpty()) {
Toast.makeText(MainActivity.this, "Enter number before performing operation", Toast.LENGTH_LONG).show();
return;
}
computeCalculation();
CURRENT_ACTION = DIVISION;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "/");
binding.editText.setText(null);
}
});
binding.buttonEquals.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(binding.editText.getText().toString().isEmpty()) {
Toast.makeText(MainActivity.this, "Enter number before performing operation", Toast.LENGTH_LONG).show();
return;
}
computeCalculation();
binding.infoTextView.setText(binding.infoTextView.getText().toString() +
decimalFormat.format(valueTwo) + " = " + decimalFormat.format(valueOne));
valueOne = Double.NaN;
CURRENT_ACTION = '0';
}
});
binding.buttonClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (binding.editText.getText().length() > 0) {
CharSequence currentText = binding.editText.getText();
binding.editText.setText(currentText.subSequence(0, currentText.length() - 1));
} else {
valueOne = Double.NaN;
valueTwo = Double.NaN;
binding.editText.setText("");
binding.infoTextView.setText("");
}
}
});
}
private void computeCalculation() {
if (!Double.isNaN(valueOne)) {
valueTwo = Double.parseDouble(binding.editText.getText().toString());
binding.editText.setText(null);
if (CURRENT_ACTION == ADDITION)
valueOne = this.valueOne + valueTwo;
else if (CURRENT_ACTION == SUBTRACTION)
valueOne = this.valueOne - valueTwo;
else if (CURRENT_ACTION == MULTIPLICATION)
valueOne = this.valueOne * valueTwo;
else if (CURRENT_ACTION == DIVISION)
valueOne = this.valueOne / valueTwo;
} else {
try {
valueOne = Double.parseDouble(binding.editText.getText().toString());
} catch (Exception e) {
}
}
}
}

Can I open a seperate XML layout with a OnLongClick

I am currently experimenting with layouts and opening new pages, I would like to open one page with a OnLongClickListener but a toast with a OnClickListener using the same text view box.
This is what I've designed so far. It won't work as the long click needs to output a boolean. Any Ideas?
XML main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.how_to_use.MainActivity"
android:id="#+id/main_view">
<TextView
android:id="#+id/long_press_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Long Press To Open \n'Drag n Drop'"/>
</LinearLayout>
XML 2nd page
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ImageView
android:id="#+id/swirl_img"
android:src="#drawable/Swirl"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity.Java
public class MainActivity extends AppCompatActivity {
private LinearLayout mainView;
private TextView txtView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtView = (TextView) findViewById(R.id.long_press_textView);
addListenerLongPressBtn();
addListenerOnClickBtn();
}
public void addListenerOnClickBtn() {
txtView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Press Secret Button for Longer", Toast.LENGTH_SHORT).show();
}
});
}
public void addListenerLongPressBtn() {
txtView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
Intent intent = new Intent(this, DragDropActivity.class);
startActivity(intent);
return true;
}
});
}
}
I found a solution to my own problem.
public void addListenerLongPressBtn() {
txtView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
Intent intent = new Intent(view.getContext(), DragDropActivity.class);
startActivity(intent);
return true;
}
});
}

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));

Handle Toggle States in onResume() using Intent and SharedPreferences

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.

Categories