create add function for calculator android - java

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.

Related

No display result in TextView

I'm a beginner, I did a simple task but I do not see the result in TextView. How can I solve my problem?
Code:
public class MainActivity extends AppCompatActivity {
Button button;
EditText editText1, editText2;
TextView textView;
public void Add(View v)
{
float x = Float.parseFloat(editText1.getText().toString());
float y = Float.parseFloat(editText2.getText().toString());
float sum = x + y;
textView.setText(String.valueOf(sum));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
editText1 = findViewById(R.id.editText);
editText2 = findViewById(R.id.editText2);
textView = findViewById(R.id.textView);
}
}
The second option I tried was:
textView.setText("SUM = " + String.valueOf(sum));
But then I receive a message:
Do not concatenate text displayed with setText. Use resource string with placeholders.
PS. Of course i added method android:onClick = "Add"
You can try sum.toString() instead of String.valueOf(sum)
This will do your work
textView.setText(Float.toString(sum))
you better make button onclick in java, then display the string value to the textview
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handleButtonClick();
}
private void handleButtonClick() {
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
addAndSetResult();
}
});
}
private void addAndSetResult() {
// inside here do the add logic and set result to textview
EditText editText1 = (EditText) findViewById(R.id.editText1);
EditText editText2 = (EditText) findViewById(R.id.editText2);
float x = Float.parseFloat(editText1.getText().toString());
float y = Float.parseFloat(editText2.getText().toString());
float sum = x + y;
String sumStr = String.valueOf(sum);
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(sumStr);
}

Null pointer on not null index? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Like in subject. I got null pointer, how it is possible ?
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
public class MainActivity extends AppCompatActivity {
Button button, button2;
TextView textView, textView2;
String abc;
public List list = new ArrayList<>();
int size;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list.add("abc");
abc = (String) list.get(0);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
textView.setText(abc);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
size = list.size();
textView2.setText(size);
}
});
}
}
You just forgot to do findViewById to your Controls in OnCreate()
button2 =(Button) findViewById(R.id.button2);
button = (Button) findViewById(R.id.btnID);
textView2 =(textView) findViewById(R.id.textView2);
Sample code
#Override
protected void onCreate( Bundle savedInstanceState ){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.mybtnID);
button2 = (Button) findViewById(R.id.button2);
textView2 = (textView) findViewById(R.id.textView2);
list.add("abc");
abc = (String) list.get(0);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick( View view ){
textView.setText(abc);
}
});
button2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick( View view ){
size = list.size();
textView2.setText(size);
}
});
}
You are missing
findViewById for all your widget
i.e.
Button button, button2;
TextView textView, textView2;
button = findViewById(R.id.id_of_button_1); // same for button2,textview,textview2
You can initialize with findById(R.id.myBtn) like everyone is saying. Or programatically like button = new Button(this);
Try this
You forgot to add findViewById
public class MainActivity extends AppCompatActivity {
Button button, button2;
TextView textView, textView2;
String abc;
public List list = new ArrayList<>();
int size;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button);
button2=(Button)findViewById(R.id.button2);
list.add("abc");
abc = (String) list.get(0);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
textView.setText(abc);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
size = list.size();
textView2.setText(size);
}
});
}
}
Try this are missing findViewById for all your widget
button = (Button) findViewById(R.id.btnID);
button2 =(Button) findViewById(R.id.button2);
textView = =(textView) findViewById(R.id.textView);
textView2 =(textView) findViewById(R.id.textView2);
Sample Code
public class MainActivity extends AppCompatActivity {
Button button, button2;
TextView textView, textView2;
String abc;
public List list = new ArrayList<>();
int size;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.btnID);
button2 =(Button) findViewById(R.id.button2);
textView = =(textView) findViewById(R.id.textView);
textView2 =(textView) findViewById(R.id.textView2);
list.add("abc");
abc = (String) list.get(0);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
textView.setText(abc);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
size = list.size();
textView2.setText(size);
}
});
}
}

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

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