Getting IllegalStateException on Button Click - caused by: java.lang.NullPointerException [duplicate] - android

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I tried to add data to sqlite, but when I clicked Add Button error appear and my app closed. I don't understand, so many wasted hours for looking the solution by myself..
here is my java code, AddSampleActivity.java
package com.example.mangan;
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.Toast;
public class AddSampleActivity extends AppCompatActivity {
DatabaseHelper myDb;
EditText editNama, editJarak, editRating , editHarga;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_sample);
editNama = (EditText) findViewById(R.id.nama);
editJarak = (EditText) findViewById(R.id.jarak);
editRating = (EditText) findViewById(R.id.rating);
editHarga = (EditText) findViewById(R.id.harga);
myDb = new DatabaseHelper(this);
}
public void addData(View view) {
boolean isInserted = myDb.insertData(editNama.getText().toString(),
editJarak.getText().toString(),
editRating.getText().toString(),
editHarga.getText().toString() );
if(isInserted)
Toast.makeText(AddSampleActivity.this,"Data Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(AddSampleActivity.this,"Data not Inserted",Toast.LENGTH_LONG).show();
}
}
my layout, activity_add_sample.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:padding="10dp"
tools:context="com.example.mangan.AddSampleActivity">
<EditText
android:id="#+id/jarak_editText"
android:hint="Jarak"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/rating_editText"
android:hint="Rating"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/harga_editText"
android:hint="Harga"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/add_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="addData"
android:text="Add"/>
</LinearLayout>
This is fullstack trace
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:5675)
at android.view.View$PerformClick.run(View.java:22651)
at android.os.Handler.handleCallback(Handler.java:836)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:208)
at android.app.ActivityThread.main(ActivityThread.java:6267)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
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:5675) 
at android.view.View$PerformClick.run(View.java:22651) 
at android.os.Handler.handleCallback(Handler.java:836) 
at android.os.Handler.dispatchMessage(Handler.java:103) 
at android.os.Looper.loop(Looper.java:208) 
at android.app.ActivityThread.main(ActivityThread.java:6267) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.mangan.AddSampleActivity.addData(AddSampleActivity.java:30)
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:5675) 
at android.view.View$PerformClick.run(View.java:22651) 
at android.os.Handler.handleCallback(Handler.java:836) 
at android.os.Handler.dispatchMessage(Handler.java:103) 
at android.os.Looper.loop(Looper.java:208) 
at android.app.ActivityThread.main(ActivityThread.java:6267) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924) 
It seem that some content on addData method is the problem. I read another question, Getting IllegalStateException on button click, but the problem is little bit different..

Your edittext ids aren't correct. change them like below
editJarak = (EditText) findViewById(R.id.jarak_editText);
editRating = (EditText) findViewById(R.id.rating_editText);
editHarga = (EditText) findViewById(R.id.harga_editText);

Your edit text ids are wrong. Try this,
editNama = (EditText) findViewById(R.id.nama_editText);
editJarak = (EditText) findViewById(R.id.jarak_editText);
editRating = (EditText) findViewById(R.id.rating_editText);
editHarga = (EditText) findViewById(R.id.harga_editText);

Related

Unable to start new activity involving Firebase

