app crashes on button click when editText is empty - android

i am creating a single screen app of grocery but while checking total price if a user doesnt type anything it should by default be equal to 0 but instead my app crashes
Below is the code for same
Activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.ashis.singlescreenapp.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/headline"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textView2" />
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:src="#mipmap/grocery_logo"
android:id="#+id/imageView"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/qty_heading"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textView_qty"
android:layout_below="#+id/imageView"
android:layout_alignLeft="#+id/imageView"
android:layout_alignStart="#+id/imageView" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView_qty"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/linearLayout">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText_apples"
android:layout_weight="1"
android:hint="Apples ($2 per piece)" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText_orange"
android:layout_weight="1"
android:hint="Orange($3 per piece)" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/linearLayout2">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText_mango"
android:layout_weight="1"
android:hint="Mango($4 per piece)" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText_banana"
android:layout_weight="1"
android:hint="Banana($1 per piece)" />
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button_confirm"
android:text="#string/btn_confirm"
android:onClick="onbuttonClicked"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textView_result"
android:minWidth="300dp"
android:layout_below="#+id/linearLayout2"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check"
android:id="#+id/button"
android:layout_above="#+id/button_confirm"
android:layout_centerHorizontal="true"
android:onClick="checkPrice" />
</RelativeLayout>
MainActivity.java
package com.example.ashis.singlescreenapp;
import android.content.Intent;
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;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText editText_apples,editText_orange,editText_mango,editText_banana;
int apples,orange,mango,banana;
TextView textView_result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void checkPrice(View view)
{
editText_apples=(EditText) findViewById(R.id.editText_apples);
editText_orange=(EditText) findViewById(R.id.editText_orange);
editText_banana=(EditText) findViewById(R.id.editText_banana);
editText_mango=(EditText) findViewById(R.id.editText_mango);
textView_result=(TextView) findViewById(R.id.textView_result);
apples=Integer.parseInt(editText_apples.getText().toString());
orange=Integer.parseInt(editText_orange.getText().toString());
mango=Integer.parseInt(editText_mango.getText().toString());
banana=Integer.parseInt(editText_banana.getText().toString());
if (editText_apples.getText().toString().equals(""))
{
apples=0;
}
else if (editText_banana.getText().toString().equals(""))
{
banana=0;
}
else if (editText_orange.getText().toString().equals(""))
{
orange=0;
}
else if (editText_mango.getText().toString().equals(""))
{
mango=0;
}
else {
int result = getPrice(apples, orange, mango, banana);
textView_result.setText(String.valueOf(result));
}
}
private int getPrice(int apples, int orange, int mango, int banana) {
int result= (apples*2) + (orange*3) + (mango*4) + (banana);
return result;
}
/*
public void onbuttonClicked(View view)
{
String email_body = "Dear Grocery Store, \n" + "Send all the following ";
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL,"ashish.choudhary#groceryStore.com");
intent.putExtra(Intent.EXTRA_SUBJECT," Send All these Product");
intent.putExtra(Intent.EXTRA_TEXT,"");
}
*/
}
Here is the logCat when i click on Confirm Button
FATAL EXCEPTION: main
Process: com.example.ashis.singlescreenapp, PID: 22748
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5226)
at android.view.View$PerformClick.run(View.java:21350)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5571)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5226) 
at android.view.View$PerformClick.run(View.java:21350) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5571) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Caused by: java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at com.example.ashis.singlescreenapp.MainActivity.checkPrice(MainActivity.java:36)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:5226) 
at android.view.View$PerformClick.run(View.java:21350) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5571) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

The problem is you are trying to format an empty String. Just check
if(!edittext.getText().toString().equals("")) {
apples = Integer.parseInt(edittext.getText().toString());
} else {
apples = 0;
}
Or you could use the short form:
apples = edittext.getText().toString().equals("") ? 0 : Integer.parseInt(edittext.getText().toString());

You are calling parseInt before you check for empty string. parseInt on empty string will throw exception. You should in any case surround parseInt with a try catch.

You can debug your code and you see - you are trying to parse int before checking text.
You need something like this for each edit text:
if (editText_apples.getText().toString().equals("")) {
apples=0;
} else {
apples=Integer.parseInt(editText_apples.getText().toString());
}
or short variant:
apples = editText_apples.getText().toString().isEmpty() ? 0
: Integer.parseInt(editText_apples.getText().toString());
To be sure, that in edit text will be only numbers, you can add inputType for edit text:
<EditText
...
android:inputType="number"/>

