getting NumberFormatException: s == null after clicking button - android

I'm newbie in android. After clicking this button(when nothing is in TextView i.e. it shows "" ) I'm getting NumberFormatException but in other cases it is working .I want to show toast message if nothing is in the String and my TextView initially is
android:id="#+id/text_view_result"
android:text=""
that button is
buttonExpense.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Integer.valueOf(result) < 0) {
Toast.makeText(getActivity().getApplicationContext(), "Amount can't be negative", Toast.LENGTH_SHORT).show();
return;
}
else if (Integer.valueOf(result) > 0) {
Intent intent = new Intent(fa2, EditorActivity.class);
intent.putExtra("result", result);
startActivity(intent);
}
else if(Integer.valueOf(result) == 0) {
Toast.makeText(getActivity().getApplicationContext(), "Amount can't be 0", Toast.LENGTH_SHORT).show();
return;
}
else{
Toast.makeText(getActivity().getApplicationContext(), "Please enter your amount", Toast.LENGTH_SHORT).show();
return;
}
}
});
method where result String is used is in method as given below
private void onEqualButtonClicked() {
int res = 0;
try {
int number = Integer.valueOf(tmp);
int number2 = Integer.valueOf(resultTextView.getText().toString());
switch (operator) {
case "+":
res = number + number2;
break;
case "/":
res = number / number2;
break;
case "-":
res = number - number2;
break;
case "X":
res = number * number2;
break;
}
result = String.valueOf(res);
resultTextView.setText(result);
}
catch (Exception e) {
e.printStackTrace();
}

An empty string is not a number. What you want to do is check if it's a number first and then handle it.
int number;
try {
number = Integer.parseInt(result);
} catch (NumberFormatException exception) {
// handle case where it's not a number
}
// perform logic where it is a number

Related

My Toast doesn't appear

I don't know why but the toast doesn't appear when I run the program. This is my code:
class Number {
int number;
public boolean isSquare() {
double squareRoot = Math.sqrt(number);
if (squareRoot==Math.floor(squareRoot)) {
return true;
} else {
return false;
}
}
public boolean isTriangular() {
int x = 1;
int triangularNumber = 1;
while(triangularNumber<number) {
x++;
triangularNumber = triangularNumber + x;
}
if (triangularNumber == number) {
return true;
} else {
return false;
}
}
}
public void idButton (View view) {
EditText inputNumber = (EditText) findViewById(R.id.inputNumber);
Number myNumber = new Number();
myNumber.number = Integer.parseInt(inputNumber.getText().toString());
String message = "";
if (myNumber.isSquare()){
if (myNumber.isTriangular()){
message = myNumber.number + " your number is triangular and square";
}
}
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
After compiling there's no error in the code, please guide me what should be improved on the code since I'm still beginner. Could you help me? Thanks.
String message = "";
if (myNumber.isSquare()){
if (myNumber.isTriangular()){
message = myNumber.number + " your number is triangular and square";
}
}
In this code, you haven't write any else statement. What if the number is neither square nor triangular? In both of these scenerios you will get an empty message as you have declared message = "";
So write your code as
String message = "";
if (myNumber.isSquare()){
if (myNumber.isTriangular()){
message = message+myNumber.number + " your number is triangular and square";
}
else
{
message = message+"No triangular";
}
}
else
{
message = message+"No square";
}

I have calculate and display result of trigonometric function on android app

When i click on digit button on app and then on cos for example, works fine.
When i click on cos and number, return -1.
For example on display TextView i see:
1cos
0.540302320
if i put:
cos1
-1
I use a switch case.
private double operateAritmetic(String a, String b, String op){
switch (op){
case "+": return (Double.valueOf(a) + Double.valueOf(b));
case "-": return (Double.valueOf(a) - Double.valueOf(b));
case "*": return (Double.valueOf(a) * Double.valueOf(b));
case "/": try{
return (Double.valueOf(a) / Double.valueOf(b));
}catch (Exception e){Log.d("Calc",e.getMessage());
}
default: return -1;
}
}
private double operateTrigonometric(String a, String op){
switch (op){
case "Sin":
return(Math.sin(Double.valueOf(a)));
case "Cos":
return(Math.cos(Double.valueOf(a)));
case "Tan":
try{
return(Math.tan(Double.valueOf(a)));
}catch(Exception e){
Log.d("Calc", e.getMessage());
}
case "sqrt":
return(Math.sqrt(Double.valueOf(a)));
default: return -1;
}
}
public void onClickEqual(View v){
String[] operation=display.split(Pattern.quote(currentOperator));
Double result;
if(operation.length==1) {
result = operateTrigonometric(operation[0],currentOperator);
_screen.setText(display + "\n" + String.valueOf(result));
}
else if (operation.length<2)
return;
else {
result = operateAritmetic(operation[0], operation[1], currentOperator);
_screen.setText(display + "\n" + String.valueOf(result));
}
}

Button Print Toast When Clicked without answer Given

I have this button which calls two methods. See Code; Now i have tried to add a method on my onPictureSubmit(v) method which will print a Toast message (Please Submit Answer) if someone clicked the button without submitting an answer. Problem is it keeps crushing. Any help on how i can detect someone clicked the button without submitting answer will be appreciated.
My Button Code;
#Override
public void onClick(View v) {
switch (pass) {
case 0:
onDefinitionSubmit(v);
break;
case 1:
onPictureSubmit(v);
break;
case 2
break;
}
}
My Code :
private void onPictureSubmit(View v) {
if (v.getId() == R.id.picture_submit) {
final int answerGiven = Integer.parseInt("" + ((EditText) findViewById(R.id.picture_answer)).getText());
final int answerKey = com.madonasystematixnote.mathhelper.lessons.PictureFragment.answer;
final int x = Integer.parseInt("" + ((TextView) findViewById(R.id.picture_x)).getText());
final int y = Integer.parseInt("" + ((TextView) findViewById(R.id.picture_y)).getText());
}
}
If I were you I'd declare the TextView, EditText, Button as a global variable, and then in your onCreate() I'd use the findViewById() to avoid NullPointerException.
Second, I'd check if the answerGiven (I guess is the answer) it's empty, so I'd create a method that returns me if it's empty or not the EditText.
public boolean isEtEmpty(String str){
if(str.isEmpty() || str.length() == 0 || str.equals("") || str == null){
return true;
}
else{
return false;
}
}
Then at the time you call onPictureSubmit() call this method doing this :
if (v.getId() == R.id.picture_submit) {
if (isEtEmpty(picture_answer.getText())){ //picture_answer is the EditText that you want to know if it's empty or not
Toast.makeText(v.getContext(), "Please Submit Answer",Toast.LENGTH_LONG).show();
}
else{
final int answerGiven = Integer.parseInt("" + ((EditText) findViewById(R.id.picture_answer)).getText());
final int answerKey = com.madonasystematixnote.mathhelper.lessons.PictureFragment.answer;
final int x = Integer.parseInt("" + ((TextView) findViewById(R.id.picture_x)).getText());
final int y = Integer.parseInt("" + ((TextView) findViewById(R.id.picture_y)).getText());
}
}

calculator with one input edittext android

i am a beginner in android. i am trying to make a calculator with just one input edit text.
when i click + button it doesn't give a sum output. to get a correct ans i have to click the +button after both the entries. like to get a sum i will do it as 1"+" 1"+""=. then it would give 2. here's my code,someoneplease help me.
public void onClick(View v){
double sum=0;
switch(v.getId()){
case R.id.buttonplus:
sum += Double.parseDouble(String.valueOf(textView.getText()));
numberDisplayed.delete(0,numberDisplayed.length());
break;
case R.id.buttonequal:
resultView.setText(String.valueOf(sum));
sum=0;
}
If I understand you correctly, you want the sum to show after you press the "equals" button. If so, then you need to have
sum += Double.parseDouble(String.valueOf(textView.getText()));
in this line also
case R.id.buttonequal:
sum += Double.parseDouble(String.valueOf(textView.getText()));
resultView.setText(String.valueOf(sum));
sum=0;
The second number isn't entered yet when you press the "plus" button so the sum is only the first number. Then you have to press it again to add to sum
So in if equals btn pressed, something like
if (lastOp.equals("sub")
{
sum -= Double.parseDouble(String.valueOf(textView.getText()));
...
}
Example
public class SimpleCalculatorActivity extends Activity
{
//variables needing class scope
double answer = 0, number1, number2;
int operator = 0, number;
boolean hasChanged = false, flag = false;
String display = null;
String display2 = null;
String curDisplay = null;
String calcString = "";
String inputLabel;
String inputString = null;
String inputString2 = null;
String inputString3 = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.setTitle("Super Duper Calculator");
initButtons();
}
//when button is pressed, send num to calc function
button1.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
inputString = button1.getText().toString();
displayCalc(inputString);
}
}
);
button2.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
inputString = button2.getText().toString();
displayCalc(inputString);
}
}
);
...
//send operator to calc function
addButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(1);
}
}
);
subButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(2);
}
}
);
calcButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(5);
}
}
);
clearButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(6);
}
}
);
}
//function to calculate
public void calculation(int input)
{
number = input;
//see which operator was clicked
switch (number)
{
case 1:
operator = 1;
hasChanged = true;
display = "";
showDisplay("+");
break;
case 2:
operator = 2;
hasChanged = true;
display = "";
showDisplay("-");
break;
case 3:
operator = 3;
hasChanged = true;
display = "";
showDisplay("*");
break;
case 4:
operator = 4;
hasChanged = true;
display = "";
showDisplay("/");
break;
case 5:
number2 = Double.parseDouble(display2);
if(number2 == 0)
{
custErrMsg();
}
else
{
operator();
displayAnswer(answer);
hasChanged = true;
}
break;
case 6:
clear();
break;
default:
clear();
break;
}
}
private void operator()
{
if (operator != 0)
{
if (operator == 1)
{
answer = number1 + number2;
}
else if (operator == 2)
{
answer = number1 - number2;
}
else if (operator == 3)
{
answer = number1 * number2;
}
else if (operator == 4)
{
answer = number1 / (number2);
}
}
}
private void displayCalc(String curValue)
{
String curNum = curValue;
if (!hasChanged)
{
if (display == null)
{
//display number if reset
inputString2 = curNum;
display = inputString2;
showDisplay(display);
}
else
{
//display previous input + new input
inputString2 = inputString2 + curNum;
display = display + curNum;
showDisplay(display);
}
}
else
{
displayNum2(curNum);
}
}
private void displayNum2 (String curValue2)
{
String curNum2;
curNum2 = curValue2;
if (!flag)
{
//display number if reset
inputString3 = curNum2;
display2 = inputString3;
number1 = Double.parseDouble(inputString2);
flag = true;
}
else
{
//display previous input + new input
inputString3 = curNum2;
display2 = display2 + curNum2;
}
showDisplay(inputString3);
}
private void displayAnswer(double curAnswer)
{
String finAnswer = String.valueOf(curAnswer);
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView1.setBackgroundColor(0xffffffff);
textView1.setText(finAnswer);
}
private void showDisplay(String output)
{
inputLabel = output;
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView1.setBackgroundColor(0xffffffff);
if (operator != 0)
{
curDisplay = textView1.getText().toString();
textView1.setText(curDisplay + inputLabel);
}
else
{
textView1.setText(inputLabel);
}
}