I am building an app that has a charity and restaurant. They register themselves and then proceed using Firebase for database handling. When I register charity register charity should open but it shows error. Logcat and register charity file attached.
activity register charity
package com.example.aayu.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
/**
* Created by AAYU on 30-May-17.
*/
public class regc extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reg_c);
final DatabaseReference rootref = FirebaseDatabase.getInstance()
.getReferenceFromUrl("https://myapplication-6e0b9.firebaseio.com/charity");
final EditText mname = (EditText) findViewById(R.id.cname);
final EditText madd = (EditText) findViewById(R.id.cadd);
final EditText mcity = (EditText) findViewById(R.id.ccity);
final EditText mstate = (EditText) findViewById(R.id.cstate);
final EditText mpin = (EditText) findViewById(R.id.cpin);
final Button mnext= (Button) findViewById(R.id.cnext);
mnext.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
String name = mname.getText().toString();
String add = madd.getText().toString();
String city = mcity.getText().toString();
String state = mstate.getText().toString();
String pin = mpin.getText().toString();
DatabaseReference childref = rootref.child("Charity Name");
childref.setValue(name);
childref = rootref.child("Address");
childref.setValue(add);
childref = rootref.child("City");
childref.setValue(city);
childref = rootref.child("State");
childref.setValue(state);
childref = rootref.child("Pincode");
childref.setValue(pin);
}
});
//setContentView(R.layout.reg2_c);
final EditText memail = (EditText) findViewById(R.id.cemail);
final EditText mph = (EditText) findViewById(R.id.cph);
final EditText muname = (EditText) findViewById(R.id.cuname);
final EditText mpwd = (EditText) findViewById(R.id.cpwd);
final Button mreg=(Button) findViewById(R.id.creg);
mreg.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
String email = memail.getText().toString();
String ph = mph.getText().toString();
String uname = muname.getText().toString();
String pwd = mpwd.getText().toString();
DatabaseReference childref = rootref.child("Email Id");
childref.setValue(email);
childref = rootref.child("Phone No");
childref.setValue(ph);
childref = rootref.child("Username");
childref.setValue(uname);
childref = rootref.child("Password");
childref.setValue(pwd);
Toast.makeText(view.getContext(), "Registration done successfully", Toast.LENGTH_SHORT).show();
}
});
// Intent loginc = new Intent(this, loginc.class);
// startActivity(loginc);
}
}
logcat
W/GooglePlayServicesUtil: Google Play services out of date. Requires 11011000 but found 9877470
V/FA: Activity paused, time: 32230643
V/FA: Processing queued up service tasks: 2
E/FA: Failed to send current screen to service
E/FA: Discarding data. Failed to send event to service
D/AndroidRuntime: Shutting down VM
E/UncaughtException: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.aayu.myapplication/com.example.aayu.myapplication.regc}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.aayu.myapplication.regc.onCreate(regc.java:76)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
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) 
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.aayu.myapplication, PID: 9023
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.aayu.myapplication/com.example.aayu.myapplication.regc}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.aayu.myapplication.regc.onCreate(regc.java:76)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
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) 
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
Application terminated.
reg_c.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_marginStart="51dp"
android:layout_marginTop="49dp"
android:id="#+id/cname"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:hint="Charity Home Name"
android:selectAllOnFocus="true" />
<Button
android:text="NEXT"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/cnext"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:background="#color/colorPrimary"
android:textStyle="normal|bold"
android:textSize="20sp"
android:elevation="21dp"
android:onClick="next" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_marginTop="24dp"
android:id="#+id/cadd"
android:layout_below="#+id/cname"
android:layout_alignStart="#+id/cname"
android:hint="Address "
android:selectAllOnFocus="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_marginTop="36dp"
android:id="#+id/ccity"
android:hint="City"
android:selectAllOnFocus="true"
android:layout_below="#+id/cadd"
android:layout_alignStart="#+id/cadd" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_marginTop="48dp"
android:id="#+id/cstate"
android:hint="State"
android:selectAllOnFocus="true"
android:layout_below="#+id/ccity"
android:layout_alignStart="#+id/ccity" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:layout_marginTop="34dp"
android:id="#+id/cpin"
android:hint="Pincode"
android:selectAllOnFocus="true"
android:layout_below="#+id/cstate"
android:layout_alignStart="#+id/cstate" />
</RelativeLayout>
layout for reg_c.xml
The issue is here:
final Button mreg=(Button) findViewById(R.id.creg);
mreg.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
String email = memail.getText().toString();
String ph = mph.getText().toString();
String uname = muname.getText().toString();
String pwd = mpwd.getText().toString();
DatabaseReference childref = rootref.child("Email Id");
childref.setValue(email);
childref = rootref.child("Phone No");
childref.setValue(ph);
childref = rootref.child("Username");
childref.setValue(uname);
childref = rootref.child("Password");
childref.setValue(pwd);
Toast.makeText(view.getContext(), "Registration done successfully", Toast.LENGTH_SHORT).show();
}
});
You don't have any button with this id in your XML file but you are trying to access it in your Activity. That is causing Null Pointer Exception.
You have two solution:
If you need this button then add a button with the id "creg" in your XML file.
OR
If you don't need that button then remove the code given above from your Activity.

