App crashes when Buttons are pressed - java

I created a short quiz in Android studio that consists of 4 questions. One question has RadioButtons, the second has CheckBoxes, third has regular Buttons, and the fourth/ fifth are EditText. Whenever I press any button after running it the app crashes and there's a massive error displayed in the logs.
Activity Main:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
style="#style/Background"
android:layout_width="match_parent"
android:layout_height="wrap_content"
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.example.hende.germanquiz.MainActivity">
<TextView
android:id="#+id/Header_text_view"
style="#style/Header"
android:text="#string/header_text" />
<TextView
android:id="#+id/question_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="16dp"
android:text="#string/questionOne" />
<RadioGroup
android:id="#+id/radio_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/radio1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:checked="true"
android:onClick="Bitte schön"
android:text="#string/wrong1_answer" />
<RadioButton
android:id="#+id/radio2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:onClick="Ich heiße"
android:text="#string/correct_answer" />
<RadioButton
android:id="#+id/radio3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:onClick="Sprechen sie Deutsch?"
android:text="#string/wrong2_answer" />
<TextView
android:id="#+id/question_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="16dp"
android:text="#string/questionTwo"
android:textColor="#B71C1C" />
<CheckBox
android:id="#+id/checkbox1"
style="#style/Buttons"
android:onClick="rechnung1"
android:text="#string/correct2_answer" />
<CheckBox
android:id="#+id/checkbox2"
style="#style/Buttons"
android:onClick="rechnung2"
android:text="#string/correct3_answer" />
<CheckBox
android:id="#+id/checkbox3"
style="#style/Buttons"
android:onClick="Vogel"
android:text="Hast du einen Vogel?" />
<TextView
android:id="#+id/question_three_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="16dp"
android:text="#string/question_three" />
<TextView
android:id="#+id/question_threea_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/question_threea" />
<Button
android:id="#+id/button2"
style="#style/RegularButton"
android:text="#string/wrong4_answer"
android:onClick="button2"/>
<Button
android:id="#+id/button3"
style="#style/RegularButton"
android:text="#string/wrong5_answer"
android:onClick="button3"/>
<Button
android:id="#+id/button1"
style="#style/RegularButton"
android:text="#string/correct4_answer"
android:onClick="button1"/>
<TextView
android:id="#+id/aurora_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/questionFour"
android:layout_marginTop="10dp" />
<EditText
android:id="#+id/edit_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/questionFive"
android:layout_marginTop="10dp"/>
<EditText
android:id="#+id/edit2_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/submit_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/submit_button"
android:onClick="calculateScore"/>
<TextView
android:id="#+id/score_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RadioGroup>
</LinearLayout>
</ScrollView>
MainActivity:
public class MainActivity extends AppCompatActivity {
int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void questionOne(){
RadioButton radio2 =(RadioButton)findViewById(R.id.radio2);
if (radio2.isSelected()) {
score = score + 1;
}}
public void questionTwo(){
CheckBox checkbox1 =(CheckBox) findViewById(R.id.checkbox1);
CheckBox checkbox2=(CheckBox) findViewById(R.id.checkbox2);
if(checkbox1.isChecked() &&checkbox2 .isChecked()){
score = score + 1;
}
}
public void questionThree(){
Button button1 = (Button)findViewById(R.id.button1);
Button button2 = (Button)findViewById(R.id.button2);
Button button3 = (Button)findViewById(R.id.button3);
if (button1.isSelected()) {
score= score + 1;
}
}
public void questionFour(){
EditText edit_text_view =(EditText) findViewById(R.id.edit_text_view);
if (edit_text_view.getText().toString().contains("Nordlicht") || edit_text_view.getText().toString().contains("Nordlicht")) {
score = score + 1;
}
}
public void questionFive(){
EditText edit2_text_view=(EditText)findViewById(R.id.edit2_text_view);
if (edit2_text_view.getText().toString().contains("On October 10th at 10:10, 10 tame goats pull 10 centners of sugar to the zoo")|| edit2_text_view.getText().toString().contains("On October 10th at 10:10, 10 tame goats pull 10 centners of sugar to the zoo")) {
score = score + 1;
}
}public void calculateScore(View view){
display (score);
questionOne ();
questionTwo ();
questionThree();
questionFour ();
questionFive ();
}
private void display(int number) {
TextView score_text_view = (TextView) findViewById(
R.id.score_text_view);
score_text_view.setText("" + number);
}}
Log error:
08-27 13:07:50.408 3344-3344/com.example.hende.germanquiz E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.hende.germanquiz, PID: 3344
java.lang.IllegalStateException: Could not find method rechnung2(View) in a parent or ancestor Context for
android:onClick attribute defined on view class android.support.v7.widget.AppCompatCheckBox with id 'checkbox2'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:5609)
at android.widget.CompoundButton.performClick(CompoundButton.java:122)
at android.view.View$PerformClick.run(View.java:22259)
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: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)
08-27 12:49:22.499 32531-416/com.example.hende.germanquiz E/InstantRun:
Failed to update existing theme for activity com.example.hende.germanquiz.MainActivity#587f4d8
java.lang.NoSuchFieldException: No field mTheme in class Landroid/content/res/Resources$Theme;
(declaration of 'android.content.res.Resources$Theme' appears in /system/framework/framework.jar)
at java.lang.Class.getDeclaredField(Native Method)
at com.android.tools.fd.runtime.MonkeyPatcher.monkeyPatchExistingResources(MonkeyPatcher.java:374)
at com.android.tools.fd.runtime.Server.restart(Server.java:523)
at com.android.tools.fd.runtime.Server.access$600(Server.java:61)
at com.android.tools.fd.runtime.Server$SocketServerReplyThread.handle(Server.java:318)
at com.android.tools.fd.runtime.Server$SocketServerReplyThread.run(Server.java:190)
at com.android.tools.fd.runtime.Server$SocketServerThread.run(Server.java:158)
at java.lang.Thread.run
08-27 12:49:43.382 32531-32531/com.example.hende.germanquiz E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
08-27 12:49:43.590 32531-32531/com.example.hende.germanquiz E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length

