java.lang.IllegalStateException: Could not find method - java

I think that is a dumb error, and I am new to programming. I was making an app to learn: there are 2 radio buttons to choose what text show in an hidden TextView, 2 check box to choose the background and text color of the TextView and a button, that do a check of the check box and the radio buttons and print the text in the TextView. But when in the emulator I try to click something, the app crashes, and the logcat says that it can't find the id and the onClick. Why do I get this?
The program:
package com.bauapp.lory.bauapp;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.TextView;
import android.graphics.Color;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton)
findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action",Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#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_main, 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 cambiaTesto (View v) {
TextView baubau = (TextView) findViewById(R.id.bauText);
RadioButton bau1 = (RadioButton) findViewById(R.id.bauRadio1);
RadioButton bau2 = (RadioButton) findViewById(R.id.bauRadio2);
CheckBox testoRosso = (CheckBox)findViewById(R.id.c1);
CheckBox sfondoGiallo = (CheckBox)findViewById(R.id.c2);
if(bau1.isChecked()) {
baubau.setText("BAU");
}
else
if (bau2.isChecked()) {
baubau.setText("BAUUUUUUU");
}
if(testoRosso.isChecked())
baubau.setTextColor(Color.RED);
else
baubau.setTextColor(Color.BLACK);
if (sfondoGiallo.isChecked())
baubau.setBackgroundColor(Color.YELLOW);
else
baubau.setBackgroundColor(Color.WHITE);
}
}
The XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android: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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.bauapp.lory.bauapp.MainActivity"
tools:showIn="#layout/activity_main">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="43dp">
<TextView
android:layout_width="342dp"
android:layout_height="191dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/bauText"
android:layout_gravity="center_horizontal|bottom"
android:onClick="baubau" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Testo rosso"
android:id="#+id/c1"
android:layout_gravity="left|center_vertical"
android:onClick="testoRosso"
android:checked="false"
android:clickable="true" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sfondo giallo"
android:id="#+id/c2"
android:layout_gravity="right|center_vertical"
android:onClick="sfondoGiallo"
android:clickable="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BAU BAU?"
android:id="#+id/bauButton"
android:layout_gravity="right|top"
android:onClick="cambiaTesto" />
<RadioGroup
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="left|top">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BAU"
android:id="#+id/bauRadio1"
android:layout_gravity="left|top"
android:onClick="bau1"
android:checked="false"
android:clickable="true" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BAUUUUUUU"
android:id="#+id/bauRadio2"
android:layout_gravity="left|top"
android:onClick="bau2"
android:checked="false"
android:clickable="true" />
</RadioGroup>
</FrameLayout>
And the logcat:
http://textuploader.com/5blrn
(I leave an external link because it doesn't paste correctly for a bug in stackoverflow).
The crash logcat is the same for all the other buttons, but, obviously, change the ID and the OnClick.
Sorry for my bad English.

My suggestion would be to remove android:onClick=... from your RadioButtons, and instead use onCheckedChangeListener on the RadioGroup and then determine which RadioButton was checked and then do whatever you need to do. Your code changes are then as follows:
<RadioGroup
android:id="#+id/bauRadioGroup"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="left|top">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BAU"
android:id="#+id/bauRadio1"
android:layout_gravity="left|top"
android:checked="false"
android:clickable="true" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BAUUUUUUU"
android:id="#+id/bauRadio2"
android:layout_gravity="left|top"
android:checked="false"
android:clickable="true" />
</RadioGroup>
Then in your MainActivity onCreate you add this code:
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.bauRadioGroup);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId == R.id.bauRadio1){
//radio button bauRadio1 was clicked
baubau.setText("BAU");
}
else if(checkedId == R.id.bauRadio2 ){
//radio button bauRadio2 was clicked
baubau.setText("BAUUUUUUU");
}
}
});
//The rest of your code ...
Please give this a try and let us know if this helps.
As already suggested, How to set On click listener on the Radio Button in Android is a good example for this.