Android buttons null pointer [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am trying to add an onClickListener to a button, but log cat outputs an error
Here is the log cat
FATAL EXCEPTION: main
Process: com.pk.a_loner, PID: 10539
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pk.a_loner/com.pk.a_loner.main.gui.Connect}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2814)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2879)
at android.app.ActivityThread.access$900(ActivityThread.java:182)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1475)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6141)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.pk.a_loner.main.gui.Connect.init(Connect.java:20)
at com.pk.a_loner.main.gui.Connect.onCreate(Connect.java:53)
at android.app.Activity.performCreate(Activity.java:6374)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2879) 
at android.app.ActivityThread.access$900(ActivityThread.java:182) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1475) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:6141) 
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:1399) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194) 
The code below, should be fine?
package com.pk.a_loner.main.gui;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.pk.a_loner.R;
import com.pk.a_loner.main.networking.Broadcast;
import com.pk.a_loner.main.networking.Listen;
public class Connect extends AppCompatActivity {
private Button button_toggleBroadcast;
private Button button_listen;
private void init() {
this.button_toggleBroadcast = (Button) (findViewById(R.id.button));
this.button_toggleBroadcast.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
if (!Broadcast.isInBroadcast()) {
if (!Broadcast.isHasInit()) {
Broadcast.init();
}
Broadcast.broadcast();
} else {
Broadcast.halt();
}
}
});
this.button_listen = (Button) (findViewById(R.id.button2));
this.button_listen.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
if (!Listen.isInScan()) {
if (!Listen.isHasInit()) {
Listen.init();
}
Listen.scan();
} else {
Listen.halt();
}
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v("hello world", "this is a hello");
this.init();
setContentView(R.layout.activity_launcher);
}
}
and here is the 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=".main.gui.Connect">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toggle broadcast"
android:id="#+id/button" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Listen 10 secs"
android:id="#+id/button2" />
</LinearLayout>
</RelativeLayout>
I checked the code, I did initialize the buttons before I add the listener, shouldn't be null? buttons also declared in xml.
The app currently crashes on startup.
Any help appreciated, many thanks.
Use this in your onCreate() instead:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v("hello world", "this is a hello");
setContentView(R.layout.activity_launcher);
this.init();
}
You need to initialise your views AFTER your layout has been inflated by setContentView()
call setContentView(R.layout.activity_launcher); before init();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v("hello world", "this is a hello");
setContentView(R.layout.activity_launcher);
this.init();
}

Error inflating TextView class in Android Studio

