Could not execute method for android:onClick - java

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.

Related

Android Studio: logcat says null reference but I don´t see why? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
So I have 2 java classes, the main one being intents.java and the second one being BrowserView.java
I´ve declared both on the android manifest and added the permissions as well.
The main XML file is called main_linearlayout
Can anyone spot the error?
Thank you!
Also - the search button seems to be doing nothing when clicked, not quite sure why?
intents.java:
package com.course.example;
import android.app.Activity;
import android.content.Intent;
import android.content.ComponentName;
import android.os.Bundle;
import android.net.Uri;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class intents extends Activity implements OnClickListener {
private EditText checkAmount, numOfPeople;
private double tip = 0.15;
private TextView viewBill, viewPerson, viewTip;
double totalB, totalP, totalTP, totalT;
// just in case:
//set a request code number to identify a particular request
public static final int requestCode_235 = 235;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(android.R.style.Theme_Dialog);
setContentView(R.layout.main_linearlayout);
// Set up click listeners for all the buttons
// Button continueButton = (Button)findViewById(R.id.first_button);
//continueButton.setOnClickListener(this);
Button goButton = (Button)findViewById(R.id.btnGo);
goButton.setOnClickListener(this);
Button searchButton = (Button)findViewById(R.id.btnSearch);
searchButton.setOnClickListener(this);
Button mapButton = (Button)findViewById(R.id.btnMap);
mapButton.setOnClickListener(this);
Button dialButton = (Button)findViewById(R.id.btnDial);
dialButton.setOnClickListener(this);
}
//avoids runtime check for permission to CALL_PHONE
public void onClick(View v) {
switch (v.getId()) {
// 1) get the calculations
case R.id.btnGo:
// get info from text box called checkAmount:
checkAmount = (EditText) findViewById(R.id.checkAmount);
String checkString = checkAmount.getText().toString();
double checkAmountD = Double.parseDouble(checkString);
double checkAmountR = Math.round(checkAmountD * 100.0) / 100.0;
// get info from number of people
numOfPeople = (EditText) findViewById(R.id.numOfPeople);
String numPeopleS = numOfPeople.getText().toString();
double numPeopleD = Double.parseDouble(numPeopleS);
// calculate total tip, total bill, total per person, and total tip per person
totalT = checkAmountR * tip;
totalB = checkAmountR + totalT;
totalP = totalB / numPeopleD;
totalTP = totalT / numPeopleD;
setNewText(); // print out calculations on app! :)
break;
//2) implicit intent, open dialer and make call
case R.id.btnSearch:
Intent i1 = new Intent(this, BrowserView.class);
startActivityForResult(i1, requestCode_235);
//startActivity(i1);
break;
//3) implicit intent, call GoogleMaps
case R.id.btnMap:
Uri uri2 = Uri.parse("geo:42.3889167,-71.2208033?z=18");
Intent i2 = new Intent(Intent.ACTION_VIEW,uri2);
if (i2.resolveActivity(getPackageManager()) != null) {
startActivity(i2);
}
break;
//4) implicit intent, open dialer and make call
case R.id.btnDial:
Uri uri3 = Uri.parse("tel:7818912000");
Intent i3 = new Intent(Intent.ACTION_CALL,uri3);
startActivity(i3);
break;
}
}
public void setNewText(){
// print these 4 out on the edit texts
TextView viewBill = (TextView) findViewById(R.id.totalBill);
double totalBRounded = Math.round(totalB * 100.0) / 100.0;
String totalBillS = String.valueOf(totalBRounded); // before rounding this was valueof(totalB)
viewBill.setText("$" + totalBillS);
TextView viewPerson = (TextView) findViewById(R.id.totalPerPerson);
double totalPRounded = Math.round(totalP * 100.0) / 100.0;
String totalPerPS = String.valueOf(totalPRounded);
viewPerson.setText("$" + totalPerPS);
TextView viewTip = (TextView) findViewById(R.id.totalTip);
double totalTipRounded = Math.round(totalT * 100.0) / 100.0;
String totalTipS = String.valueOf(totalTipRounded);
viewTip.setText("$" + totalTipS);
TextView viewTipPerPerson = (TextView) findViewById(R.id.tipPerPerson);
double totalTipPerPRounded = Math.round(totalTP * 100.0) / 100.0;
String tipPerPersonS = String.valueOf(totalTipPerPRounded);
viewTipPerPerson.setText("$" + tipPerPersonS);
}
//listen for event of requested activity finishing
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case (requestCode_235): {
if (resultCode == Activity.RESULT_OK)
Toast.makeText(this, "WebLookup finished", Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "WebLookup is NOT working", Toast.LENGTH_LONG).show();
break;
}
default : Toast.makeText(this, "", Toast.LENGTH_LONG).show();
}//switch
}// onActivityResult
}
browser view. java:
package com.course.example;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
public class BrowserView extends Activity {
private EditText urlText;
private Button searchButton;
private WebView webView;
#Override
public void onCreate(Bundle savedInstanceState) {
// ...
super.onCreate(savedInstanceState);
setContentView(R.layout.screen2);
// Get a handle to all user interface elements
urlText = (EditText) findViewById(R.id.url_field);
searchButton = (Button) findViewById(R.id.btnSearch);
webView = (WebView) findViewById(R.id.web_view);
webView.getSettings().setJavaScriptEnabled(true);
//intercept URL loading and load in widget
webView.setWebViewClient(new WebViewClient(){
#SuppressWarnings("deprecation")
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl(url);
return true;
}
});
// Set button to open browser
searchButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
webView.loadUrl(urlText.getText().toString());
}
});
//set listener on EditText
urlText.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View view, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
webView.loadUrl(urlText.getText().toString());
return true;
}
return false;
}
});
}
//the back key navigates back to the previous web page - we were looking at this
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
first couple of lines of logcat:
21-02-27 08:10:35.387 2853-2853/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.course.example, PID: 2853
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.course.example/com.course.example.intents}: 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:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
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.course.example.intents.onCreate(intents.java:49)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
2021-02-27 08:11:23.928 5064-5064/com.course.example E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.course.example, PID: 5064
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.course.example/com.course.example.intents}: 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:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
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.course.example.intents.onCreate(intents.java:49)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
2021-02-27 08:11:27.268 5101-5101/com.course.example E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.course.example, PID: 5101
Edit: here are the 2 XML files:
main linear layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/myLinearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ACA6AA"
android:orientation="vertical"
android:padding="4dp" >
<TextView
android:id="#+id/labelUserName"
android:layout_width="300dp"
android:layout_height="80dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="20dp"
android:background="#F688B4"
android:fontFamily="#font/alfa_slab_one"
android:gravity="center"
android:text="Tip Calculator"
android:textColor="#CCCECE"
android:textSize="25sp"
android:textStyle="bold"></TextView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_marginLeft="5dp"
android:layout_weight="2"
android:background="#F688B4"
android:fontFamily="serif-monospace"
android:gravity="center"
android:text="Check Amount"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold" />
<EditText
android:id="#+id/checkAmount"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textSize="18sp" >
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_marginLeft="5dp"
android:layout_weight="2"
android:background="#F688B4"
android:fontFamily="serif-monospace"
android:gravity="center"
android:text="Number of People"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold" />
<EditText
android:id="#+id/numOfPeople"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textSize="18sp" >
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_marginLeft="5dp"
android:layout_weight="2"
android:background="#F688B4"
android:fontFamily="serif-monospace"
android:gravity="center"
android:text="Tip Percentage%"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold" />
<EditText
android:id="#+id/tipPercent"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textSize="18sp" >
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="horizontal">
<Button
android:id="#+id/btnGo"
style="#style/demoStyle"
android:text="Tip"></Button>
<Button
android:id="#+id/btnWeb"
style="#style/demoStyle"
android:text="WEB"></Button>
<Button
android:id="#+id/btnDial"
style="#style/demoStyle"
android:text="DIAL"></Button>
<Button
android:id="#+id/btnMap"
style="#style/demoStyle"
android:text="MAP"></Button>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_marginLeft="2dp"
android:layout_weight="2"
android:background="#F688B4"
android:fontFamily="#font/abhaya_libre"
android:gravity="center"
android:text="Total Bill"
android:textColor="#color/black"
android:textSize="16sp" />
<TextView
android:id="#+id/totalBill"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_marginLeft="2dp"
android:layout_weight="2"
android:fontFamily="#font/abhaya_libre"
android:gravity="center"
android:textColor="#color/black"
android:textSize="16sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="2"
android:background="#F688B4"
android:fontFamily="#font/abhaya_libre"
android:gravity="center"
android:text="Total per Person"
android:textColor="#color/black"
android:textSize="16sp" />
<TextView
android:id="#+id/totalPerPerson"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="2"
android:fontFamily="#font/abhaya_libre"
android:gravity="center"
android:textColor="#color/black"
android:textSize="16sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_marginLeft="2dp"
android:layout_weight="2"
android:background="#F688B4"
android:fontFamily="#font/abhaya_libre"
android:gravity="center"
android:text="Total Tip"
android:textColor="#color/black"
android:textSize="16sp" />
<TextView
android:id="#+id/totalTip"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_marginLeft="2dp"
android:layout_weight="2"
android:fontFamily="#font/abhaya_libre"
android:gravity="center"
android:textColor="#color/black"
android:textSize="16sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="2"
android:background="#F688B4"
android:fontFamily="#font/abhaya_libre"
android:gravity="center"
android:text="Tip per Person"
android:textColor="#color/black"
android:textSize="16sp" />
<TextView
android:id="#+id/tipPerPerson"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="2"
android:fontFamily="#font/abhaya_libre"
android:gravity="center"
android:textColor="#color/black"
android:textSize="16sp" />
</LinearLayout>
</LinearLayout>
screen 2:
<?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:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
android:id="#+id/url_field"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4" />
<Button
android:id="#+id/btnSearch"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="search" />
</LinearLayout>
<WebView
android:id="#+id/web_view"
android:layout_width="match_parent"
android:background="#ACA6AA"
android:layout_height="match_parent" />
</LinearLayout>
The problem is you set the onClickListener on the button by setOnClickListener and you don't implement view.onClickListener.
you made a method with parameter of View and you don't have any onclick attribute on your xml.
either implement view.onclicklistener and have setonclicklistener or set attribute and have that method.
this should work properly
and also for your search button too if you are adding onclicklistener on button with that method you should use new View.OnClickListener the plain onclicklistener shall not work

