App keeps crashing when I switch to landscape mode - java

I have been working on a basic Calculator App in Android Studios. I've gotten preety deep into it and I am happy with my progress so far. The problem that I am now facing is that when I am running the Calculator App, whenever I input a number in portrait mode and switch into landscape mode and try to add a number or do any operation on it, the app crashes. I used the onSaveInstanceState method to save the data and the onRestoreInstanceState method to retrieve it. I looked into documentation on how to use these two methods and I am sure that I am implemented them correctly. Any help would be appreciated.
I have pasted the code down below.
package com.mohamedali.calculatorapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private EditText moeresult;
private EditText moenewNumber;
private TextView displayOperation;
//Comment: Variables to hold the operands and type of calculations
private Double operand1 = null;
private String pendingOperation = " = ";
public static final String STATE_PENDING_OPERATION = "Pending Operation";
public static final String STATE_OPERAND1 = "Operand 1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
moeresult = (EditText) findViewById(R.id.result);
moenewNumber = (EditText) findViewById(R.id.NewNumber);
displayOperation = (TextView) findViewById(R.id.Operation);
Button button0 = (Button) findViewById(R.id.button0);
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
Button button3 = (Button) findViewById(R.id.button3);
Button button4 = (Button) findViewById(R.id.button4);
Button button5 = (Button) findViewById(R.id.button5);
Button button6 = (Button) findViewById(R.id.button6);
Button button7 = (Button) findViewById(R.id.button7);
Button button8 = (Button) findViewById(R.id.button8);
Button button9 = (Button) findViewById(R.id.button9);
Button buttonDecimal = (Button) findViewById(R.id.buttonDecimal);
Button buttonMultiply = (Button) findViewById(R.id.buttonMultiply);
Button buttonDivide = (Button) findViewById(R.id.buttonDivide);
Button buttonMinus = (Button) findViewById(R.id.buttonMinus);
Button buttonPlus = (Button) findViewById(R.id.buttonPlus);
Button buttonEqual = (Button) findViewById(R.id.buttonEqual);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Button b = (Button) v;
moenewNumber.append(b.getText().toString());
}
};
button0.setOnClickListener(listener);
button1.setOnClickListener(listener);
button2.setOnClickListener(listener);
button3.setOnClickListener(listener);
button4.setOnClickListener(listener);
button5.setOnClickListener(listener);
button6.setOnClickListener(listener);
button7.setOnClickListener(listener);
button8.setOnClickListener(listener);
button9.setOnClickListener(listener);
buttonDecimal.setOnClickListener(listener);
View.OnClickListener opListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
Button b = (Button) view;
String op = b.getText().toString();
String value = moenewNumber.getText().toString();
try {
Double doublevalue = Double.valueOf(value);
performOperation(doublevalue, op);
} catch (NumberFormatException e) {
moenewNumber.setText("");
}
pendingOperation = op;
displayOperation.setText(pendingOperation);
}
};
buttonEqual.setOnClickListener(opListener);
buttonMultiply.setOnClickListener(opListener);
buttonMinus.setOnClickListener(opListener);
buttonDivide.setOnClickListener(opListener);
buttonPlus.setOnClickListener(opListener);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString(STATE_PENDING_OPERATION, pendingOperation);
if (operand1 != null) {
outState.putDouble(STATE_PENDING_OPERATION, operand1);
}
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
pendingOperation = savedInstanceState.getString(STATE_PENDING_OPERATION);
operand1 = savedInstanceState.getDouble(STATE_OPERAND1);
displayOperation.setText(pendingOperation);
}
private void performOperation(Double value, String operation) {
// first thing is that it checks if first value is null
if (null == operand1) {
operand1 = value;
} else {
if (pendingOperation.equals(" = ")) {
pendingOperation = operation;
}
switch (pendingOperation) {
case "=":
operand1 = value;
break;
case "/":
if (value == 0) {
operand1 = 0.0;
} else {
operand1 /= value;
}
break;
case "*":
operand1 *= value;
break;
case "-":
operand1 -= value;
break;
case "+":
operand1 += value;
break;
}
}
// Displays the result
moeresult.setText(operand1.toString());
// It then clears it
moenewNumber.setText("");
}
}

Related

How to call method in android so able to run code