I'm new to the Android SDK as well as Android Studio, but I'm familiar with programming. I have two activities that should be linked together, but for whatever reason my app crashes on launch due to an error in one of my XML files in regards to a TextView object I created. I have no idea what's going on from there. Any help is appreciated!
I'm 90% sure this file is the culprit. I can upload more code on request if you think that it is necessary. Below is the error.
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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.txfbla.benjamin.fblattire.LoginActivity">
<TextView android:id="#+id/login_usernameHeading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/username"
android:textSize="18sp"
android:textColor="#string/login_blue"/>
<EditText android:id="#+id/login_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textAutoComplete" />
<TextView android:id="#+id/login_passwordHeading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/password"
android:textSize="18sp"
android:textColor="#string/login_blue"/>
<EditText android:id="#+id/login_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"/>
<Button android:id="#+id/login_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/login"
android:textSize="16sp"
android:onClick="logIn"/>
</LinearLayout>
package com.txfbla.benjamin.fblattire;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
public void logIn(View view){
Intent intent = new Intent(this, HomePageActivity.class);
EditText editText = (EditText) findViewById(R.id.login_username);
String username = editText.getText().toString();
intent.putExtra("username", username);
startActivity(intent);
}
}
Here's the activity I'm trying to load:
package com.txfbla.benjamin.fblattire;
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;
public class HomePageActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
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();
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
Here's the error I'm getting:
01-09 02:16:15.144 25368-25368/com.txfbla.benjamin.fblattire E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.txfbla.benjamin.fblattire, PID: 25368
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.txfbla.benjamin.fblattire/com.txfbla.benjamin.fblattire.LoginActivity}: android.view.InflateException: Binary XML file line #13: Error inflating class TextView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: android.view.InflateException: Binary XML file line #13: Error inflating class TextView
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at com.txfbla.benjamin.fblattire.LoginActivity.onCreate(LoginActivity.java:14)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) 
at android.app.ActivityThread.access$800(ActivityThread.java:144) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5221) 
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:899) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 
Caused by: android.content.res.Resources$NotFoundException: File #3677A1 from drawable resource ID #0x7f060018: .xml extension required
at android.content.res.Resources.loadColorStateList(Resources.java:2549)
at android.content.res.TypedArray.getColorStateList(TypedArray.java:427)
at android.widget.TextView.<init>(TextView.java:987)
at android.widget.TextView.<init>(TextView.java:629)
at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:60)
at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:56)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:92)
at android.support.v7.app.AppCompatDelegateImplV7.createView(AppCompatDelegateImplV7.java:938)
at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(AppCompatDelegateImplV7.java:992)
at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:725)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:504) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:414) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:365) 
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256) 
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109) 
at com.txfbla.benjamin.fblattire.LoginActivity.onCreate(LoginActivity.java:14) 
at android.app.Activity.performCreate(Activity.java:5933) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) 
at android.app.ActivityThread.access$800(ActivityThread.java:144) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5221) 
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:899) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 
You can't set textColor from a string resource. You can either hard code the value like #FFFFFF or save the value in colors.xml file
colors.xml
<color name="white">#FFFFFF</color>
Change
<TextView android:id="#+id/login_usernameHeading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/username"
android:textSize="18sp"
android:textColor="#string/login_blue "/>
to
<TextView android:id="#+id/login_usernameHeading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/username"
android:textSize="18sp"
android:textColor="#color/white" />
Similarly change the second TextView textColor to color resource.
I was facing similar error but reason was different. If you are trying to add TextView for Activity with name Splash it will give similar error.

App stops working whenever I select one radio button

I have two radio buttons and if one is selected I want to change the value of Textview. I am getting an error. The app stops working when I click one of my radio buttons. It is giving this error on log.
logged error
> /com.example.myapp.mttally E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.myapp.mttally, PID: 15125
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4025)
at android.view.View.performClick(View.java:4785)
at android.widget.CompoundButton.performClick(CompoundButton.java:120)
at android.view.View$PerformClick.run(View.java:19884)
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:5343)
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:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
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:4020)
            at android.view.View.performClick(View.java:4785)
            at android.widget.CompoundButton.performClick(CompoundButton.java:120)
            at android.view.View$PerformClick.run(View.java:19884)
            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:5343)
            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:905)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