The Radio Button needs a method to handle its onClick event.
You have given the onClick method as android:onClick="bau1" for android:id="#+id/bauRadio1", but the MainActivity class needs to implement the bau1 method.
Hence the IllegalStateException of cannot find method bau1.
Check this link for more details on RadioButton and Responding to Click Events:
https://developer.android.com/guide/topics/ui/controls/radiobutton.html

Ciao Lorenzo,
I noticed at the end of your XML file: you forgot to close the RelativeLayout with the proper closetag </RelativeLayout> .
It's only a copy-paste mystake or your xml file is incorrect?
I give you a tip. Avoid filling the xml file with too many layout when with a few changes you can get the same view with fewer elements.
In your example the FrameLayout is completely useless.
EDIT: In your layout i didn't see the <FloatingActionButton> .
Make sure to add the support library dependence in your build.grandle file:
Remember to change the version based on your api target *
compile 'com.android.support:design:23.2.1'
After that you can add the FAB in you layout like this:
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:layout_margin="16dp"
android:src="#drawable/my_icon" />

Either create
public void bau1(View view){
//Perform some code
}
In your MainActivity
OR
Remove android:onClick="bau1" from XML
Specially I prefer using OnCheckedChangeListener instead of onClick in case of RadioGroup like shown here.

Related

Method showAtLocation cannot be resolved

I am attempting to create a popup menu that comes from a button at the bottom right corner of the screen. The issue is that the menu would need to be displayed above the button. Ive botched together some code from Android. How to show popup window directly above button. However, the showAtLocation method does not resolve. Another issue that I believe is related to this is that the activity crashes ever since I added my onMenuItemClick() switch statements. Any help would be greatly appreciated :) and more code can be found at my Github
--edit---
So it turns out that showAtLocation only works for popup windows, however I am using a popup menu. So the question becomes, ho wdo you make a popup display above a button rather than below?
WorkoutsCreater.java:
package com.example.workoutapp;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.Toast;
public class WorkoutsCreater extends AppCompatActivity implements PopupMenu.OnMenuItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_workouts_creater);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Workout Creater"); //change text at top of screen accordingly
Button btn=findViewById(R.id.BtnNew);
btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
PopupMenu popup = new PopupMenu(WorkoutsCreater.this, v); //display menu when button clicked
popup.setOnMenuItemClickListener(WorkoutsCreater.this);
popup.inflate(R.menu.workout_new_popup_menu);
popup.showAtLocation(v, Gravity.TOP, 0, (int) v.getY()); //show popup above button
}
});
}
#Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(this, "Selected Item: " +item.getTitle(), Toast.LENGTH_SHORT).show();
switch (item.getItemId()) { //testing which button is pressed in menu
case R.id.RepBased:
System.out.println("Rep Based");
return true;
case R.id.RunBased:
System.out.println("Run Based");
return true;
case R.id.TimeBased:
System.out.println("Time Based");
return true;
default:
return false;
}
}
}
workout_new_popup_menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/RepBased"
android:icon="#drawable/ic_workouts"
android:title="Rep Based" />
<item android:id="#+id/RunBased"
android:icon="#drawable/ic_run_black"
android:title="Run Based" />
<item android:id="#+id/TimeBased"
android:icon="#drawable/ic_time_based"
android:title="Time Based" />
</menu>
activity_workouts_creater.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/ConstraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".WorkoutsCreater">
<TextView
android:id="#+id/NameWorkoutTextView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="20dp"
android:layout_marginLeft="20dp"
android:gravity="center"
android:text="Name of Workout:"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textSize="15dp"
app:layout_constraintBottom_toBottomOf="#+id/NameWorkoutInput"
app:layout_constraintEnd_toStartOf="#+id/NameWorkoutInput"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/NameWorkoutInput" />
<EditText
android:id="#+id/NameWorkoutInput"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginEnd="40dp"
android:layout_marginRight="40dp"
android:inputType="text"
android:maxLength="20"
android:textSize="15dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/NameWorkoutTextView"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/BtnNew"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:clickable="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:srcCompat="#drawable/ic_add_white" />
</androidx.constraintlayout.widget.ConstraintLayout>
showAtLocation() is a PopupWindow method, not a PopupMenu method.
The code you copied uses it on PopupWindow as well.
You can read more about PopupWindow here and about the specific method here
v.setOnTouchListener(popup.getDragToOpenListener()); fixes the popup issue and the crashing was caused by using the wrong button type. Turns out you cannot use floating action buttons with popup menus