In your xml you define property onClick. That means when you click on that button android will call method named in "onClick" property. Since you dont have those methods defined in you MainActivity, you get runtime error

There is multiple problems here.
The first seems to be because you have declared a method named "rechnung2" on the onClick property of the Checkbox but you have never implemented it.
On the second error it appears are you using a different theme than the default and may be causing a conflict somewhere along the chain.
The last error in the trace may be because you are appending the score onto a blank space in your display method

The onClick XML attribute calls a method, you must have that method in your MainActivity. In addition you have to follow these rules:
The method you declare in the android:onClick attribute must have a
specific signature. Specifically, the method must:
Be public
Return void
Define a View as its only parameter (this will be the View that was clicked)

In your Activity there is no method named rechnung2
Your logcat says it:
java.lang.IllegalStateException: Could not find method rechnung2(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatCheckBox with id 'checkbox2'
Suggestion : Please check your xml and find all android:onclick elements then check your Activity, in your Activity you must have regarding method.
Also Android Studio warns you if you don't have that method in your Activity like that :

Related

Runtime Error with Android Studio (Button)

I would be so, so grateful if you can help me with this problem.
I am learning android development with Android Basics on Udacity.
I am at User Input: Lesson 8.
The apps have been downloading to my phone fine so far but now the app (JustJava) crashes when I press the only button in it. There are no serious (red) errors showing on Android Studio.
I have reviewed logcat but cannot understand it except that the button (onClick) is the problem. I have no idea how to fix it.
This keeps appearing in red in logcat every few seconds: E/TZ_CCM_SERVER: Only 'CCM' are supported
Here is the full error log relating my runtime crash:
07-09 10:51:17.638 18253-18253/com.example.android.justjava E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.justjava, PID: 18253
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:389)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10826)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384)
at android.view.View.performClick(View.java:5697) 
at android.widget.TextView.performClick(TextView.java:10826) 
at android.view.View$PerformClick.run(View.java:22526) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:158) 
at android.app.ActivityThread.main(ActivityThread.java:7224) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.android.justjava.MainActivity.displayPrice(MainActivity.java:45)
at com.example.android.justjava.MainActivity.submitOrder(MainActivity.java:28)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384) 
at android.view.View.performClick(View.java:5697) 
at android.widget.TextView.performClick(TextView.java:10826) 
at android.view.View$PerformClick.run(View.java:22526) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:158) 
at android.app.ActivityThread.main(ActivityThread.java:7224) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
EDIT:
MainActivity / java code:
package com.example.android.justjava;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import java.text.NumberFormat;
/**
* This app displays an order form to order coffee.
*/
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* This method is called when the order button is clicked.
*/
public void submitOrder(View view) {
int coffeeNumber = 3;
display(coffeeNumber);
displayPrice(coffeeNumber * 5);
}
/**
* This method displays the given quantity value on the screen.
*/
private void display(int number) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText("" + number);
}
/**
* This method displays the given price on the screen.
*/
private void displayPrice(int number) {
TextView priceTextView = (TextView) findViewById(R.id.price_text_view);
priceTextView.setText(NumberFormat.getCurrencyInstance().format(number));
}
}
XML Code:
<?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:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Quantity"
android:fontFamily="sans-serif-light"
android:textColor="#android:color/black"
android:padding="10dp"
android:textAllCaps="true"
android:layout_marginBottom="16dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textSize="16sp"
android:fontFamily="sans-serif-light"
android:textColor="#android:color/black"
android:padding="10dp"
android:id="#+id/quantity_text_view"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Price"
android:fontFamily="sans-serif-light"
android:textColor="#android:color/black"
android:padding="10dp"
android:textAllCaps="true"
android:layout_marginBottom="16dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="€0"
android:textSize="16sp"
android:fontFamily="sans-serif-light"
android:textColor="#android:color/black"
android:padding="10dp"
android:layout="#+id/price_text_view"
/>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Order"
android:onClick="submitOrder"
/>
</LinearLayout>
Check your activity_main.xml in this layout you does not have a TextView with that id price_text_view. Just define a TextView with that id and your App will not crash anymore and you can go Forward to the next chapter ;)
<TextView
android:id="#+id/price_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
I think you just made a silly misstake. I saw you're using layout insteed of id ^^
Change your xml like below
<?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:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Quantity"
android:fontFamily="sans-serif-light"
android:textColor="#android:color/black"
android:padding="10dp"
android:textAllCaps="true"
android:layout_marginBottom="16dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textSize="16sp"
android:fontFamily="sans-serif-light"
android:textColor="#android:color/black"
android:padding="10dp"
android:id="#+id/quantity_text_view"/>
<TextView
android:id="#+id/price_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Price"
android:fontFamily="sans-serif-light"
android:textColor="#android:color/black"
android:padding="10dp"
android:textAllCaps="true"
android:layout_marginBottom="16dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="€0"
android:textSize="16sp"
android:fontFamily="sans-serif-light"
android:textColor="#android:color/black"
android:padding="10dp"
android:layout="#+id/price_text_view"
/>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Order"
android:onClick="submitOrder"
/>
I have just Called TextView in global, then initialized in onCreateand then using wherever we need.
Just replace this edited java class,
public class MainActivity extends AppCompatActivity {
TextView priceTextView, quantityTextView ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
priceTextView = (TextView) findViewById(R.id.price_text_view);
}
/**
* This method is called when the order button is clicked.
*/
public void submitOrder(View view) {
int coffeeNumber = 3;
display(coffeeNumber);
displayPrice(coffeeNumber * 5);
}
/**
* This method displays the given quantity value on the screen.
*/
private void display(int number) {
quantityTextView.setText("" + number);
}
/**
* This method displays the given price on the screen.
*/
private void displayPrice(int number) {
priceTextView.setText(NumberFormat.getCurrencyInstance().format(number));
}
}