I want to create a simple calculator in Android, in my way I get an error on calling a fuction that i have already declared. Any Android Expert here that can help me?
public class CalculatorActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
}
//Start my method
public void calculator(View v) {
Button btn0 = (Button) findViewById(R.id.btn0);
Button btn1 = (Button) findViewById(R.id.btn1);
Button btn2 = (Button) findViewById(R.id.btn2);
Button btn3 = (Button) findViewById(R.id.btn3);
Button btn4 = (Button) findViewById(R.id.btn4);
Button btn5 = (Button) findViewById(R.id.btn5);
Button btn6 = (Button) findViewById(R.id.btn6);
Button btn7 = (Button) findViewById(R.id.btn7);
TextView textViewResult = (TextView) findViewById(R.id.textView);
if (btn0.isPressed() == true) {
textViewResult.setText(textViewResult + "0");
} else if (btn1.isPressed() == true) {
textViewResult.setText(textViewResult + "1");
}
}
//End my method
//I want to call that fucntion, and i get an error
calculator();
}
You should call that method inside OnCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
calculator();
}
Use Below Code:
public class CalculatorActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
//I want to call that fucntion, and i get an error
calculator();
}
//Start my method
public void calculator() {
Button btn0 = (Button) findViewById(R.id.btn0);
Button btn1 = (Button) findViewById(R.id.btn1);
Button btn2 = (Button) findViewById(R.id.btn2);
Button btn3 = (Button) findViewById(R.id.btn3);
Button btn4 = (Button) findViewById(R.id.btn4);
Button btn5 = (Button) findViewById(R.id.btn5);
Button btn6 = (Button) findViewById(R.id.btn6);
Button btn7 = (Button) findViewById(R.id.btn7);
TextView textViewResult = (TextView) findViewById(R.id.textView);
if (btn0.isPressed() == true) {
textViewResult.setText(textViewResult + "0");
} else if (btn1.isPressed() == true) {
textViewResult.setText(textViewResult + "1");
}
}
//End my method
}
call calculator() method inside your onCreate() method
Try this
public class CalculatorActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
calculator();
}
//Start my method
public void calculator() {
Button btn0 = (Button) findViewById(R.id.btn0);
Button btn1 = (Button) findViewById(R.id.btn1);
Button btn2 = (Button) findViewById(R.id.btn2);
Button btn3 = (Button) findViewById(R.id.btn3);
Button btn4 = (Button) findViewById(R.id.btn4);
Button btn5 = (Button) findViewById(R.id.btn5);
Button btn6 = (Button) findViewById(R.id.btn6);
Button btn7 = (Button) findViewById(R.id.btn7);
TextView textViewResult = (TextView) findViewById(R.id.textView);
if (btn0.isPressed() == true) {
textViewResult.setText(textViewResult + "0");
} else if (btn1.isPressed() == true) {
textViewResult.setText(textViewResult + "1");
}
}
//End my method
}
Call calculator(); inside your onCreate()
public class CalculatorActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
calculator();
}
//Start my method
public void calculator(View v) {
Button btn0 = (Button) findViewById(R.id.btn0);
Button btn1 = (Button) findViewById(R.id.btn1);
Button btn2 = (Button) findViewById(R.id.btn2);
Button btn3 = (Button) findViewById(R.id.btn3);
Button btn4 = (Button) findViewById(R.id.btn4);
Button btn5 = (Button) findViewById(R.id.btn5);
Button btn6 = (Button) findViewById(R.id.btn6);
Button btn7 = (Button) findViewById(R.id.btn7);
TextView textViewResult = (TextView) findViewById(R.id.textView);
if (btn0.isPressed() == true) {
textViewResult.setText(textViewResult + "0");
} else if (btn1.isPressed() == true) {
textViewResult.setText(textViewResult + "1");
}
}
}
Now it's going to working charm

create add function for calculator android