textview showing correct in design and incorrect in emulator

Hi I am new in andriod and this is my first app but i got problem when I am trying to add textview it is appearing correct in andriod design but incorrect in emulator and there is no error in program.so help me fix this
Here is the screenshot of my problem``
I tried to change the api and theme but it didn't work
code MainActivity.java
package amitkumar.helloworld;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#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_main, 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);
}
}
content_main.xml
<?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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="amitkumar.helloworld.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:id="#+id/textView2"
android:layout_width="377dp"
android:layout_height="70dp"
android:layout_marginBottom="380dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="1dp"
android:text="Hello World!"
android:textAlignment="center"
android:textAppearance="#style/TextAppearance.AppCompat.Display2"
android:textColor="#android:color/holo_red_dark"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.444"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
app:layout_constraintVertical_bias="1.0" />
<TextView
android:id="#+id/textView"
android:layout_width="379dp"
android:layout_height="60dp"
android:layout_marginBottom="287dp"
android:layout_marginEnd="2dp"
android:layout_marginStart="3dp"
android:layout_marginTop="164dp"
android:lineSpacingExtra="10sp"
android:text="#string/textview"
android:textAlignment="center"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#color/colorPrimary"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.888"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
tools:text="This is My First Project"
android:layout_marginRight="2dp"
android:layout_marginLeft="3dp" />
</android.support.constraint.ConstraintLayout>
Set your TextView text like this android:text="This is My First Project" instead of this android:text="#string/textview and delete line tools:text="This is My First Project"
For showing your XML content at run time use android: namespace.
android:text="Will be shown at runtime"
By using tools: namespace you will only be able to see content in android studio's preview.
tools:text="Just to show in preview"
tools:text="toolsText" is used for Android Studio layout preview
android:text="androidText" is used to set text to a a layout element