textView setText() Null Pointer Exception [Single Activity Application]

The simple app with just one activity is creating problems with finding the layout's TextView and showing the same as null. Kindly debug the same why the app is crashing on clicking the submit button. I tried many solutions in Stack Overflow and many solutions say that the view might be located outside the activity specified, but here the only one activity is there. So research didn't help me, and now I'm left with the fellow developers who could predict the fault I could have committed.
MainActivity.java
package me.thirumurugan.quiz;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button submit;
TextView result;
RadioButton answer_a;
EditText answer_b;
CheckBox answer_c1, answer_c2, answer_c3, answer_c4;
EditText answer_d;
int correct = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
answer_a = (RadioButton) findViewById(R.id.answer_a);
answer_b = (EditText) findViewById(R.id.answer_b);
answer_c1 = (CheckBox) findViewById(R.id.answer_c1);
answer_c2 = (CheckBox) findViewById(R.id.answer_c2);
answer_c3 = (CheckBox) findViewById(R.id.answer_c3);
answer_c4 = (CheckBox) findViewById(R.id.answer_c4);
answer_d = (EditText) findViewById(R.id.answer_d);
submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
correct = 0;
if (answer_a.isChecked()){
correct++;
}
if (answer_b.getText().toString().equals("2020")){
correct++;
}
if (answer_c1.isChecked()&&answer_c2.isChecked()&&answer_c3.isChecked()&&!answer_c4.isChecked()){
correct++;
}
if (answer_d.getText().toString().toLowerCase().equals("arun jaitley")){
correct++;
}
result.setText("The Score is " + correct + " on 4!");
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context="me.thirumurugan.quiz.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/welcome_messege"
android:textAlignment="center"
android:id="#+id/result"
android:padding="#dimen/padding"
android:textStyle="bold"
android:textSize="16sp"
android:background="#color/colorAccent"
android:textColor="#FFF"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/padding"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/padding"
android:text="#string/question_1"
android:textColor="#color/colorPrimary"
android:textStyle="bold" />
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/answer_a"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/answer_1_a" />
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/answer_1_b" />
</RadioGroup>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/padding"
android:layout_marginTop="#dimen/padding"
android:text="#string/question_2"
android:textColor="#color/colorPrimary"
android:textStyle="bold" />
<EditText
android:id="#+id/answer_b"
android:hint="#string/answer_hint"
android:textColorHint="#color/colorAccent"
android:layout_width="match_parent"
android:textSize="14sp"
android:layout_height="wrap_content"
android:backgroundTint="#color/colorPrimary"
tools:targetApi="lollipop" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/padding"
android:layout_marginTop="#dimen/padding"
android:text="#string/question_3"
android:textColor="#color/colorPrimary"
android:textStyle="bold" />
<CheckBox
android:id="#+id/answer_c1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/answer_3_a" />
<CheckBox
android:id="#+id/answer_c2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/answer_3_b" />
<CheckBox
android:id="#+id/answer_c3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/answer_3_c" />
<CheckBox
android:id="#+id/answer_c4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/answer_3_d" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/padding"
android:layout_marginTop="#dimen/padding"
android:text="#string/question_4"
android:textColor="#color/colorPrimary"
android:textStyle="bold" />
<EditText
android:id="#+id/answer_d"
android:hint="#string/answer_hint"
android:textSize="14sp"
android:textColorHint="#color/colorAccent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/colorPrimary"
tools:targetApi="lollipop" />
<Button
android:id="#+id/submit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/colorPrimary"
android:text="#string/submit"
android:textColor="#FFFFFF"
android:textStyle="bold"
tools:targetApi="lollipop" />
</LinearLayout>
</ScrollView>
</LinearLayout>
The error message was the following in the trace:
08-10 21:58:06.301 20947-20947/me.thirumurugan.quiz E/AndroidRuntime:
FATAL EXCEPTION: main Process: me.thirumurugan.quiz, PID: 20947
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.TextView.setText(java.lang.CharSequence)' on a null
object reference at
me.thirumurugan.quiz.MainActivity$1.onClick(MainActivity.java:52) 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)
You are in need of a clean and rebuild. There is nothing wrong with your code. Multiple users have copied the code and used it to success in their applications, including myself:
Text is missing because I do not have your dimens or strings files.
You do not have a scope issue, as others have suggested. Your member variables should be accessible by any anonymous inner class you create.
There are otherwise missing lines from your shared code. In which case, the community can not resolve your problem as nobody will be capable of replicating it.