I need to create a calculator in Android. I need to create a plus function to add to numbers (integers). Here is my code. I also need to create other functions, like for subtraction.
public class MainActivity extends AppCompatActivity {
Button one,two,three,four,five,six,seven,eight,nine,plus,minus,mul,divide,equal;
TextView textView;
String currentDisplayedInput="";
private String inputToBeParsed = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
one = (Button) findViewById(R.id.one);
two = (Button) findViewById(R.id.two);
three = (Button) findViewById(R.id.three);
four = (Button) findViewById(R.id.four);
five = (Button) findViewById(R.id.five);
six = (Button) findViewById(R.id.six);
seven = (Button) findViewById(R.id.seven);
eight = (Button) findViewById(R.id.eight);
nine = (Button) findViewById(R.id.nine);
plus = (Button) findViewById(R.id.plus);
minus = (Button) findViewById(R.id.minus);
mul = (Button) findViewById(R.id.multiply);
divide = (Button) findViewById(R.id.divide);
equal=(Button)findViewById(R.id.equal);
textView = (TextView) findViewById(R.id.textView);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentDisplayedInput += "1";
//inputToBeParsed += "1";
textView.setText(currentDisplayedInput);
}
});
two.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentDisplayedInput += "2";
//inputToBeParsed += "1";
textView.setText(currentDisplayedInput);
}
});
equal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
All I need to do is to when I click 1 + 1, the TextView should show the result 2.

Android: How to pass parameters from OnClickListener to another

I'm new to android and Java. I wanna pass a variable (ac) from OnClickListener to another. I've tried this way, but i receive this error: cannot resolve symbol 'ac'. Can you help me please?
Button Calculate = (Button) theLayout.findViewById(R.id.button);
Button buttonb = (Button) theLayout.findViewById(R.id.buttonb);
final TextView tvac = (TextView) theLayout.findViewById(R.id.tvac);
final TextView tvh = (TextView) theLayout.findViewById(R.id.tvh);
final EditText eta = (EditText) theLayout.findViewById(R.id.eta);
final EditText etn = (EditText) theLayout.findViewById(R.id.etn);
final EditText etb = (EditText) theLayout.findViewById(R.id.etb);
Calculate.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Double a = new Double(eta.getText().toString());
Double n = new Double(etn.getText().toString());
Double ac = a*n;
tvac.setText(getResources().getString(R.string.tvresultados2) + " " + ac);
}
});
buttonb.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
double b = new Double(etb.getText().toString());
double h = ac/b; //error: cannot resolve symbol 'ac'
tvh.setVisibility(View.VISIBLE);
tvh.setText("h = " + h);
}
});
The most simple way is to declare global variable. Declare your ac outside of onCreate scope instead of inside of it.
public Double ac; // global variable
#Override
public void onCreate(Bundle savedInstanceState){
Button Calculate = (Button) theLayout.findViewById(R.id.button);
Button buttonb = (Button) theLayout.findViewById(R.id.buttonb);
final TextView tvac = (TextView) theLayout.findViewById(R.id.tvac);
final TextView tvh = (TextView) theLayout.findViewById(R.id.tvh);
final EditText eta = (EditText) theLayout.findViewById(R.id.eta);
final EditText etn = (EditText) theLayout.findViewById(R.id.etn);
final EditText etb = (EditText) theLayout.findViewById(R.id.etb);
Calculate.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Double a = new Double(eta.getText().toString());
Double n = new Double(etn.getText().toString());
ac = a*n;
tvac.setText(getResources().getString(R.string.tvresultados2) + " " + ac);
}
});
buttonb.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
double b = new Double(etb.getText().toString());
double h = ac; //assign global variable into h
tvh.setVisibility(View.VISIBLE);
tvh.setText("h = " + h);
}
});
}

I have 34 buttons on my android application. Is there any way to avoid writing onclicklistener for each of them?