application is crashing when pressing button [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
number format exception
(2 answers)
Closed 6 years ago.
Hello everyone i'm new here so this is my first post
I want to build my first android app and that would be a GPA calculator to be exact but every time I press the calculate button the app crashes I use android studio and here is the java code
package com.example.mac.gpacalculator;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
TextView result;
EditText grade1;
EditText grade2;
EditText grade3;
EditText grade4;
EditText grade5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
result=(TextView) findViewById(R.id.total);
grade1=(EditText)findViewById(R.id.num1);
grade2=(EditText)findViewById(R.id.num2);
grade3=(EditText)findViewById(R.id.num3);
grade4=(EditText)findViewById(R.id.num4);
grade5=(EditText)findViewById(R.id.num5);
final Button calcbtn= (Button) findViewById(R.id.calc);
calcbtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
double c1 = Float.parseFloat(grade1.getText().toString());
c1=convert(String.valueOf(grade1));
double c2 = Float.parseFloat(grade2.getText().toString());
c1=convert(String.valueOf(grade2));
double c3 = Float.parseFloat(grade3.getText().toString());
c1=convert(String.valueOf(grade3));
double c4 = Float.parseFloat(grade4.getText().toString());
c1=convert(String.valueOf(grade4));
double c5 = Float.parseFloat(grade5.getText().toString());
c1=convert(String.valueOf(grade5));
double c6=calculation(c1,c2,c3,c4,c5);
result.setText((int) c6);
}
});
}
#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_main, menu);
return true;
}
public static double convert(String grade)
{
double a=0.0;
//checking the conditions
if(grade.equalsIgnoreCase("A"))
{
a=4.0;
}
if(grade.equalsIgnoreCase("A-"))
{
a=3.7;
}
if(grade.equalsIgnoreCase("B+"))
{
a=3.3;
}
else if(grade.equalsIgnoreCase("B"))
{
a=3.0;
}
if(grade.equalsIgnoreCase("B-"))
{
a=2.7;
}
if(grade.equalsIgnoreCase("C+"))
{
a=2.3;
}
else if(grade.equalsIgnoreCase("C"))
{
a=2.0;
}
if(grade.equalsIgnoreCase("C-"))
{
a=1.7;
}
if(grade.equalsIgnoreCase("D+"))
{
a=1.3;
}
else if(grade.equalsIgnoreCase("D"))
{
a=1.0;
}
else if(grade.equalsIgnoreCase("F"))
{
a=0.0;
}
return a;
}
public static double calculation(double c1, double c2, double c3, double c4, double c5)
{
double operation;
operation=(c1+c2+c3+c4+c5)/5;//calculating the GPA
return operation;
}
#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);
}
}
and here is the XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/content_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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.mac.gpacalculator.MainActivity"
tools:showIn="#layout/activity_main">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/num4"
android:layout_below="#+id/num3"
android:layout_alignStart="#+id/num3"
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-"
android:textAlignment="center"
android:hint="Grade"
android:inputType="text" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/num5"
android:layout_below="#+id/num4"
android:layout_alignStart="#+id/num4"
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-"
android:textAlignment="center"
android:hint="Grade"
android:inputType="text" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/num2"
android:layout_below="#+id/num1"
android:layout_alignStart="#+id/num1"
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-"
android:textAlignment="center"
android:hint="Grade"
android:inputType="text" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/num3"
android:inputType="text"
android:textAlignment="center"
android:hint="Grade"
android:layout_below="#+id/num2"
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-"
android:layout_alignStart="#+id/num2" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/num1"
android:hint="Grade"
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-"
android:textAlignment="center"
android:layout_marginTop="49dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:inputType="text" />
<Button
android:text="CALCULATE"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/calc"
android:layout_marginTop="24dp"
android:layout_below="#+id/num5"
android:layout_centerHorizontal="true"
android:onClick="calculation"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:id="#+id/total"
android:hint="0"
android:layout_below="#+id/calc"
android:layout_centerHorizontal="true"
android:textSize="50sp" />
</RelativeLayout>
Also where can i learn more about android development can you recommend me some resources like books, websites, etc. that would me much appreciated.
Thanks in advance.
oh sorry I didn't include the error message
FATAL EXCEPTION: main
Process: com.example.mac.gpacalculator, PID: 2327
java.lang.NumberFormatException: empty String
at java.lang.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1071)
at java.lang.Float.parseFloat(Float.java:459)
at com.example.mac.gpacalculator.MainActivity$2.onClick(MainActivity.java:51)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
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: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)
Application terminated.
You have to have Button btn = (Button) findViewById(R.id.button); otherwise you will throw a NullPointerException. Check the android monitor to see if that matches the error there.
You have added android:onClick="calculation" in your XML <Button>tag so define a method called calculation which accepts view in your code ..
or simply use calcbtn.setOnClickListener... in your code and remove android:onClick="calculation" from the button tag
Don't use Both android:onClick="calculation and view.setOnClick.. for a same View..
There is no id called fab in your XML so add a FloatingActionButton and give that id to it or comment FloatingActionButton fab ....});
I see multiple error here:
As answered by #charuka, you have added a method in your button android:onClick="calculation, which couldn't be found by android and causes crash.
you are trying to parse EditText into String, which is not String, here: convert(String.valueOf(grade1));, change it to convert(grade1.getText().toString());

How to validate string as user input (from keyboard) and display "correct answer" using toast?