You have some issues trying to parse for integers from empty strings. Try replace this piece of code:
apples=Integer.parseInt(editText_apples.getText().toString());
orange=Integer.parseInt(editText_orange.getText().toString());
mango=Integer.parseInt(editText_mango.getText().toString());
banana=Integer.parseInt(editText_banana.getText().toString());
if (editText_apples.getText().toString().equals(""))
{
apples=0;
}
else if (editText_banana.getText().toString().equals(""))
{
banana=0;
}
else if (editText_orange.getText().toString().equals(""))
{
orange=0;
}
else if (editText_mango.getText().toString().equals(""))
{
mango=0;
}
else {
int result = getPrice(apples, orange, mango, banana);
textView_result.setText(String.valueOf(result));
}
with this:
String txt1 = editText_apples.getText().toString();
apples=Integer.parseInt("".equals(txt1.trim()) ? "0" : txt1);
String txt2 = editText_orange.getText().toString();
orange=Integer.parseInt("".equals(txt2.trim()) ? "0" : txt2);
String txt3 = editText_mango.getText().toString();
mango=Integer.parseInt("".equals(txt3.trim()) ? "0" : txt3);
String txt4 = editText_banana.getText().toString();
banana=Integer.parseInt("".equals(txt4.trim()) ? "0" : txt4);
int result = getPrice(apples, orange, mango, banana);
textView_result.setText(String.valueOf(result));