Can i write some code so that instead of writing a separate onClick listener i can group them all in single piece of code? Presently i have this. Now how can i avoid writing onclicklistener method for each.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DecimalFormat currencyFormatter = (DecimalFormat) NumberFormat.getInstance();
char decimalSeparator = currencyFormatter.getDecimalFormatSymbols().getDecimalSeparator();
mDecimalSeparator = Character.toString(decimalSeparator);
setContentView(R.layout.main);
mInputStack = new Stack<String>();
mOperationStack = new Stack<String>();
inputText = (TextView) findViewById(R.id.InputText);
inputText.setText("0");
resultText = (TextView) findViewById(R.id.ResultText);
resultText.setText("");
One = (Button) findViewById(R.id.button1);
Two = (Button) findViewById(R.id.button2);
Three = (Button) findViewById(R.id.button3);
Four = (Button) findViewById(R.id.button4);
Five = (Button) findViewById(R.id.button5);
Six = (Button) findViewById(R.id.button6);
Seven = (Button) findViewById(R.id.button7);
Eight = (Button) findViewById(R.id.button8);
Nine = (Button) findViewById(R.id.button9);
Zero = (Button) findViewById(R.id.button0);
Add = (Button) findViewById(R.id.buttonAdd);
Subtract = (Button) findViewById(R.id.buttonSubtract);
Multiply = (Button) findViewById(R.id.buttonMultiply);
Divide = (Button) findViewById(R.id.buttonDivide);
Delete = (Button) findViewById(R.id.buttonDel);
Period = (Button) findViewById(R.id.buttonPeriod);
Equal = (Button) findViewById(R.id.buttonEqual);
Sin = (Button) findViewById(R.id.buttonSin);
Cos = (Button) findViewById(R.id.buttonCos);
Tan = (Button) findViewById(R.id.buttonTan);
Cosec = (Button) findViewById(R.id.buttonCosec);
Sec = (Button) findViewById(R.id.buttonSec);
Cot = (Button) findViewById(R.id.buttonCot);
Sinh = (Button) findViewById(R.id.buttonSinh);
Cosh = (Button) findViewById(R.id.buttonCosh);
Tanh = (Button) findViewById(R.id.buttonTanh);
Factorial = (Button) findViewById(R.id.buttonFactorial);
Log = (Button) findViewById(R.id.buttonLog10);
Ln = (Button) findViewById(R.id.buttonLoge);
Reciprocal = (Button) findViewById(R.id.buttonReciprocal);
Square = (Button) findViewById(R.id.buttonSquare);
SquareRoot = (Button) findViewById(R.id.buttonSquareRoot);
Power = (Button) findViewById(R.id.buttonPower);
Percent = (Button) findViewById(R.id.buttonPercent);
One.setOnClickListener(this);
Two.setOnClickListener(this);
Three.setOnClickListener(this);
Four.setOnClickListener(this);
Five.setOnClickListener(this);
Six.setOnClickListener(this);
Seven.setOnClickListener(this);
Eight.setOnClickListener(this);
Nine.setOnClickListener(this);
Zero.setOnClickListener(this);
Add.setOnClickListener(this);
Subtract.setOnClickListener(this);
Divide.setOnClickListener(this);
Multiply.setOnClickListener(this);
Equal.setOnClickListener(this);
Delete.setOnClickListener(this);
Period.setOnClickListener(this);
Sin.setOnClickListener(this);
Cos.setOnClickListener(this);
Tan.setOnClickListener(this);
Cot.setOnClickListener(this);
Sec.setOnClickListener(this);
Cosec.setOnClickListener(this);
Sinh.setOnClickListener(this);
Cosh.setOnClickListener(this);
Tanh.setOnClickListener(this);
Percent.setOnClickListener(this);
Reciprocal.setOnClickListener(this);
Log.setOnClickListener(this);
Ln.setOnClickListener(this);
Power.setOnClickListener(this);
Square.setOnClickListener(this);
SquareRoot.setOnClickListener(this);
Factorial.setOnClickListener(this);
Sign.setOnClickListener(this);
You can set an android:click property in the xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="Go!"
android:onClick="goButtonClicked" android:id="#+id/goButton"></Button>
</LinearLayout>
SimplestButtonActivity.java
package com.botbook.simplestbutton;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class SimplestButtonActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void goButtonClicked(View v) {
tToast("Go button clicked!");
}
private void tToast(String s) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, s, duration);
toast.show();
}
}
You can set an android:click property in the xml. This will allow you to decide what function to call when the button is clicked in the xml. The function must take the same parameters as the normal onClick function and must be part of your activity, but can be named anything you want- Like onePressed, twoPressed, etc.
Try this
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
// do stuff;
break;
case R.id.button2:
// do stuff;
break;
case R.id.button3:
// do stuff;
break;
//....add here add buttons
default:
break;
}
}

android application development- saving and retrieving the values of editText and textView