Tictac toe game keeps stopping with logcat error java.lang.IllegalStateException:Could not execute method for android:onClick

When I play the game it causes an error after some time and the window closes, App keep stopping.
Logcat for the game is
Process: com.example.tictactoe, PID: 12663
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:414)
at android.view.View.performClick(View.java:7448)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28309)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7698)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:952)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:7448) 
at android.view.View.performClickInternal(View.java:7425) 
at android.view.View.access$3600(View.java:810) 
at android.view.View$PerformClick.run(View.java:28309) 
at android.os.Handler.handleCallback(Handler.java:938) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7698) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:952) 
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=9; index=9
at com.example.tictactoe.MainActivity.playertap(MainActivity.java:32)
at java.lang.reflect.Method.invoke(Native Method) 
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409) 
at android.view.View.performClick(View.java:7448) 
at android.view.View.performClickInternal(View.java:7425) 
at android.view.View.access$3600(View.java:810) 
at android.view.View$PerformClick.run(View.java:28309) 
at android.os.Handler.handleCallback(Handler.java:938) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7698) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:952) 
XML Code for the game is
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:fontFamily="cursive"
android:padding="10dp"
android:text="#string/heading"
android:textSize="34sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<ImageView
android:id="#+id/imageView"
android:layout_width="0dp"
android:layout_height="0dp"
android:contentDescription="#string/main_grid"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
app:layout_constraintVertical_bias="1.0"
app:srcCompat="#drawable/grid" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="420dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="#+id/imageView"
app:layout_constraintTop_toBottomOf="#+id/textView">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:contentDescription="#string/o_value"
android:onClick="playertap"
android:tag="1"
android:padding="20sp"
/>
<ImageView
android:id="#+id/imageView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="playertap"
android:tag="2"
android:padding="20sp" />
<ImageView
android:id="#+id/imageView3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="playertap"
android:tag="3"
android:contentDescription="TODO"
android:padding="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="playertap"
android:tag="4"
android:padding="20sp" />
<ImageView
android:id="#+id/imageView5"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="playertap"
android:tag="5"
android:padding="20sp" />
<ImageView
android:id="#+id/imageView6"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="playertap"
android:tag="6"
android:padding="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView7"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="playertap"
android:tag="7"
android:padding="20sp" />
<ImageView
android:id="#+id/imageView8"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="playertap"
android:tag="8"
android:padding="20sp" />
<ImageView
android:id="#+id/imageView9"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick ="playertap"
android:tag="9"
android:padding="20sp" />
</LinearLayout>
</LinearLayout>
<TextView
android:id="#+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="15sp"
android:text="#string/status"
android:textSize="18sp"
android:textStyle="italic"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearLayout" />
</androidx.constraintlayout.widget.ConstraintLayout>
like so
mainactivity java code:
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
boolean gameActive = true;
// Player representation
// 0 - X
// 1 - O
int activePlayer = 0;
int[] gameState = {2, 2 , 2, 2, 2, 2, 2, 2, 2};
// State meanings:
// 0 - X
// 1 - O
// 2 - Null
int[][] winPositions = {{0,1,2}, {3,4,5}, {6,7,8},
{0,3,6}, {1,4,7}, {2,5,8},
{0,4,8}, {2,4,6}};
public void playertap(View view){
ImageView img = (ImageView) view;
int tappedImage = Integer.parseInt(img.getTag().toString());
if(!gameActive){
gameReset(view);
}
if(gameState[tappedImage] == 2) {
gameState[tappedImage] = activePlayer;
img.setTranslationY(-1000f);
if (activePlayer == 0) {
img.setImageResource(R.drawable.x);
activePlayer = 1;
TextView status = findViewById(R.id.status);
status.setText("O's Turn - Tap to play");
} else {
img.setImageResource(R.drawable.o);
activePlayer = 0;
TextView status = findViewById(R.id.status);
status.setText("X's Turn - Tap to play");
}
img.animate().translationYBy(1000f).setDuration(300);
}
// Check if any player has won
for(int[] winPosition: winPositions){
if(gameState[winPosition[0]] == gameState[winPosition[1]] &&
gameState[winPosition[1]] == gameState[winPosition[2]] &&
gameState[winPosition[0]]!=2){
// Somebody has won! - Find out who!
String winnerStr;
gameActive = false;
if(gameState[winPosition[0]] == 0){
winnerStr = "X has won";
}
else{
winnerStr = "O has won";
}
// Update the status bar for winner announcement
TextView status = findViewById(R.id.status);
status.setText(winnerStr);
}
}
}
public void gameReset(View view) {
gameActive = true;
activePlayer = 0;
for(int i=0; i<gameState.length; i++){
gameState[i] = 2;
}
((ImageView)findViewById(R.id.imageView9)).setImageResource(0);
((ImageView)findViewById(R.id.imageView1)).setImageResource(0);
((ImageView)findViewById(R.id.imageView2)).setImageResource(0);
((ImageView)findViewById(R.id.imageView3)).setImageResource(0);
((ImageView)findViewById(R.id.imageView4)).setImageResource(0);
((ImageView)findViewById(R.id.imageView5)).setImageResource(0);
((ImageView)findViewById(R.id.imageView6)).setImageResource(0);
((ImageView)findViewById(R.id.imageView7)).setImageResource(0);
((ImageView)findViewById(R.id.imageView8)).setImageResource(0);
TextView status = findViewById(R.id.status);
status.setText("X's Turn - Tap to play");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
The app crashes usually after one input although sometimes crashes after one whole game is completed
Unable to understand as the on-click function works fine.
The issue here is in your index, like it says in your exception:
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=9; index=9
at com.example.tictactoe.MainActivity.playertap(MainActivity.java:32)
Two possible solutions here. The first one, which is the better one, is to simply change tags on your images from 0 to 8, instead of 1 to 9. Another approach is to just use - 1 on tappedImage so you always get the right index, but this can complicate things in the future so I would suggest going with the first one since you don't have much code to edit.
This happens because when you click on ImageView with tag = "9", tappedImage gets the value of 9 and you are using it as an index for your array which has a size == 9. But array index is always starting with 0 and going to size - 1. In this case, with size == 9, indexes would be 0, 1, 2, 3, 4, 5, 6, 7, 8 - where 8 is the last one.
As much as I can see you had that logic with your winPositions, you just forgot to start tags from zero.
It's telling you exactly what is happening in the stack trace:
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=9; index=9
at com.example.tictactoe.MainActivity.playertap(MainActivity.java:32)
Line 32 of your MainActivity is going out of bounds of the array, and throwing an exception (ArrayIndexOutOfBoundsException). Unlike the ImageViews which start with an index of 1, the array is 0 based indexed.
You need to adjust your array indexes so they are in the range of 0-8 instead of 1-9, by using tappedImage - 1

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.

Android: 3 activities with the same code but 1 crashes all the time

I am building a math app that has timed multiple choice questions for addition, subtraction, multiplication, and division. The code is pretty simple and is the same for each activity. However, My subtraction activity is very buggy and always crashes at random times. Sometimes it will crash after pressing GO, sometimes it crashes after choosing the first answer, sometimes I can get to 3 questions then it crashes. I'm confused because it does not happen with addition or multiplication. I'm wondering if it has something to do with memory?
Anyways, here is my code and error. Thanks in advance!
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.*;
public class subActivity extends AppCompatActivity {
Button button0;
Button button1;
Button button2;
Button button3;
TextView sub;
Button startButton;
TextView resultTextView;
TextView pointsTextView;
ArrayList<Integer> answers = new ArrayList<Integer>();
int locationOfCorrectAnswer;
int score = 0;
int numberOfQuestions = 0;
TextView timerTextView;
Button playAgainButton;
RelativeLayout gameRelativeLayout;
GridLayout buttonLayout;
float percent;
public void playAgain(View view){
score = 0;
numberOfQuestions = 0;
timerTextView.setText("30s");
pointsTextView.setText("0/0");
resultTextView.setText("");
playAgainButton.setVisibility(View.INVISIBLE);
generateQuestion();
new CountDownTimer(30100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
buttonLayout.setVisibility(View.VISIBLE);
sub.setVisibility(View.VISIBLE);
timerTextView.setText(String.valueOf(millisUntilFinished/1000) + "s");
}
#Override
public void onFinish() {
playAgainButton.setVisibility(View.VISIBLE);
timerTextView.setText("0s");
resultTextView.setText("Your score:" + percent + "%\n Questions:" + Integer.toString(score) + "/" + numberOfQuestions);
buttonLayout.setVisibility(View.INVISIBLE);
sub.setVisibility(View.INVISIBLE);
}
}.start();
}
public void generateQuestion() {
Random rand = new Random();
int a = rand.nextInt(21);
int b = rand.nextInt(21);
int incorrectAnswer;
sub.setText(a + " - " + b);
locationOfCorrectAnswer = rand.nextInt(4);
answers.clear();
for (int i=0; i<4;i++){
if(i == locationOfCorrectAnswer){
answers.add(a-b);
}
else{
incorrectAnswer = rand.nextInt((a-b));
while (incorrectAnswer == a-b) {
incorrectAnswer = rand.nextInt((a-b));
}
answers.add(incorrectAnswer);
}
}
button0.setText(Integer.toString(answers.get(0)));
button1.setText(Integer.toString(answers.get(1)));
button2.setText(Integer.toString(answers.get(2)));
button3.setText(Integer.toString(answers.get(3)));
}
public void start(View view) {
startButton.setVisibility(View.INVISIBLE);
gameRelativeLayout.setVisibility(RelativeLayout.VISIBLE);
playAgain(findViewById(R.id.playAgain));
}
public void chooseAnswer(View view) {
if (view.getTag().toString().equals(Integer.toString(locationOfCorrectAnswer))) {
score++;
resultTextView.bringToFront();
resultTextView.setText("Correct!");
//resultTextView.setBackgroundColor(-16711936);
} else {
resultTextView.bringToFront();
resultTextView.setText("Incorrect!");
//resultTextView.setBackgroundColor(-65536);
}
numberOfQuestions++;
pointsTextView.setText(Integer.toString(score) + "/" + numberOfQuestions);
percent = Math.round((score/(float)numberOfQuestions)*100.0); //get the percentage recieved
generateQuestion();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
startButton = (Button) findViewById(R.id.goButton);
sub = (TextView) findViewById(R.id.subTextView);
resultTextView = (TextView) findViewById(R.id.resultTextView);
pointsTextView = (TextView) findViewById(R.id.pointsTextView);
button0 = (Button) findViewById(R.id.button0);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
timerTextView = (TextView) findViewById(R.id.timerTextView);
playAgainButton = (Button) findViewById(R.id.playAgain);
gameRelativeLayout = (RelativeLayout) findViewById(R.id.gameRelativeLayout);
buttonLayout = (GridLayout) findViewById(R.id.buttonLayout);
}
}
This error shows up when it crashes:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.jimmy.mathtime, PID: 14678
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:5224)
at android.view.View$PerformClick.run(View.java:21356)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5585)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
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:5224) 
at android.view.View$PerformClick.run(View.java:21356) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5585) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620) 
Caused by: java.lang.IllegalArgumentException: n <= 0: -1
at java.util.Random.nextInt(Random.java:182)
at com.example.jimmy.mathtime.subActivity.generateQuestion(subActivity.java:84)
at com.example.jimmy.mathtime.subActivity.chooseAnswer(subActivity.java:124)
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:5224) 
at android.view.View$PerformClick.run(View.java:21356) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5585) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620) 
My XML file:
<?xml version="1.0" encoding="utf-8"?>
<android.widget.RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.jimmy.mathtime.subActivity">
<RelativeLayout
android:id="#+id/gameRelativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="invisible">
<GridLayout
android:id="#+id/buttonLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/subTextView">
<Button
android:id="#+id/button0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="0"
android:layout_columnWeight="1"
android:layout_row="0"
android:layout_rowWeight="1"
android:background="#android:color/holo_blue_bright"
android:onClick="chooseAnswer"
android:tag="0"
android:text="#string/_3"
android:textSize="80sp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_columnWeight="1"
android:layout_row="0"
android:layout_rowWeight="1"
android:background="#color/colorAccent"
android:onClick="chooseAnswer"
android:tag="1"
android:text="#string/_3"
android:textSize="80sp" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="0"
android:layout_columnWeight="1"
android:layout_row="1"
android:layout_rowWeight="1"
android:background="#android:color/holo_green_light"
android:onClick="chooseAnswer"
android:tag="2"
android:text="#string/_3"
android:textSize="80sp" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_columnWeight="1"
android:layout_row="1"
android:layout_rowWeight="1"
android:background="#android:color/holo_purple"
android:onClick="chooseAnswer"
android:tag="3"
android:text="#string/_3"
android:textSize="80sp" />
</GridLayout>
<TextView
android:id="#+id/subTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/timerTextView"
android:layout_centerHorizontal="true"
android:layout_marginTop="36dp"
android:padding="10dp"
android:text="#string/_3_x_3"
android:textColor="#android:color/black"
android:textSize="50sp"
android:textStyle="bold" />
<TextView
android:id="#+id/timerTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="15dp"
android:layout_marginTop="14dp"
android:padding="10dp"
android:text="#string/_30s"
android:textSize="30sp"
android:textStyle="bold" />
<Button
android:id="#+id/playAgain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/buttonLayout"
android:layout_centerHorizontal="true"
android:layout_marginBottom="65dp"
android:background="#color/colorPrimary"
android:onClick="playAgain"
android:text="Play_again"
android:textSize="30sp"
android:visibility="invisible" />
<TextView
android:id="#+id/pointsTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/timerTextView"
android:layout_marginEnd="16dp"
android:padding="10dp"
android:text="#string/_0_0"
android:textSize="30sp"
android:textStyle="bold"
tools:ignore="RelativeOverlap" />
<TextView
android:id="#+id/resultTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:padding="20dp"
android:text="#string/correct"
android:textSize="30sp"
android:textStyle="bold" />
</RelativeLayout>
<Button
android:id="#+id/goButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:backgroundTint="#android:color/holo_blue_bright"
android:onClick="start"
android:padding="40dp"
android:text="#string/go"
android:textSize="80sp"
android:visibility="visible" />
</android.widget.RelativeLayout>
Your exception states:
Caused by: java.lang.IllegalArgumentException: n <= 0: -1
at java.util.Random.nextInt(Random.java:182)
at com.example.jimmy.mathtime.subActivity.generateQuestion(subActivity.java:84)
Basically you pass a negative value to rand.nextInt(max) method.
In your code you do the following operation:
incorrectAnswer = rand.nextInt((a-b));
If b is greater than a, you pass a negative number to nextInt function. This causes your problem. It is not allowed to do this. Check if (a-b)>0!

Categories

Resources