Android Studio Printing EditText returns null - java

I've created a simple application where the user inputs their name and score which should be an integer only and then by clicking the button, it should print the data from those two EditText box's into the log. The issue is that I am getting Null for the Name and zero for the Score.
//Main
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.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
Button SaveDataButton;
EditText TextName, TextScore;
String Name;
int Score;
#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();
SaveDataButton = (Button) findViewById(R.id.button);
TextName = (EditText) findViewById(R.id.editText1);
TextScore = (EditText) findViewById(R.id.editText2);
Name = TextName.getText().toString();
Score = Integer.parseInt(TextScore.getText().toString());
}
});
}
public void SaveDataOnClick (View view){
System.out.println(Name);
System.out.println(Score);
}
#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);
}
}
//layout
<?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.example.capstoneproject.module08courseproject_datastorage.MainActivity"
tools:showIn="#layout/activity_main">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/textView3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="31dp"
android:weightSum="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Name"
android:id="#+id/textView" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText1"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Score"
android:id="#+id/textView2" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText2"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save Data"
android:id="#+id/button"
android:layout_gravity="center_horizontal"
android:onClick="SaveDataOnClick" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Name and Score Data Storage"
android:id="#+id/textView3"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
//output
11-29 22:07:01.846 3192-3192/? I/System.out: null
11-29 22:07:01.846 3192-3192/? I/System.out: 0

Editing because I missed the fact that you were getting your widgets in the anonymous onClickListener wired to your FloatingActionButton. Make these changes to fix it:
#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();
// remove all the widget stuff and move it outside
}
});
SaveDataButton = (Button) findViewById(R.id.button);
TextName = (EditText) findViewById(R.id.editText1);
TextScore = (EditText) findViewById(R.id.editText2);
//Name = TextName.getText().toString();
//Score = Integer.parseInt(TextScore.getText().toString());
}
The way you had it written is that the last 5 lines of code above are only executed if the floating action button (round button in the bottom right corner of a material design app) is clicked. I don't think this is your intended behavior. Instead, you want to get your widget references and keep them when onCreate() is called by the activity manager.
I commented out the last two lines because at this point the value in both edit texts is null. This is useless for the name and causes a number format exception for the score (you can't convert null to a number).
Finally, I think you wan to get the actual values when the user clicks your "SAVE DATA" button, so modify your SaveDataOnClick method. Remember, this method will be called each time the button is clicked/tapped, so it will get whatever the current value in the edit text fields are. Something like this:
public void SaveDataOnClick (View view){
Name = TextName.getText().toString();
Score = Integer.parseInt(TextScore.getText().toString());
System.out.println(Name);
System.out.println(Score);
}
I made these changes, and here is my log output:
11-29 22:44:22.696 20997-20997/? I/System.out: bobby
11-29 22:44:22.696 20997-20997/? I/System.out: 123

Related

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());

Method invocation may produce java NullpointerException in Button click listener [duplicate]

I create new Blank Activity project in Android Studio 1.5.1 with min API 15
and after generated code i have this warning/error:
on pasteBin
Code in MainActivity.java:
package com.gamecodeschool.myapplication;
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 MyActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
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.my_menu, 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);
}
}
Code in content_my.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.gamecodeschool.myapplication.MyActivity"
tools:showIn="#layout/my_layout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
Code in my_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
tools:context="com.gamecodeschool.myapplication.MyActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_my" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
Tell me please how to fix this problem and why it happens. I'm new in Android and Android Studio. Previously I used the Apache Cordova.
Just check/assert whether fab is null:
if (fab != null)
or:
assert fab != null;
Like this:
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
if (fab != null)
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();
}
});
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
In this line pass your onClicklistener instance as the second parameter to the setAction method.
Snackbars can contain an action which is set via
setAction(CharSequence, android.view.View.OnClickListener).
Change it like this
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", new View.OnClickListener() {
#Override
public void onClick(View v) {
//whatever you want to do when "Action" is clicked in the SnackBar
}
}).show();
This null pointer is coming due to Snackbar not because of your floating button. You need to create the object of click listener in set Action method instead of passing null.

java.lang.IllegalStateException: Could not find method

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.

Method invocation 'fab.setOnClickListener(new View.OnClickListener() { #Override public void on...' may produce 'java.lang.NullPointerException'

I create new Blank Activity project in Android Studio 1.5.1 with min API 15
and after generated code i have this warning/error:
on pasteBin
Code in MainActivity.java:
package com.gamecodeschool.myapplication;
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 MyActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
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.my_menu, 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);
}
}
Code in content_my.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.gamecodeschool.myapplication.MyActivity"
tools:showIn="#layout/my_layout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
Code in my_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
tools:context="com.gamecodeschool.myapplication.MyActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_my" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
Tell me please how to fix this problem and why it happens. I'm new in Android and Android Studio. Previously I used the Apache Cordova.
Just check/assert whether fab is null:
if (fab != null)
or:
assert fab != null;
Like this:
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
if (fab != null)
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();
}
});
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
In this line pass your onClicklistener instance as the second parameter to the setAction method.
Snackbars can contain an action which is set via
setAction(CharSequence, android.view.View.OnClickListener).
Change it like this
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", new View.OnClickListener() {
#Override
public void onClick(View v) {
//whatever you want to do when "Action" is clicked in the SnackBar
}
}).show();
This null pointer is coming due to Snackbar not because of your floating button. You need to create the object of click listener in set Action method instead of passing null.

Categories