Could not execute method for android:onClick

I'm making a quiz app and I'm using one EditText, and when I don't type anything in it and press SubmitButton I get this error:
FATAL EXCEPTION: main
Process: com.example.andriod.quiz, PID: 12960
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:4756)
at android.view.View$PerformClick.run(View.java:19761)
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:5264)
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:900)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:695)
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.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19761)
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:5264)
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:900)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:695)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.content.res.Resources.getText(Resources.java:284)
at android.widget.TextView.setText(TextView.java:4176)
at com.example.andriod.quiz.MainActivity.submitAnswer(MainActivity.java:65)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19761)
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:5264)
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:900)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:695)
Here is my java code:
package com.example.andriod.quiz;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
/**
* This app displays Millionaire Quiz
*/
public class MainActivity extends AppCompatActivity {
private String name;
private int correctAnswers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* This method is called when the Ok button is clicked. it's displays personalized greetings.
*
* #param view
*/
public void greetings(View view) {
EditText nameField = (EditText) findViewById(R.id.customer_name);
name = nameField.getText().toString();
TextView greetings = (TextView) findViewById(R.id.greetings);
greetings.setText("Hello " + name + ". Scroll down if you are ready.");
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
LinearLayout questionsLayout = (LinearLayout) findViewById(R.id.questions_layout);
questionsLayout.setVisibility(View.VISIBLE);
}
/**
* Checks correct answers, and displays a toast with congratulations and amount of correctly answered questions.
*
* #param view
*/
public void submitAnswer(View view) {
correctAnswers = 0;
RadioButton firstQuestion = (RadioButton) findViewById(R.id.first_correct);
if (firstQuestion.isChecked()) {
correctAnswers++;
}
EditText secondQuestion = (EditText) findViewById(R.id.second_question);
int answer = Integer.parseInt(secondQuestion.getText().toString());
if (answer == 27) {
correctAnswers++;
}
CheckBox checkBoxA = (CheckBox) findViewById(R.id.answer_a);
CheckBox checkBoxB = (CheckBox) findViewById(R.id.answer_b);
CheckBox checkBoxC = (CheckBox) findViewById(R.id.answer_c);
CheckBox checkBoxD = (CheckBox) findViewById(R.id.answer_d);
if (!checkBoxA.isChecked() && checkBoxB.isChecked() && checkBoxC.isChecked() && !checkBoxD.isChecked()) {
correctAnswers++;
}
RadioButton fourthQuestion = (RadioButton) findViewById(R.id.fourth_correct);
if (fourthQuestion.isChecked()) {
correctAnswers++;
}
RadioButton fifthQuestion = (RadioButton) findViewById(R.id.fifth_correct);
if (fifthQuestion.isChecked()) {
correctAnswers++;
}
String correctlyAnswered;
switch (correctAnswers) {
case 5:
correctlyAnswered = "Congratulation " + name + " you answer correctly to every question! You won 1 million! ";
break;
case 4:
correctlyAnswered = "Congratulation " + name + " you answer correctly to 4 questions! You won 750 thousands! You should try one more time!";
break;
case 3:
correctlyAnswered = "Congratulation " + name + " you answer correctly to 3 questions! You won 500 thousands! You should try one more time!";
break;
case 2:
correctlyAnswered = "Congratulation " + name + " you answer correctly to 3 questions! You won 250 thousands! You should try one more time!";
break;
case 1:
correctlyAnswered = "Congratulation " + name + " you answer correctly to 1 question! You won 100 thousands! You should try one more time!";
break;
default:
correctlyAnswered = "You didn't answer correctly to any question :( \nYou should try one more time!";
}
Toast toast = Toast.makeText(this, correctlyAnswered, Toast.LENGTH_LONG);
toast.show();
}
}
And here is xml file:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/second_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#6158AC"
android:orientation="vertical"
tools:context="com.example.andriod.quiz.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="16dp"
android:text="Welcome in Millionaire Game! \nAre you ready to play for a million?"
android:textSize="24sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/customer_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Name"
android:inputType="textCapWords" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="greetings"
android:text="Ok"
android:textAllCaps="true" />
</LinearLayout>
<TextView
android:id="#+id/greetings"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="16dp"
android:paddingTop="16dp"
android:textSize="24sp" />
<LinearLayout
android:id="#+id/questions_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:visibility="visible">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First question: \nHow many parts has Harry Potter series?" />
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/first_correct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Seven" /><!--correct-->
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Eight" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Six" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Three" />
</RadioGroup>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Second question: \nOwen thinks of a number, adds 13, and then divides the result by 5. The answer is 8. Find the number Owen thinks of." />
<EditText
android:id="#+id/second_question"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="number"
android:hint="Write here your answer." />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Third question: \nWhat is a value of absolute zero?" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<CheckBox
android:id="#+id/answer_a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-189°C" />
<CheckBox
android:id="#+id/answer_b"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-271,15°C" /><!--correct-->
<CheckBox
android:id="#+id/answer_c"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0K" /><!--correct-->
<CheckBox
android:id="#+id/answer_d"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="100K" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fourth question: \nWhat is the main component in glass?" />
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/fourth_correct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sand" /> <!--correct-->
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Iron" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Coal" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Water" />
</RadioGroup>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fifth question: \nWhich is the largest species of the tiger?" />
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Chinese tiger" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bengali tiger" />
<RadioButton
android:id="#+id/fifth_correct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Siberian tiger" /><!--correct-->
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Indo-Chinese tiger" />
</RadioGroup>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="submitAnswer"
android:text="Submit answers"
android:textAllCaps="true" />
</LinearLayout>
</LinearLayout>
Does anyone knows why this error occurs?
I'm sorry for every mistake I made, this is my first question here ;)
It fails here:
int answer = Integer.parseInt(secondQuestion.getText().toString());
You must have a not empty field here, and also it should be a number.
You can do simply check:
int answer = 0;
EditText secondQuestion = (EditText) findViewById(R.id.second_question);
if(secondQuestion.getText().toString().equals("")) {
//Handle invalid input
} else {
answer = Integer.parseInt(secondQuestion.getText().toString());
}
Just implement some validation of invalid input, and this can be handled easily.