I am a beginner to this field of android and am currently in pursuit of developing an application to track the number of periods that i have bunked with the use of counters and the subject names in edittext and the values of counters keeps on incrementing as the button bunked is pressed everytime and its change will be effected in a textfield respectively
my app has only one activity and when the user has finished entering the data in edittext and as the counters are incremented so do the values in textview and when the user presses the back button the app exits and now when the user enters the app once again now all the previously entered data are gone...
no data in edittext or textview either...
public class MainActivity extends Activity {
public static final String sub1="sub";
public static final String count1="Count";
String sub[]=new String[10];
String count[]=new String[10];
int counter[]=new int[10];
Button button[]=new Button[10];
EditText et[]=new EditText[10];
TextView tv[]=new TextView[12];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button[0] = (Button) findViewById(R.id.button1);
button[1] = (Button) findViewById(R.id.button2);
button[2] = (Button) findViewById(R.id.button3);
button[3] = (Button) findViewById(R.id.button4);
button[4] = (Button) findViewById(R.id.button5);
button[5] = (Button) findViewById(R.id.button6);
button[6] = (Button) findViewById(R.id.button7);
button[7] = (Button) findViewById(R.id.button8);
button[8] = (Button) findViewById(R.id.button9);
tv[0] = (TextView) findViewById(R.id.textView2);
tv[1] = (TextView) findViewById(R.id.textView3);
tv[2] = (TextView) findViewById(R.id.textView4);
tv[3] = (TextView) findViewById(R.id.textView5);
tv[4] = (TextView) findViewById(R.id.textView6);
tv[5] = (TextView) findViewById(R.id.textView7);
tv[6] = (TextView) findViewById(R.id.textView8);
tv[7] = (TextView) findViewById(R.id.textView9);
tv[8] = (TextView) findViewById(R.id.textView10);
tv[9] = (TextView) findViewById(R.id.textView1);
et[0] = (EditText) findViewById(R.id.editText1);
et[1] = (EditText) findViewById(R.id.editText2);
et[2] = (EditText) findViewById(R.id.editText3);
et[3] = (EditText) findViewById(R.id.editText4);
et[4] = (EditText) findViewById(R.id.editText5);
et[5] = (EditText) findViewById(R.id.editText6);
et[6] = (EditText) findViewById(R.id.editText7);
et[7] = (EditText) findViewById(R.id.editText8);
et[8] = (EditText) findViewById(R.id.editText9);
for(int l=0;l<9;l++) {
sub[l]=et[l].getText().toString();
et[l].setText(sub[l]);
}
for (int j = 0; j < 9; j++) {
button[j].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
for(int k=0;k<9;k++) {
if(button[k]==arg0.findViewById(R.id.button1)) {
counter[k]++;
tv[k].setText(""+counter[k]);
}
if(button[k]==arg0.findViewById(R.id.button2)) {
counter[k]++;
tv[k].setText(""+counter[k]);
}
if(button[k]==arg0.findViewById(R.id.button3)) {
counter[k]++;
tv[k].setText(""+counter[k]);
}
if(button[k]==arg0.findViewById(R.id.button4)) {
counter[k]++;
tv[k].setText(""+counter[k]);
}
if(button[k]==arg0.findViewById(R.id.button5)) {
counter[k]++;
tv[k].setText(""+counter[k]);
}
if(button[k]==arg0.findViewById(R.id.button6)) {
counter[k]++;
tv[k].setText(""+counter[k]);
}
if(button[k]==arg0.findViewById(R.id.button7)) {
counter[k]++;
tv[k].setText(""+counter[k]);
}
if(button[k]==arg0.findViewById(R.id.button8)) {
counter[k]++;
tv[k].setText(""+counter[k]);
}
if(button[k]==arg0.findViewById(R.id.button9)) {
counter[k]++;
tv[k].setText(""+counter[k]);
}
}
}
});
}
}
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString(sub1,sub[0]);
savedInstanceState.putInt(count1, counter[0]);
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
sub[0]=savedInstanceState.getString(sub1);
counter[0]=savedInstanceState.getInt(count1);
}
}
Its happening because you are saving all data in Arrays which get cleaned up when the app exits. There are several ways tht you could do this. You could either use SharedPreferences to save your data or write your values to a file.
For e.g. you could use SharedPreferences as follows:
public static final String MY_PREF = "MyPreference";
SharedPreferences.Editor editorPref;
public static String keyName = "MyKey";
SharedPreferences myPref;
You could then create the shared preference and add values to it.Hope this helps

Categories