..`
           
          
My java code on main file is this
package com.example.myapp.mttally;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
RadioButton lend;
RadioButton borrow;
TextView toFrom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView toFrom = (TextView) findViewById(R.id.toFrom);
RadioButton lend = (RadioButton) findViewById(R.id.lend);
RadioButton borrow = (RadioButton) findViewById(R.id.borrow);
}
#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 void onRadioButtonClicked(View view) {
// Is the button now checked?
Boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.lend:
if (checked)
toFrom.setText(" To");
break;
case R.id.borrow:
if (checked)
toFrom.setText(" From");
break;
}
}
}
Here my xml file
<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">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="8dp"
android:id="#+id/linearLayout">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:clickable="false"
>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radio_button1"
android:id="#+id/lend"
android:textSize="16dp"
android:onClick="onRadioButtonClicked"
/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radio_button2"
android:id="#+id/borrow"
android:textSize="16dp"
android:onClick="onRadioButtonClicked"
/>
</RadioGroup>
</LinearLayout>
</LinearLayout>
<TextView
android:layout_width="140dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/toFrom"
android:layout_below="#+id/linearLayout"
android:layout_centerHorizontal="true"
android:layout_marginTop="78dp" />
</RelativeLayout>
Every time you write something like TextView toFrom, RadioButton lend, or, more generally <type of variable> <variable name>, you're declaring a new variable. You declare variables called twoFrom, lend, and borrow in two places: once in the MainActivity class and once in the onCreate method. So, your code has two different variables that are both called toFrom, two variables called lend, and two variables called borrow.
Consider the lend variable. Each copy of the lend variable has its own "scope", or the area of code in which it exists. Since you declared the first lend variable in the class itself (not inside any of the methods), its scope is the class. You can (typically) use it in code anywhere in the class.
Your second lend variable, however, is what causes the problem. You've declared a second lend variable inside the onCreate method. That second lend is the one gets the TextView object...and then it ceases to exist once the onCreate method finishes executing.
So, to fix this, your onCreate should look like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toFrom = (TextView) findViewById(R.id.toFrom);
lend = (RadioButton) findViewById(R.id.lend);
borrow = (RadioButton) findViewById(R.id.borrow);
}
That way, when you get the reference to the TextView, you're holding it in the variable that will still exist when onRadioButtonClicked is called, not in a second identically-named variable that will cease to exist almost immediately.

I'm getting a NullPointerException when I click a button on my Android app

I’m working on a simple Quiz app where the user is presented a question and can select either True or False to answer the question. I added a “Show Answer” button, but when I click on that button I’m getting the following NullPointerException. I think I'm missing something in my activity_cheat.xml but I can't figure out what.
05-31 19:30:59.238 5978-5978/com.bignerdranch.android.geoquiz.geoquiz E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.bignerdranch.android.geoquiz.geoquiz, PID: 5978
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(int)' on a null object reference
at com.bignerdranch.android.geoquiz.geoquiz.CheatActivity$1.onClick(CheatActivity.java:33)
at android.view.View.performClick(View.java:5197)
at android.view.View$PerformClick.run(View.java:20926)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
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:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
CheatActivity.java
package com.bignerdranch.android.geoquiz.geoquiz;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class CheatActivity extends Activity {
private boolean mAnswerIsTrue;
private TextView mAnswerTextView;
private Button mShowAnswer;
public static final String EXTRA_ANSWER_IS_TRUE = "com.bignerdranch.android.geoquiz.answer_is_true";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false);
mShowAnswer = (Button)findViewById(R.id.showAnswerButton);
mShowAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mAnswerIsTrue) {
mAnswerTextView.setText(R.string.true_button);
} else {
mAnswerTextView.setText(R.string.false_button);
}
}
});
}
}
activity_cheat.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="24dp"
android:text="#string/warning_text_view" />
<TextView
android:id="#+id/answerTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="24dp" />
<Button
android:id="#+id/showAnswerButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/show_answer_button" />
</LinearLayout>
You forgot to bind mAnswerTextView with the UI:
Add
mAnswerTextView = (TextView)findViewById(R.id.answerTextView);
after the line
setContentView(R.layout.activity_cheat);
mAnswerTextView is never initialized. That's why you get the NPE.
add
mAnswerTextView = (TextView)findViewById(R.id.answerTextView);
before
if (mAnswerIsTrue)
mAnswerTextView is null.
Add,
mAnswerTextView = (TextView) findViewById(R.id.answerTextView);
before your onClickListener.

Categories

Resources