Initialise view while setting content
public class MainActivity extends AppCompatActivity {
EditText editText_apples,editText_orange,editText_mango,editText_banana;
int apples,orange,mango,banana;
TextView textView_result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText_apples=(EditText) findViewById(R.id.editText_apples);
editText_orange=(EditText) findViewById(R.id.editText_orange);
editText_banana=(EditText) findViewById(R.id.editText_banana);
editText_mango=(EditText) findViewById(R.id.editText_mango);
textView_result=(TextView) findViewById(R.id.textView_result);
}
public void checkPrice(View view)
{
if(TextUtils.isDigitOnly(editText_apples.getText().toString()){
apples=Integer.parseInt(editText_apples.getText().toString());
}else{
apples=0;
}
if(TextUtils.isDigitOnly(editText_orange.getText().toString()){
orange=Integer.parseInt(editText_orange.getText().toString());
}else{
orange=0;
}
if(TextUtils.isDigitOnly(editText_mango.getText().toString()){
mango=Integer.parseInt(editText_mango.getText().toString());
}else{
mango=0;
}
if(TextUtils.isDigitOnly(editText_banana.getText().toString()){
banana=Integer.parseInt(editText_banana.getText().toString());
}else{
banana=0;
}
int result = getPrice(apples, orange, mango, banana);
textView_result.setText(String.valueOf(result));
}
private int getPrice(int apples, int orange, int mango, int banana) {
int result= (apples*2) + (orange*3) + (mango*4) + (banana);
return result;
}
}
in your code at the time of button clicks views are getting initialized and then u will be able to use them and the values are null in edit text so casting them in integer generates null pointer exception.

#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText_apples=(EditText) findViewById(R.id.editText_apples);
editText_orange=(EditText) findViewById(R.id.editText_orange);
editText_banana=(EditText) findViewById(R.id.editText_banana);
editText_mango=(EditText) findViewById(R.id.editText_mango);
textView_result=(TextView) findViewById(R.id.textView_result);
checkPrice();
}
public void checkPrice()
{
apples = edittext_apples.getText().toString().equals("") ? 0 : Integer.parseInt(edittext.getText().toString());
orange=editText_orange..getText().toString().equals("") ? 0 : Integer.parseInt(edittext.getText().toString());
mango=editText_mango..getText().toString().equals("") ? 0 : Integer.parseInt(edittext.getText().toString());
banana=editText_banana.getText().toString().equals("") ? 0 : Integer.parseInt(edittext.getText().toString());
...............
}

Related

I keep getting a error when I execute the send Credentials void

When I run my code i get a error when the SendCredentials void is executed.
The error is:-
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.messager, PID: 16131
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
at android.view.View.performClick(View.java:6614)
at android.view.View.performClickInternal(View.java:6591)
at android.view.View.access$3100(View.java:786)
at android.view.View$PerformClick.run(View.java:25948)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6806)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:6614) 
at android.view.View.performClickInternal(View.java:6591) 
at android.view.View.access$3100(View.java:786) 
at android.view.View$PerformClick.run(View.java:25948) 
at android.os.Handler.handleCallback(Handler.java:873) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:201) 
at android.app.ActivityThread.main(ActivityThread.java:6806) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.io.DataInputStream.readLine()'
on a null object reference
at com.example.messager.MainActivity.SendCredentials(MainActivity.java:69)
at com.example.messager.MainActivity.SendMessage(MainActivity.java:26)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385) 
at android.view.View.performClick(View.java:6614) 
at android.view.View.performClickInternal(View.java:6591) 
at android.view.View.access$3100(View.java:786) 
at android.view.View$PerformClick.run(View.java:25948) 
at android.os.Handler.handleCallback(Handler.java:873) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:201) 
at android.app.ActivityThread.main(ActivityThread.java:6806) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
My Code is
package com.example.messager;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import java.net.*;
import java.io.*;
public class MainActivity extends AppCompatActivity {
EditText stopPort;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void SendMessage(View view)throws IOException{
EditText emailText = (EditText) findViewById(R.id.Email);
String Username = emailText.getText().toString();
EditText passwordText = (EditText) findViewById(R.id.Password);
String Password = passwordText.getText().toString();
System.out.println("Your username is " + Username + "Your Password is " + Password);
SendCredentials();
}
public void SendCredentials()throws IOException {
System.out.println("Work");
Socket socket = new Socket("192.168.0.114", 4321);
System.out.println("Work");
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
dOut.writeByte(1);
dOut.writeUTF("This is a test");
dOut.flush();
System.out.println("Work");
}
public void Check(){
}
}
`
 
Looking to above code and exception trace 2 things can be wrong.
check your code for
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.io.DataInputStream.readLine()' on a null object reference at
In xml layout file, have you declared "check" method on android:onClick
i.e. android:onClick="check", if yes then your check method should look like this
public void Check(View view){
}
Can you share you xml layout file as well.
yea my xml code is '
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"
tools:context=".MainActivity">
<TextView
android:id="#+id/Welcome"
android:layout_width="198dp"
android:layout_height="52dp"
android:layout_marginStart="104dp"
android:layout_marginTop="68dp"
android:text="Welcome"
android:textAlignment="center"
android:textAllCaps="false"
android:textColor="#color/colorPrimaryDark"
android:textSize="36sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<android.support.design.widget.TextInputLayout
android:id="#+id/passwordWrapper"
android:layout_width="387dp"
android:layout_height="56dp"
android:layout_marginStart="8dp"
android:layout_marginTop="444dp"
android:hint="Password"
app:hintEnabled="true"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<EditText
android:id="#+id/Password"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="Password"
android:inputType="textPassword"
android:textSize="18sp"
tools:text="" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/emailWrapper"
android:layout_width="397dp"
android:layout_height="56dp"
android:layout_marginStart="8dp"
android:layout_marginTop="368dp"
android:hint="Email"
app:hintEnabled="true"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<EditText
android:id="#+id/Email"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="Email"
android:inputType="textWebEmailAddress"
android:textAlignment="textStart"
android:textSize="18sp"
tools:text=""/>
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/LoginButton"
android:layout_width="348dp"
android:layout_height="45dp"
android:layout_marginStart="28dp"
android:layout_marginTop="520dp"
android:text="LOGIN"
android:onClick="SendMessage"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
'
public void SendMessage(View view) throws IOException {
EditText emailText = (EditText) findViewById(R.id.Email);
String Username = emailText.getText().toString();
EditText passwordText = (EditText) findViewById(R.id.Password);
String Password = passwordText.getText().toString();
System.out.println("Your username is " + Username + "Your Password is " + Password);
SendCredentials();
}
public void SendCredentials() throws IOException {
new MyAsyncTask().execute();
}
public void Check() {
}
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
Activity activity;
IOException ioException;
MyAsyncTask() {
super();
}
#Override
protected Void doInBackground(Void... voids) {
StringBuilder sb = new StringBuilder();
try {
System.out.println("Work");
Socket socket = new Socket("192.168.0.114", 4321);
System.out.println("Work");
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
dOut.writeByte(1);
dOut.writeUTF("This is a test");
dOut.flush();
System.out.println("Work");
socket.close();
} catch (IOException e) {
this.ioException = e;
}
}
}

why does my app crash when I use the setText Mehod? [duplicate]

This question already has answers here:
android.content.res.Resources$NotFoundException: String resource ID #0x0
(8 answers)
Closed 5 years ago.
QUESTION:
Why is my app crashing whenever I try to use the setText() method to assign random Numbers as my Buttons' text?
My Goal is to set random numbers to the buttons and if the user clicks the button with the larger number, he/she is awarded a point.
I debugged the program and found the logic to be working correctly. However the app keeps crashing at startup and I don't know what exactly is the underlying problem.
MAIN ACTIVITY:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private static int points, rand1, rand2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
points =0;
randomize();
}
public void onLeftClick(View view) {
if(rand1 > rand2)
points++;
else
points--;
TextView text = (TextView) findViewById(R.id.pointText);
text.setText("Points : "+points);
randomize();
}
public void onRightClick(View view) {
if(rand2 > rand1)
points++;
else
points--;
TextView text = (TextView) findViewById(R.id.pointText);
text.setText("Points : "+points);
randomize();
}
private void randomize() {
Random random = new Random();
rand1= random.nextInt(10);
rand2 = 0;
while (true) {
rand2 = random.nextInt(10);
if (rand1 != rand2)
break;
}
Button leftButton = (Button)findViewById(R.id.leftButton);
leftButton.setText((char)rand1); **ERROR HERE**
Button rightButton = (Button)findViewById(R.id.rightButton);
rightButton.setText((char)rand2);
}
}
XML FILE:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
tools:context="com.example.clickgame.MainActivity">
<TextView
android:layout_width="119dp"
android:layout_height="24dp"
android:text="CLICK GAME"
android:textAlignment="center"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.032"
tools:layout_constraintRight_creator="1"
tools:layout_constraintLeft_creator="1" />
<Button
android:id="#+id/leftButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="215dp"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="216dp"
android:onClick="onLeftClick"
android:text="0"
app:layout_constraintBottom_toTopOf="#+id/pointText"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_constraintBottom_creator="1"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintTop_creator="1" />
<Button
android:id="#+id/rightButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="215dp"
android:layout_marginEnd="18dp"
android:layout_marginRight="18dp"
android:layout_marginTop="216dp"
android:onClick="onRightClick"
android:text="0"
app:layout_constraintBottom_toTopOf="#+id/pointText"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_constraintBottom_creator="1"
tools:layout_constraintRight_creator="1"
tools:layout_constraintTop_creator="1" />
<TextView
android:id="#+id/pointText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="POINTS : 0"
android:textStyle="bold"
tools:layout_constraintRight_creator="1"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
tools:layout_constraintLeft_creator="1"
android:layout_marginBottom="16dp"
app:layout_constraintLeft_toLeftOf="parent" />
</android.support.constraint.ConstraintLayout>
ERROR LOG:
09-10 14:51:53.742 478-478/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.clickgame, PID: 478
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.clickgame/com.example.clickgame.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0x6
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x6
at android.content.res.Resources.getText(Resources.java:335)
at android.widget.TextView.setText(TextView.java:4555)
at com.example.clickgame.MainActivity.randomize(MainActivity.java:66) //THIS LINE
at com.example.clickgame.MainActivity.onCreate(MainActivity.java:22) //THIS LINE
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
To add to the answer of Amirhossein Naghshzan what is happening here is that the setText method of TextView is capable of using a resourceId as a parameter. When you pass in and integer to this method it tries to find a string resource with that id. If it can't find one an exception is thrown hence the need to wrap a single number value with String.valueOf()
Use String.valueof() to cast int to string:
leftButton.setText(String.valueof(rand1));
rightButton.setText(String.valueof(rand2));
Use String.valueof(), in the brackets of .settext()
Sample:
TextView text = (TextView) findViewById(R.id.pointText);
text.setText("Points : "+ String.valueof(points));
If you glance on this java documentation, then you could see that String.valueOf() returns:
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
So there shouldn't really be a difference except for an additional method invocation.
Also, in case of Object#toString, if the instance is null, a NullPointerException will be thrown, so, arguably, it's less safe.
i have cleaned your activity, use this one instead :
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private int
points = 0,
rand1,
rand2;
private TextView text;
private Button leftButton, rightButton;
private Random random = new Random();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.pointText);
leftButton = (Button)findViewById(R.id.leftButton);
leftButton.setOnClickListener(this);
rightButton = (Button)findViewById(R.id.rightButton);
rightButton.setOnClickListener(this);
randomize();
}
private void randomize() {
rand1 = random.nextInt(10);
rand2 = 0;
while (true) {
rand2 = random.nextInt(10);
if (rand1 != rand2)
break;
}
leftButton.setText(String.valueOf(rand1));
rightButton.setText(String.valueOf(rand2));
}
#Override
public void onClick(View v){
switch(v.getId()){
case R.id.leftButton{
if(rand1 > rand2)
points++;
else
points--;
text.setText("Points : " + String.valueOf(points));
randomize();
}break;
case R.id.rightButton:{
if(rand2 > rand1)
points++;
else
points--;
text.setText("Points : " + String.valueOf(points));
randomize();
}break;
}
}
}
Your Error is:
Resources$NotFoundException: String resource ID
you have to set the ID on your View item:
<TextView
android:id="#+id/pointText"

Why is Android closing the application without showing the "<application> has stopped unexpectedly" message?

I am in the process of learning Android development and was trying to crash my application at runtime. I made a button that calls a method when clicked and then made sure that the method does not exist.
The application starts up fine. As soon as i click the button, the application closes just as intended. The only unexpected thing was that my device did not show any error message like application has closed unexpectedly or that the application force closed.
Did I accidentally turn off some setting in the Developer Options or is it just my device that doesn't like showing error messages ? Any more information needed ?
activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.example.android.justjava.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Quantity"
android:textAllCaps="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/quantity_text_view"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:textColor="#000000"
android:text="0"
android:textSize="16sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Price"
android:textAllCaps="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/price_text_view"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:textColor="#000000"
android:text="$0"
android:textSize="16sp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAllCaps="true"
android:text="ORDER"
android:onClick="submitOrder"/>
</LinearLayout>
MainActivity.java:
package com.example.android.justjava;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import java.text.NumberFormat;
/**
* This app displays an order form to order coffee.
*/
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* This method is called when the order button is clicked.
*/
public void submitOrders(View view) {
int quantity = 5 ;
display(quantity) ;
displayPrice(quantity * 50) ;
}
/**
* This method displays the given quantity value on the screen.
*/
private void display(int number) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText("" + number);
}
private void displayPrice(int number) {
TextView priceTextView = (TextView) findViewById(R.id.price_text_view);
priceTextView.setText(NumberFormat.getCurrencyInstance().format(number));
}
}
Logcat:
01-20 16:08:54.087 28870-28893/? I/OpenGLRenderer: Initialized EGL,
version 1.4 01-20 16:08:54.087 28870-28893/? D/OpenGLRenderer: Swap
behavior 1 01-20 16:08:58.044 28870-28870/com.example.android.justjava
V/BoostFramework: BoostFramework() : mPerf =
com.qualcomm.qti.Performance#b82000f 01-20 16:08:58.119
28870-28870/com.example.android.justjava D/AndroidRuntime: Shutting
down VM 01-20 16:08:58.120 28870-28870/com.example.android.justjava
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.justjava, PID: 28870
java.lang.IllegalStateException: Could not find method
submitOrder(View) in a parent or ancestor Context for android:onClick
attribute defined on view class
android.support.v7.widget.AppCompatButton
at
android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
at
android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:5642)
at android.view.View$PerformClick.run(View.java:22338)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6209)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 01-20
16:08:58.120 28870-28870/com.example.android.justjava D/AppTracker:
App Event: crash 01-20 16:08:58.132 28870-28870/? I/Process: Sending
signal. PID: 28870 SIG: 9
It's based on this Udacity course.
In your XML button, its submitOrder not submitOrders. See the extra S :
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAllCaps="true"
android:text="ORDER"
android:onClick="submitOrder"/>
So, change this:
public void submitOrders(View view) {
With this:
public void submitOrder(View view) {
Remove s from method name submitOrders
public void submitOrder(View view) {
int quantity = 5 ;
display(quantity) ;
displayPrice(quantity * 50) ;
}
Or You can remove android:onClick="submitOrder"
<Button
android:id="#+id/order"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAllCaps="true"
android:text="ORDER"/>
than in your java file
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button order = (Button)findViewById(R.id.order);
order.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int quantity = 5 ;
display(quantity) ;
displayPrice(quantity * 50) ;
}
});
}

Unable to start activity, virtual method? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Here's MediaPlayer1.class
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MediaPlayer1 extends AppCompatActivity {
MediaPlayer mpAudio;
Boolean play;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_player);
play = false;
mpAudio = MediaPlayer.create(this, R.raw.youngagain);
mpAudio.setLooping(true);
Button bPlay = (Button) findViewById(R.id.playBtn);
bPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (play == false)
mpAudio.start();
else
mpAudio.pause();
play = !play;
}
});
}
}
and the layout file activity_media_player.xml
<FrameLayout 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/base_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background_material_dark"
android:gravity="center_horizontal"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/zmountain"
android:scaleType="centerCrop"
android:foreground="#e1000000" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hardwell on Air"
android:textColor="#fafafa"
android:textSize="24sp"
android:textStyle="bold"
android:layout_marginTop="60dp"
android:layout_marginBottom="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Hardwell on Air"
android:textColor="#fafafa"
android:layout_marginBottom="20dp"
android:id="#+id/textView" />
<sas.unplug.SquareImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="#drawable/zghost" />
<com.wnafee.vector.MorphButton
android:id="#+id/playBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
android:background="#null"
app:vc_endDrawable="#drawable/ic_pause_to_play"
app:vc_foregroundTint="#color/colorAccent"
app:vc_startDrawable="#drawable/ic_play_to_pause" />
</LinearLayout>
</FrameLayout>
I am getting the following error on my activity above which I've called through my adapter, like this:
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final PodcastData item = items.get(position);
holder.ptitle.setText(item.getPTitle());
holder.plikes.setText(""+item.getPLikes());
//Converting image into a bitmap
Bitmap bitmap = item.getAlbum();
//usig the generate method
Palette palette = Palette.generate(bitmap, 16);
Palette.generateAsync(bitmap, 16, new Palette.PaletteAsyncListener() {
#Override
public void onGenerated(Palette palette) {
Palette.Swatch vibrant = palette.getVibrantSwatch();
if (vibrant != null) {
// If we have a vibrant color
// update the title TextView
holder.ptitle.setTextColor(vibrant.getTitleTextColor());
holder.ptitle.setBackgroundColor(vibrant.getRgb());
}
}
});
holder.album.setImageBitmap(item.getAlbum());
holder.bLike.setOnClickListener(new View.OnClickListener() {
int likes = item.getPLikes();
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Likes selected " + items.get(position).getPLikes(), Toast.LENGTH_SHORT).show();
if(item.liked) {
holder.bLike.setColorFilter(Color.argb(255, 255, 255, 255));
likes-=1;
}
else {
holder.bLike.setColorFilter(Color.argb(255, 255, 38, 38));
likes+=1;
}
item.liked = !item.liked;
items.get(position).setPlikes(likes);
item.setPlikes(likes);
holder.plikes.setText("" + item.getPLikes());
ParseQuery<ParseObject> query = ParseQuery.getQuery("Podcast");
query.whereEqualTo("name", item.getPTitle());
query.getInBackground(item.objectId, new GetCallback<ParseObject>() {
#Override
public void done(ParseObject object, ParseException e) {
if (e == null) {
object.put("likes", likes);
object.saveInBackground();
}
}
});
}
});
holder.album.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, MediaPlayer1.class); // Start MediaPlayer1 activity here
context.startActivity(intent);
}
});
}
activity is started in the last function - holder.album.setOnClickListener()
FATAL EXCEPTION: main
Process: sas.unplug, PID: 1715
java.lang.RuntimeException: Unable to start activity ComponentInfo{sas.unplug/sas.unplug.MediaPlayer1}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.setLooping(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.setLooping(boolean)' on a null object reference
at sas.unplug.MediaPlayer1.onCreate(MediaPlayer1.java:21)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I am running the same exact code individually as a seperate project and the player works fine there but as soon as I start this activity in my main project my app crashes. Please help me I am in need of help desperately as I have my minor project submission tomorrow.
mpAudio = MediaPlayer.create(this, R.raw.youngagain)
MediaPlayer.create() return a MediaPlayer object, or null if creation failed.
MediaPlayer.create() failed and mpAudio = null .
So when you mpAudio.setLoop, you get nullpointer error.

Application Unfortunately stopped when going from 2nd activity to 3rd activity

I'm new to Android developing. This is an assignment which was given to me. I have to convert the value and the converted value must be shown in the next activity. But when I press the submit button its crashes.I don;t know what is the problem. Is there a problem with my RadioButtons. Please help me...
This is the second activity(ConvertActivity)
package com.gihan.temperatureconverter;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
public class ConvertActivity extends ActionBarActivity {
//RadioButton cel=(RadioButton) findViewById(R.id.rCel);
//RadioButton fah=(RadioButton) findViewById(R.id.rFah);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_convert);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_convert, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void calculation(View view) {
EditText val=(EditText) findViewById(R.id.editText);
int value = Integer.valueOf(val.getText().toString()).intValue();
int ans=0;
int fahval=0;
int celval=0;
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId()) {
case R.id.rCel:
if (checked){
ans=((value-32)*5/9);
fahval=value;
celval=ans;}
break;
case R.id.rFah:
if (checked){
ans=((value*9)/5)+32;
celval=value;
fahval=ans;}
break;
}
/*if (cel.isChecked()){
ans=((value-32)*5/9);
fahval=value;
celval=ans;
}
if (fah.isChecked()){
ans=((value*9)/5)+32;
celval=value;
fahval=ans;
}*/
Intent intent = new Intent(ConvertActivity.this, LastActivity.class);
intent.putExtra("celval", getText(celval));
intent.putExtra("fahval", getText(fahval));
ConvertActivity.this.startActivity(intent);
}
}
This is the 2nd XML(activity_convert)
<RelativeLayout 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.gihan.temperatureconverter.ConvertActivity"
android:background="#drawable/ic_background">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/editText"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="50dp"
android:hint="Enter Value"
android:textSize="20dp"/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/radioGroup"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true">
<RadioButton
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="To Celsius"
android:id="#+id/rCel"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:checked="false"
android:gravity="fill_horizontal"
android:textColor="#ffc80301"
android:textSize="25sp"/>
<RadioButton
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="To Fahrenheit"
android:id="#+id/rFah"
android:checked="false"
android:gravity="fill_horizontal"
android:textColor="#ffc80301"
android:textSize="25sp"
android:layout_below="#+id/rCel"
android:layout_alignLeft="#+id/rCel"
android:layout_alignStart="#+id/rCel" />
</RadioGroup>
<Button
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Submit"
android:id="#+id/sub"
android:onClick="calculation"
android:layout_below="#+id/radioGroup"
android:layout_centerHorizontal="true"
android:layout_marginTop="80dp" />
</RelativeLayout>
This is the 3rd activity(LastActivity)
package com.gihan.temperatureconverter;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class LastActivity extends ActionBarActivity {
TextView vFah=(TextView)findViewById(R.id.vFah);
TextView vCel=(TextView)findViewById(R.id.vCel);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_last);//use whatever layout you want.
Bundle extras = getIntent().getExtras();
int celval=extras.getInt("celval");
int fahval=extras.getInt("fahval");
//String cel=String.valueOf(celval);
//String fah=String.valueOf(fahval);
vCel.setText(Integer.toString(celval));
vFah.setText(Integer.toString(fahval));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_convert, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void again(View view) {
Intent intent = new Intent(LastActivity.this, ConvertActivity.class);
LastActivity.this.startActivity(intent);
}
public void home(View view) {
Intent intent = new Intent(LastActivity.this, MainActivity.class);
LastActivity.this.startActivity(intent);
}
}
This is the 3rd XML(activity_last)
<RelativeLayout 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:background="#drawable/ic_background"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.gihan.temperatureconverter.LastActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Successfully Converted"
android:id="#+id/textView2"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:textColor="#ffff0004"
android:textSize="30sp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Home"
android:id="#+id/button2"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="70dp"
android:gravity="center_horizontal"
android:textSize="25sp"
android:onClick="home"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Calculate again"
android:id="#+id/button3"
android:layout_marginBottom="45dp"
android:gravity="center_horizontal"
android:layout_above="#+id/button2"
android:layout_centerHorizontal="true"
android:textSize="25sp"
android:onClick="again"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Fahrenheit"
android:id="#+id/textView3"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:textColor="#ff0010ff" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Celsius"
android:id="#+id/textView4"
android:layout_below="#+id/textView3"
android:layout_centerHorizontal="true"
android:layout_marginTop="52dp"
android:textColor="#ff0010ff" />
<TextView
android:layout_width="wrap_content"
android:layout_height="20sp"
android:id="#+id/vFah"
android:layout_below="#+id/textView3"
android:layout_centerHorizontal="true"
android:textColor="#ff9300ff"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="20sp"
android:id="#+id/vCel"
android:layout_below="#+id/textView4"
android:layout_centerHorizontal="true"
android:textColor="#ff9300ff"/>
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.gihan.temperatureconverter" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ConvertActivity"
android:label="#string/app_name">
</activity>
<activity
android:name=".LastActivity"
android:label="#string/app_name">
</activity>
</application>
</manifest>
Logcat
--------- beginning of crash
06-09 21:05:58.413 2381-2381/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.gihan.temperatureconverter, PID: 2381
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4020)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4015)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.ClassCastException: android.support.v7.widget.AppCompatButton cannot be cast to android.widget.RadioButton
at com.gihan.temperatureconverter.ConvertActivity.calculation(ConvertActivity.java:56)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4015)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Some Comments were some ways I tried. It's also failed.
And also this is Android Studio Project.
Your Error Solved Check this code
mainactivity.java
public class MainActivity extends ActionBarActivity {
EditText val;
public static int ans;
public static String fahval="";
public static String celval="";
RadioButton Box1,Box2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
val =(EditText) findViewById(R.id.editText);
}
public void calculation(View v)
{
//get value from edit text box and convert into double
double a=Double.parseDouble(String.valueOf(val.getText()));
Box1 = (RadioButton) findViewById(R.id.rCel);
Box2 = (RadioButton) findViewById(R.id.rFah);
//check which radio button is checked
if(Box1.isChecked())
{
//display conversion
celval = String.valueOf(f2c(a));
// Toast.makeText(getApplicationContext(), celval,Toast.LENGTH_LONG).show();
Box1.setChecked(true);
}
else
{
fahval = String.valueOf(c2f(a));
// Toast.makeText(getApplicationContext(), fahval,Toast.LENGTH_LONG).show();
Box2.setChecked(true);
}
Intent intent = new Intent(this, LastActivity.class);
intent.putExtra("celval", celval);
intent.putExtra("fahval", fahval);
startActivity(intent);
}
//Celcius to Fahrenhiet method
private double c2f(double c)
{
return (c*9)/5+32;
}
//Fahrenhiet to Celcius method
private double f2c(double f)
{
return (f-32)*5/9;
}
}
LastActivity.java
public class LastActivity extends ActionBarActivity {
TextView vFah;
TextView vCel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.last);//use whatever layout you want.
vFah=(TextView)findViewById(R.id.vFah);
vCel=(TextView)findViewById(R.id.vCel);
Bundle extras = getIntent().getExtras();
String celval=extras.getString("celval");
String fahval=extras.getString("fahval");
//String cel=String.valueOf(celval);
//String fah=String.valueOf(fahval);
vCel.setText(celval);
vFah.setText(fahval);
}
public void again(View view) {
Intent intent = new Intent(LastActivity.this, MainActivity.class);
LastActivity.this.startActivity(intent);
}
public void home(View view) {
Intent intent = new Intent(LastActivity.this, MainActivity.class);
LastActivity.this.startActivity(intent);
}
}
I was building some apps this week, and couldn't figure out why I couldn't navigate from the Main Activity to a second activity and from there to a 3rd level activity (that would pop to 2nd activity), and app kept crashing when I added the 3rd. Finally looked in the Logcat to figure out what's wrong, and then read "Cannot Navigate from 'second activity'.... This View will not accept Navigation". Searched through code to find errors, but Never thought to look there before.

Categories

Resources