I'm developing a simple game where a question will be asked in a "Plain TextView" and user needs to provide the answer using the keyboard in a "EditText" and press on the check "button" after typing...then a "correct answer" should be displayed on a toast screen if the answer is correct or an "incorrect answer" for wrong answer. I'm a beginner so a detailed answer would be really helpful..thank you.
Here's my Main Activity.Java:
package com.example.laxmanaryal.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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_main, 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);
}
}
And here's activity_main.xml:
<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=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="What has 88 keys but cannot open a single door?"
android:id="#+id/textView1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="40dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText1"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:width="255dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="71dp" />
First of all you have to declare your Button and EditText on your MainActivity, do as follows.
Button button;
EditText edittext;
Then inside on your onCreate() you have to get the view from your EditText and your Button so you have to do it as follows :
button = (Button)findViewById(R.id.button); //R.id.button is the id on your xml
edittext = (EditText)findViewById(R.id.editText1); //this is the EditText id
Oh wait, I've read the question again and I forgot something, just add on your xml this:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="What's 2x2?" <!-- This is the question-->
android:layout_gravity="center" />
Then the next step is set an onClickListener() on your Button so you can get the event when user clicks on it. You can do it as follows :
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
//Here you must get the text on your EditText
String Answer = (String) edittext.getText().toString(); //here you have the text typed by the user
//You can make an if statement to check if it's correct or not
if(Answer=="4"){
//Create a Toast because it's correct
Toast.makeText(MainACtivity.this, "Correct!",
Toast.LENGTH_LONG).show();
}
else{
//It's not the correct answer
Toast.makeText(MainACtivity.this, "FAAAAAAAAIL!",
Toast.LENGTH_LONG).show();
}
}
});
That's just an example of you could do it, if you want to improve it, just do it by yourself.
As StackOverflow says
Questions asking for homework help must include a summary of the work you've done so far to solve the problem, and a description of the difficulty you are having solving it.
You should Learn Android Basics to learn about Android.
Happy coding :)

java - Android app crashes when button is pressed

I am trying to get a part of a simple Android app working. I am confused as to why I am getting the error "Unfortunately, this app has stopped working".
Basically, I need the total value to increase when I click on a button based on what value they have. For example coffee adds 2 to the total. Every time I click a button that adds to the total value, the app crashes.
Here is the source code. I have just copied the parts that are specific to this problem.
package com.example.pp.application;
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.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements AdapterView.OnItemSelectedListener {
TextView tv01;
Double Total = 0.00;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv01 = (TextView) findViewById(R.id.tv01);
}
#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_main, 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 sendMessage(View view)
{
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
startActivity(intent);
}
public void addCoffee() {
Total = Total + 2.20;
tv01.setText(""+Total+"");
}
public void addBus() {
Total = Total + 1.90;
tv01.setText(""+Total+"");
}
public void addMilk() {
Total = Total + 1.50;
tv01.setText(""+Total+"");
}
}
And here is the Manifest:
<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=".MainActivity"
android:id="#+id/label">
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Coffee"
android:id="#+id/button"
android:onClick="addCoffee"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="42dp" />
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Bus"
android:onClick="addBus"
android:id="#+id/button3"
android:layout_below="#+id/button2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Milk"
android:onClick="addMilk"
android:id="#+id/button4"
android:layout_below="#+id/button3"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:onClick="sendMessage"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/button5" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="------------------"
android:id="#+id/tv01"
android:layout_alignRight="#+id/button"
android:layout_alignEnd="#+id/button" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Total"
android:id="#+id/textView"
android:layout_toStartOf="#+id/tv01"
android:layout_toLeftOf="#+id/tv01" />
Instead of public void addCoffee() your onClick method definition should look like public void addCoffee(View v), where v is the widget you clicked on (in this case the Button). Take the same approach when updating other onClick methods. This requirement applies only to callbacks defined via android:onClick attribute in XML layout.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv01 = (TextView) findViewById(R.id.tv01);
public void addCoffee(View v) {
Total = Total + 2.20;
tv01.setText(""+Total+"");
}
}
and continue with another function with same way
Since you haven't posted the stack trace of the LogCat, I have no way of telling when in the code your error has been.
But it's likely to have occured before. These links contain similar stances and documentations about exceptions.
My Android App Keeps Crashing
https://developers.google.com/analytics/devguides/collection/android/v4/exceptions
https://developer.android.com/distribute/essentials/optimizing-your-app.html
Android App Crashes on Button Click

Categories