android-can't get value of edit text in fragment [duplicate]

This question already has answers here:
Get Value of a Edit Text field
(13 answers)
Closed 6 years ago.
I've tried get edittext value but does not work.This is my code in android fragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v=inflater.inflate(R.layout.fragment_add_patient, container, false);
final EditText FirstName=(EditText) v.findViewById(R.id.FirstName);
final Button addPatientButton=(Button) v.findViewById(R.id.AddPatientButton);
addPatientButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isOnline()) {
try {
if (FirstName.getText().toString().trim().equals("")) {
FirstName.setError("First Name is required!");
return;
}
I receive error at this line :FirstName.getText().toString().trim().equals("")
The error is following: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference.
Here is my fragment_add_patient xml file which contains all items.
<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"
tools:context="com.example.ionut.myapplication.PatientController.AddPatientFragment">
<!-- TODO: Update blank fragment layout -->
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="80dp"
android:id="#+id/PatientFirstName"
android:hint="First Name" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_marginTop="27dp"
android:id="#+id/PatientLastName"
android:hint="Last Name"
android:layout_below="#+id/PatientFirstName"
android:layout_alignLeft="#+id/PatientFirstName"
android:layout_alignStart="#+id/PatientFirstName" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:layout_below="#+id/PatientLastName"
android:layout_alignRight="#+id/PatientLastName"
android:layout_alignEnd="#+id/PatientLastName"
android:layout_marginTop="25dp"
android:id="#+id/Email"
android:hint="Email" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:layout_marginTop="22dp"
android:id="#+id/PatientAge"
android:hint="Age"
android:layout_below="#+id/Email"
android:layout_alignLeft="#+id/Email"
android:layout_alignStart="#+id/Email" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="phone"
android:ems="10"
android:layout_below="#+id/PatientAge"
android:layout_alignLeft="#+id/PatientAge"
android:layout_alignStart="#+id/PatientAge"
android:layout_marginTop="32dp"
android:id="#+id/PatientPhone"
android:hint="Phone" />
<Button
android:text="Add Patient"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/AddPatientButton"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="77dp" />
<Spinner
android:id="#+id/cspinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:layout_below="#+id/PatientPhone"
android:layout_alignRight="#+id/PatientPhone"
android:layout_alignEnd="#+id/PatientPhone"
android:layout_alignLeft="#+id/PatientPhone"
android:layout_alignStart="#+id/PatientPhone" />
Thanks in advance!.
The FirstName EditText is null because the findViewById method is trying to find an editext with the id of FirstName but the correct id is PatientFirstName
To solve the issue, replace the
final EditText FirstName=(EditText) v.findViewById(R.id.FirstName);
with
final EditText FirstName=(EditText) v.findViewById(R.id.PatientFirstName);
Simply you are trying to query of non existing id in your layout .
the actual id for your "First Name" EditText is "PatientFirstName". also try to make your code just a little bit organized as follows
1- Declare your Button , EditText variables as a global variable to be accessible anywhere inside your fragment
2- if you gonna add more buttons with click events then you should make your fragment or activity implements the View.onClickListener

Android Cursor Adapter for Custom ListView Layout - Null Pointer Exception Error [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
First post on this site, so forgive me my sins. I am attempting to create a custom ListView layout that is populated by fields from my SQLite Database Adapter class. Below is the method I tried to use for this, and it is called in the onCreate method of its class, as well as the onClick method of a button to save to the Database:
//Method to re-populate custom list view songlist_layout when a new entry is added
private void populateSongList() {
//Cursor to navigate through records of the database
Cursor cursor = myDb.getAllRows();
//Need two arrays to work with the Cursor. First is from field names
String [] fromFieldNames = new String[] {DBAdapter.KEY_ROWID,
DBAdapter.KEY_SONGTITLE,
DBAdapter.KEY_SONGDURATION};
//Second is int array
int [] toViewIDs = new int [] {R.id.textViewSongNumber, R.id.textViewSongName,
R.id.textViewSongDuration};
//Cursor Adapter Object
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(),
R.layout.songlist_layout, cursor, fromFieldNames, toViewIDs,0);
//Need to grab ListView from activity_add_song to set the adapter to it
ListView songList = (ListView)findViewById(R.id.songsListView);
songList.setAdapter(myCursorAdapter);
}
//Method to handle the click event of the Save button, adding the data into the database
public void onClickSaveSong (View v) {
//Song Title and duration are essential fields, so we want to check if they
// have text before saving to the database
if(!TextUtils.isEmpty(etSongTitle.getText().toString()) &&
!TextUtils.isEmpty(etSongDuration.getText().toString())) {
myDb.insertRow(etSongTitle.getText().toString(),
etSongKey.getText().toString(),
etSongTuning.getText().toString(),
etSongDuration.getText().toString());
//Pop-up to inform user the Data has been saved
Toast.makeText(getBaseContext(), "Song Added!", Toast.LENGTH_LONG).show();
}//if
//Otherwise a pop-up to tell the user to enter the essential info
else {Toast.makeText(getBaseContext(), "Enter Title and Duration",
Toast.LENGTH_LONG).show();}
//Call to repopulate songs ListView
populateSongList();
}//onClickSaveSong()
The custom XML Layout for the ListView contains three TextViews to hold the songNumber, the songName and the songDuration:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textViewSongNumber"
android:paddingRight="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textViewSongName"
android:paddingRight="60dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textViewSongDuration"
android:paddingRight="70dp"/>
I have read elsewhere that the problem could be because the ListView is grabbing from the wrong ListView ID
ListView songList = (ListView)findViewById(R.id.songsListView);
However comparing it to the XML Layout for the ListView, I don't see how this would be the case:
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/songsListView"
android:layout_below="#+id/imageView"
android:layout_centerHorizontal="true"
android:layout_above="#+id/addSongButton" />
Finally, the logcat:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.blob.gigstrofinal/com.blob.gigstrofinal.AddSong}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.blob.gigstrofinal.AddSong.populateSongList(AddSong.java:121)
at com.blob.gigstrofinal.AddSong.onCreate(AddSong.java:45)
I cannot figure this out. I haven't been using Android for long, and a lot of this is over my head, so I would appreciate any help at all on this matter. The App is for a University Project, and it is due next week!
EDIT: I forgot to specify, the Null Pointer Exception is pointing to line 121 of AddSong.java which is: songList.setAdapter(myCursorAdapter);
I am calling the populateSongList()method from the onCreate method in the AddSong class:
public class AddSong extends Activity {
//Declare Database Adapter
DBAdapter myDb;
//Declare EditText objects to be used for each field in the SQLite Database
EditText etSongTitle;
EditText etSongKey;
EditText etSongTuning;
EditText etSongDuration;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_song);
//Initialise EditText objects by assigning them to the corresponding ID
etSongTitle = (EditText)findViewById(R.id.editSongTitle);
etSongKey = (EditText)findViewById(R.id.editSongKey);
etSongTuning = (EditText)findViewById(R.id.editSongTuning);
etSongDuration = (EditText)findViewById(R.id.editSongDuration);
//Call method to open Database
openDB();
//Call to populate songs ListView
populateSongList();
}
and again for the onClickSaveSong method of AddSong.java (see second code snippet of original post.
EDIT2: The full contents of activity_add_song.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="com.blob.gigstrofinal.AddSong"
android:background="#color/colorPrimary"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tvSongTitle"
android:id="#+id/songTitle"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:textStyle="bold"
android:textSize="13sp"
android:textColor="#color/colorPrimary2" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/songTitle"
android:id="#+id/editSongTitle"
android:layout_alignParentStart="true"
android:editable="true"
android:inputType="text"
android:background="#e6e6e6"
android:textColor="#color/colorPrimary3"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tvKey"
android:id="#+id/songKey"
android:textStyle="bold"
android:textSize="13sp"
android:textColor="#color/colorPrimary2"
android:layout_marginTop="15dp"
android:layout_below="#+id/editSongTitle"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editSongKey"
android:layout_below="#+id/songKey"
android:layout_alignParentStart="true"
android:layout_alignEnd="#+id/editSongTitle"
android:background="#e6e6e6"
android:inputType="text"
android:textColor="#color/colorPrimary3" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tvTuning"
android:id="#+id/songTuning"
android:textStyle="bold"
android:textSize="13sp"
android:textColor="#color/colorPrimary2"
android:layout_marginTop="13dp"
android:layout_below="#+id/editSongKey"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editSongTuning"
android:layout_below="#+id/songTuning"
android:layout_alignParentStart="true"
android:layout_alignEnd="#+id/editSongKey"
android:background="#e6e6e6"
android:textColor="#color/colorPrimary3"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tvDuration"
android:id="#+id/songDuration"
android:textStyle="bold"
android:textSize="13dp"
android:textColor="#color/colorPrimary2"
android:layout_marginTop="15dp"
android:layout_below="#+id/editSongTuning"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editSongDuration"
android:layout_below="#+id/songDuration"
android:layout_alignParentStart="true"
android:layout_alignEnd="#+id/editSongTuning"
android:background="#e6e6e6"
android:textColor="#color/colorPrimary3"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tvLyrics"
android:id="#+id/songLyrics"
android:textStyle="bold"
android:textSize="13sp"
android:textColor="#color/colorPrimary2"
android:layout_below="#+id/editSongDuration"
android:layout_alignParentStart="true"
android:layout_marginTop="15sp"
android:textIsSelectable="false" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/editSongLyrics"
android:layout_below="#+id/songLyrics"
android:layout_alignParentStart="true"
android:layout_alignEnd="#+id/editSongDuration"
android:background="#e6e6e6"
android:layout_above="#+id/saveButton"
android:layout_marginBottom="20dp"
android:textColor="#color/colorPrimary3"/>
<Button
android:id="#+id/saveButton"
android:text="#string/buttonSaveText"
android:background="#color/colorPrimary"
android:textColor="#color/colorPrimary2"
android:textStyle="bold"
android:textSize="11sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="19dp"
android:layout_marginRight="22dp"
android:onClick="onClickSaveSong"
android:layout_alignParentBottom="true"
/>
<Button
android:id="#+id/backButton"
android:text="#string/backButtonText"
android:background="#color/colorPrimary"
android:textColor="#color/colorPrimary2"
android:textStyle="bold"
android:textSize="11sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickBack"
android:layout_alignBottom="#+id/saveButton"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="19dp"
/>
</RelativeLayout>
It is perhaps worth mentioning that the ListView itself is not located in Activity_add_song, it is in another Activity activity_songs. Would that cause a null pointer exception?
The problem is that the ListView is not in the layout xml that you're inflating in this Activity.
When you call this in onCreate():
setContentView(R.layout.activity_add_song);
You're inflating the activity_add_song.xml layout xml to the current Window.
Then when you call:
ListView songList = (ListView)findViewById(R.id.songsListView);
It's looking at the currently inflated layout for a ListView with ID songsListView. Since there is no songsListView in the currently inflated layout (activity_add_song.xml), it will be null.
Move all code dealing with songsListView to the Activity that inflates the layout with the ListView.
Make sure you call populateSongList() after setContentView().
And please be more specific about where the line 121 is.
Caused by: java.lang.NullPointerException
at com.blob.gigstrofinal.AddSong.populateSongList(AddSong.java:121)
Since line 121 is this:
songList.setAdapter(myCursorAdapter);
and that is where you are getting null, then either songList or myCursorAdapter is null. myCursorAdapter is clearly not null, so you likely have the wrong name for your findViewById method in this line:
ListView songList = (ListView)findViewById(R.id.songsListView);
Check that the listview is actually called "songsListView" in your XML - it probably isn't.
Your activity_add_song.xml should contain the ListView, which is missing in your code.
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/songsListView"
android:layout_below="#+id/imageView"
android:layout_centerHorizontal="true"
android:layout_above="#+id/addSongButton" />
and R.layout.songlist_layout should contain the layout for each row
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textViewSongNumber"
android:paddingRight="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textViewSongName"
android:paddingRight="60dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textViewSongDuration"
android:paddingRight="70dp"/>

Categories

Resources