android: How to change ListViewItem Background on runtime? (Not for selection)

In my android app, I need to change the Background color of each Item of my ListView seperately.
I found no examples or helpful documentation. The background should change if the value of a double is 0. I set the ListView Property: android:drawSelectorOnTop="true" and used following code:
(All of it functions, only the background doesn't change!) How can I solve this problem?
public void onClickButtonOKStand (View view) {
EditAusgabe = (EditText) findViewById(R.id.EditText01);
if (EditAusgabe.getText().toString().length() <= 0) {
Toast T = Toast.makeText(getApplicationContext(), "Eingabe ungültig! Geben Sie einen Betrag ein", Toast.LENGTH_LONG);
T.show();
return;
}
if (EditAusgabe.getText().toString() == ".") {
Toast T = Toast.makeText(getApplicationContext(), "Eingabe ungültig! Geben Sie einen Betrag ein", Toast.LENGTH_LONG);
T.show();
return;
}
Z = Double.parseDouble(EditAusgabe.getText().toString());
if (VArt == "Down") {
if (VStand >= Z) {
VStand = VStand - Z;
if (VStand <= 0.39) {
Toast T = Toast.makeText(getApplicationContext(), "Ihr Guthaben ist aufgebraucht!", Toast.LENGTH_strong textLONG);
T.show();
VStand = 0.00;
****************** The next line is my problem: ******************************
StartListe.getChildAt(Position).setBackgroundColor(color.holo_red_light);
}
}
else if (VStand < Z) {
Toast T = Toast.makeText(getApplicationContext(), "Vorgang nicht möglich! Ihr Konto liegt bei " + FORMAT.format(VStand) + " €.", Toast.LENGTH_LONG);
T.show();
EditAusgabe.setText("");
return;
}
}
if (VArt == "Up") {
VStand = VStand + Z;
}
Stand.set(Position, FORMAT.format(VStand));
Liste.set(Position, (VName + " " + FORMAT.format(VStand) + " € / " + FORMAT.format(VWert) + " €"));
ListeAktualisieren();
}
public void ListeAktualisieren () {
setContentView(R.layout.activity_ausgabenkontrolle);
ArrayAdapter<String> ListenAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Liste);
StartListe = (ListView) findViewById(R.id.listView1);
StartListe.setAdapter(ListenAdapter);
StartListe.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> ListenAdapter, View view, int i, long ID) {
// TODO Auto-generated method stub
Item = view;
Position = ListenAdapter.getPositionForView(view);
VName = Namen.get(Position);
VArt = Arten.get(Position);
VWert = Double.parseDouble(Werte.get(Position).toString());
VStand = Double.parseDouble(Stand.get(Position).toString());
setContentView(R.layout.activity_stand);
if (VArt == "Down") {
if (VStand == 0) {
Toast T = Toast.makeText(getApplicationContext(), "Ihr Guthaben ist aufgebraucht!", Toast.LENGTH_LONG);
T.show();
}
}
}
});
registerForContextMenu(StartListe);
}
I think the way to change the background color in response to a click is to apply the change to the incoming View given to you in your onClickListener implementation. You seem to be messing about with setContentViews, etc. which isn't the way to go. SetContentView sets your overall layout, and there's rarely a reason to call it more than once in an Activity.

Categories

Resources