Illegal State Exception, Application can't find method defined in class - java

I have a method name set using onClick in my XML file but the application can't seem to find it. I think it is because the method should be called using the button of an alert dialog. Any ideas would be appreciated!
Main Activity:
public class MainActivity extends Activity {
String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void recordExpenditure(View v) {
Log.v(TAG, "User clicked Record Expenditure button");
// custom dialog
final Dialog dialog = new Dialog(v.getContext());
dialog.setContentView(R.layout.add_expenditure_dialog_layout);
dialog.setTitle("Add new expenditure");
dialog.show();
}
public void viewExpenditure(View v) {
Log.v(TAG, "User clicked View Expenditure button");
}
public void saveExpenditure(View v) {// <---- Can't find this
DatabaseHandler db = new DatabaseHandler(this);
// Inserting Contacts
Log.d(TAG, "Inserting new expenditure into database");
Log.v(TAG, "User clicked Save Expenditure button");
EditText saveExpenditureTitleText = (EditText)findViewById(R.id.expenditureTitleBox);
EditText saveExpenditureValue = (EditText)findViewById(R.id.expenditureValueBox);
String expenditureText = saveExpenditureTitleText.getText().toString();
String expenditureValue = saveExpenditureValue.getText().toString();
db.addExpenditure(new Expenditure(expenditureText, expenditureValue));
Log.v(TAG, "Recording expenditure details...\nExpenditure Title: " + expenditureText + "\nExpenditure Value: " + expenditureValue);
}
public void cancelExpenditure(View v) {
Log.v(TAG, "User clicked Cancel Expenditure button");
}
}
Main Layout.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"
tools:context=".MainActivity" >
<Button
android:id="#+id/recordExpenditure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:text="Add Expenditure"
android:onClick="recordExpenditure" />
<Button
android:id="#+id/viewExpenditure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/recordExpenditure"
android:layout_below="#+id/recordExpenditure"
android:layout_marginTop="45dp"
android:text="View Expenditure"
android:onClick="viewExpenditure" />
</RelativeLayout>
Dialog Box.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/expenditureValueText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/expenditureTitleBox"
android:text="Expenditure Value" />
<TextView
android:id="#+id/expenditureTitleText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Expenditure Title" />
<EditText
android:id="#+id/expenditureTitleBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/expenditureTitleText"
android:ems="10" />
<EditText
android:id="#+id/expenditureValueBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/expenditureValueText"
android:ems="10"
android:inputType="numberDecimal" >
<requestFocus />
</EditText>
<Button
android:id="#+id/saveExpenditureDetails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/expenditureValueBox"
android:text="Save"
android:onClick="saveExpenditure" /> <---- Can't find this
<Button
android:id="#+id/cancelExpenditureDetails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/saveExpenditureDetails"
android:layout_alignBottom="#+id/saveExpenditureDetails"
android:layout_alignRight="#+id/expenditureValueBox"
android:text="Cancel"
android:onClick="cancelExpenditure" />
</RelativeLayout>
Error:
09-15 21:12:37.411: E/AndroidRuntime(818): FATAL EXCEPTION: main
09-15 21:12:37.411: E/AndroidRuntime(818): java.lang.IllegalStateException: Could not find a method saveExpenditure(View) in the activity class android.view.ContextThemeWrapper for onClick handler on view class android.widget.Button with id 'saveExpenditureDetails'
09-15 21:12:37.411: E/AndroidRuntime(818): at android.view.View$1.onClick(View.java:3578)

E/AndroidRuntime(818): java.lang.IllegalStateException: Could not find a method saveExpenditure(View) in the activity class android.view.ContextThemeWrapper for onClick handler on view class android.widget.Button with id 'saveExpenditureDetails'
You will notice that the error message indicates that Android is looking for saveExpenditure(View) in android.view.ContextThemeWrapper, which is not your class. That's because your layout is being used by a dialog, not your activity directly. AFAIK, you will need to use setOnClickListener() to associate a listener with the Button in a Dialog.

Related

Getting nullpointer exception in Imageview of a layout file [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
Hello my problem is that i am getting a null pointer exception in my program i am getting a exception in a imageview of a layout file i am trying to make a firebase app so i use try-catch blocks for handling firebase error so i decided to make a beautiful dialog box but when i test it first time it runs but now it throws a null pointer exception so please help me here is my code and activities
:- my register activity
public class registerActivity extends Activity {
Dialog error_dialog_box_register;
TextView dialog_title_register, dialog_message_register;
ImageView dialog_main_image, dialog_cancel_image;
Button ok_button, login_button;
private Button RegisterButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
RegisterButton = findViewById(R.id.register_in_button);
RegisterButtonListener();
}
private void RegisterButtonListener() {
RegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CreateNewAccount();
}
});
}
private void CreateNewAccount() {
mAuth.createUserWithEmailAndPassword(Email, Password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Register_Progress_bar.setVisibility(View.GONE);
SendUserToDate_of_birthActivity();
} else {
try {
Register_Progress_bar.setVisibility(View.GONE);
throw Objects.requireNonNull(task.getException());
} catch (FirebaseAuthUserCollisionException f) {
ShowErrorPopup();
Toast.makeText(registerActivity.this, "User already exists", Toast.LENGTH_SHORT).show();
} catch (FirebaseNetworkException e) {
Toast.makeText(registerActivity.this, "Error network error", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
#SuppressLint("SetTextI18n")
private void ShowErrorPopup() {
error_dialog_box_register.setContentView(R.layout.custom_popup_p);
dialog_cancel_image = (ImageView) findViewById(R.id.Cancel_dialog_box_register);
ok_button = (Button) findViewById(R.id.dialog_ok_button_register);
login_button = (Button) findViewById(R.id.dialog_login_button_register);
dialog_title_register = (TextView) findViewById(R.id.Dialog_title_register);
dialog_message_register = (TextView) findViewById(R.id.dialog_message_register);
dialog_cancel_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
error_dialog_box_register.dismiss();
}
});
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SendUserToLoginActivity();
}
});
dialog_title_register.setText("Error");
dialog_message_register.setText("Email already exists please login or try again");
error_dialog_box_register.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
error_dialog_box_register.show();
}
}
Here is my xml file:-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="#+id/Cancel_dialog_box_register"
android:layout_width="46dp"
android:layout_height="38dp"
android:layout_alignParentEnd="true"
android:layout_marginTop="7dp"
android:layout_marginEnd="7dp"
android:elevation="5dp"
android:src="#drawable/ic_close_black_24dp"
/>
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
app:cardBackgroundColor="#color/ColorRed"
app:cardCornerRadius="15dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:layout_marginBottom="25dp"
android:orientation="vertical">
<TextView
android:id="#+id/Dialog_title_register"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:text=""
android:textAlignment="center"
android:textColor="#000000"
android:textSize="25sp"
android:textStyle="bold" />
<ImageView
android:id="#+id/dialog_main_image_register"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="10dp"
android:src="#drawable/ic_error_black_24dp" />
<TextView
android:id="#+id/dialog_message_register"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="20dp"
android:text=""
android:textAlignment="center"
android:textColor="#000000"
android:textSize="18sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/dialog_login_button_register"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp"
android:background="#drawable/login_b_custom"
android:text="#string/login"
android:textColor="#color/colorPrimaryDark"
android:textSize="15sp" />
<Button
android:id="#+id/dialog_ok_button_register"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginStart="15dp"
android:layout_marginTop="20dp"
android:background="#drawable/login_b_custom"
android:text="Ok"
android:textColor="#color/colorPrimaryDark"
android:textSize="15sp"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
And i am getting error like these
2019-08-03 15:52:13.840 5711-5711/? E/Zygote: isWhitelistProcess - Process is Whitelisted
2019-08-03 15:52:13.841 5711-5711/? E/Zygote: accessInfo : 1
2019-08-03 15:52:43.642 5711-5711/com.geetmp3.themusicapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.geetmp3.themusicapp, PID: 5711
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.geetmp3.themusicapp.AccountCreation.registerActivity.ShowErrorPopup(registerActivity.java:193)
at com.geetmp3.themusicapp.AccountCreation.registerActivity.access$300(registerActivity.java:34)
at com.geetmp3.themusicapp.AccountCreation.registerActivity$2.onComplete(registerActivity.java:146)
at com.google.android.gms.tasks.zzj.run(Unknown Source:4)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7076)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
Please reply me why i am getting null pointer exception and please help me
In your OnCreate function you assign your RegisterButton as:
RegisterButton = findViewById(R.id.register_in_button);
but in your layout you have two buttons with the IDs of:
android:id="#+id/dialog_login_button_register"
and
android:id="#+id/dialog_ok_button_register"
So your findViewById call returns with null because no button with the ID of register_in_button exists. Then you get an exception when you attempt to invoke the null object's method.
Please create variables reference by dialog because all ImageVeiw or textview are inside the dialog
error_dialog_box_register= new Dialog(this);
error_dialog_box_register.requestWindowFeature(Window.FEATURE_NO_TITLE);
error_dialog_box_register.setContentView(R.layout.custom_popup_p);
error_dialog_box_register.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
error_dialog_box_register.setCancelable(false);
dialog_cancel_image = error_dialog_box_register.findViewById(R.id.Cancel_dialog_box_register);

How to make a pop up image like an advertisement? [Android]

I've encountered a lot of pop up images like the example below, i've made a pop up image but there is no close button at the top left corner, do u guys have any idea how to make a pop up image with close button at the top left cornel like the example below in Android?
You need to make your own Dialog with your custom layout
Dialog dialog;
private void showDialog() {
// custom dialog
dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_dialog);
// set the custom dialog components - text, image and button
ImageButton close = (ImageButton) dialog.findViewById(R.id.btnClose);
Button buy = (Button) dialog.findViewById(R.id.btnBuy);
// Close Button
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
//TODO Close button action
}
});
// Buy Button
buy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
//TODO Buy button action
}
});
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
custom_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:background="#android:color/white"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/images" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<Button
android:id="#+id/btnBuy"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#android:color/holo_green_light"
android:text="BUY"
android:textColor="#android:color/white" />
<TextView
android:id="#+id/txtTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/btnBuy"
android:text="Thank You (Domestic Album Version)"
android:textColor="#android:color/black"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/txtTitle"
android:text="Still Not Gettin' Any, 2004" />
</RelativeLayout>
</LinearLayout>
<ImageButton
android:id="#+id/btnClose"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#android:color/black"
android:src="#android:drawable/ic_menu_close_clear_cancel" />
</RelativeLayout>
Result is:
You can use this library. There is close button on top right corner. only need to set image only.
https://github.com/chathuralakmal/AndroidImagePopup

EditText OnClick Exception

So I am making an app for an assignment.
Basically convert Miles to KM or KM to Miles.
I've now got the radio buttons working but when I add the onclick event, upon clicking the edittext fields I get an exception. :
java.lang.IllegalArgumentException:
Expected receiver of type a00891437.set3s.comp3975.convertunits.MainActivity,
but got android.support.v7.internal.widget.TintContextWrapper
Here is the code
package a00891437.set3s.comp3975.convertunits;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onRadioButtonClicked(final View view) {
View mText = findViewById(R.id.MilesText);
View kmText = findViewById(R.id.KilometersText);
if (view.getId() == R.id.KmToMButton) {
mText.setEnabled(false);
kmText.setEnabled(true);
}
if (view.getId() == R.id.MToKmButton) {
kmText.setEnabled(false);
mText.setEnabled(true);
}
}
public void onClickedText(final View view) {
Log.d("MainActivity", "Clicked");
}
}
The layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
android:id="#+id/screen">
TextView android:text="#string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="110dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/KilometersText"
android:layout_above="#+id/button"
android:layout_marginBottom="134dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:enabled="false"
android:onClick="onClickedText"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/MilesText"
android:layout_centerVertical="true"
android:layout_alignLeft="#+id/KilometersText"
android:layout_alignStart="#+id/KilometersText"
android:enabled="false"
android:onClick="onClickedText"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Km"
android:id="#+id/Kilometers"
android:layout_alignTop="#+id/KilometersText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="43dp"
android:layout_marginStart="43dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="M"
android:id="#+id/Miles"
android:layout_alignTop="#+id/MilesText"
android:layout_alignRight="#+id/Kilometers"
android:layout_alignEnd="#+id/Kilometers" />
<RadioGroup
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Kilometers to Miles"
android:id="#+id/KmToMButton"
android:layout_alignParentTop="true"
android:layout_alignLeft="#+id/MToKmButton"
android:layout_alignStart="#+id/MToKmButton"
android:checked="false"
android:onClick="onRadioButtonClicked"/>/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Miles to Kilometers"
android:id="#+id/MToKmButton"
android:layout_below="#+id/KmToMButton"
android:layout_alignLeft="#+id/Kilometers"
android:layout_alignStart="#+id/Kilometers"
android:checked="false"
android:onClick="onRadioButtonClicked"/>/>
</RadioGroup>
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="59dp"
android:layout_marginStart="59dp" />
</RelativeLayout>
You are specifying the onClick event method through XML, and it looks like this does not work with support library AppCompatActivity.
You should just get the reference to the EditText and call setOnClickListener().
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText kilometers = (EditText) findViewById(R.id.KilometersText);
kilometers.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
onClickedText(v);
}
});
// repeat this for the miles EditText
// you'll need to add an id for the radio group for this to work:
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio_group);
radioGroup.setOnCheckedChangedListener(new RadioGroup.OnCheckedChangedListener() {
// I leave the code inside here for you to do as an exercise
});
}

How to automatically go to next level in a game after completion of first level?

I'm trying to develop a riddle game with levels. First level is in "OneActivity.java" and "activity_one.xml" 2nd level on "TwoActivity.java" and "activity_two.xml" and so on. After the user types the answer to the question in level one, a toast display with "Correct" is displayed if the answer is correct and "Wrong" if it's incorrect. Now, how do I automatically go to next level if the answer is correct but remain on same level until the user inputs the correct answer. Here's my OneActivity.java and activity_one.xml
OneActivity.java:
package com.golo.user.gaunkhanekatha;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class OneActivity extends Activity {
public Button check;
public EditText typeh;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
check = (Button)findViewById(R.id.check); //R.id.button is the id on your xml
typeh = (EditText)findViewById(R.id.typeh); //this is the EditText id
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
//Here you must get the text on your EditText
String Answer = (String) typeh.getText().toString(); //here you have the text typed by the user
//You can make an if statement to check if it's correct or not
if(Answer.equals("4") || (Answer.equals("four")))
{
//Create a Toast because it's correct
Toast.makeText(OneActivity.this, "Correct!",
Toast.LENGTH_LONG).show();
}
else{
//It's not the correct answer
Toast.makeText(OneActivity.this, "Wrong! Try Again",
Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_aboutus, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_one.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
android:weightSum="1"
android:textAlignment="center"
android:id="#+id/oneque">
<TextView
android:layout_width="300dp"
android:layout_height="200dp"
android:text="What is 2+2?"
android:id="#+id/que"
android:width="255dp"
android:textSize="30dp"
android:layout_margin="50dp"
android:textStyle="italic"
android:gravity="center" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/typeh"
android:layout_gravity="center_horizontal"
android:text="Type Here" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check Answer"
android:id="#+id/check"
android:layout_gravity="center_horizontal" />
</LinearLayout>
activity_level.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">
<Button
android:id="#+id/button1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dp"
android:layout_weight="1"
android:onClick="moveToOneActivity"
android:background="#drawable/one" />
<Button
android:id="#+id/button2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dip"
android:layout_weight="1"
android:onClick="moveToTwoActivity"
android:background="#drawable/two" />
<Button
android:id="#+id/button3"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dip"
android:layout_weight="1"
android:onClick="moveToThreeActivity"
android:background="#drawable/three" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">
<Button
android:id="#+id/button4"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dp"
android:layout_weight="1"
android:onClick="moveToFourActivity"
android:background="#drawable/four" />
<Button
android:id="#+id/button5"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dip"
android:layout_weight="1"
android:onClick="moveToFiveActivity"
android:background="#drawable/five" />
<Button
android:id="#+id/button6"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dip"
android:layout_weight="1"
android:onClick="moveToSixActivity"
android:background="#drawable/six" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">
<Button
android:id="#+id/button7"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dp"
android:layout_weight="1"
android:onClick="moveToSevenActivity"
android:background="#drawable/seven" />
<Button
android:id="#+id/button8"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dip"
android:layout_weight="1"
android:onClick="moveToEightActivity"
android:background="#drawable/eight" />
<Button
android:id="#+id/button9"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dip"
android:layout_weight="1"
android:onClick="moveToNineActivity"
android:background="#drawable/nine" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">
<Button
android:id="#+id/button10"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dp"
android:layout_weight="1"
android:onClick="moveToTenActivity"
android:background="#drawable/ten" />
<Button
android:id="#+id/button11"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dip"
android:layout_weight="1"
android:onClick="moveToElevenActivity"
android:background="#drawable/eleven" />
<Button
android:id="#+id/button12"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dip"
android:layout_weight="1"
android:onClick="moveToTwelveActivity"
android:background="#drawable/twelve" />
</LinearLayout>
</LinearLayout>
if(Answer.equals("4") || (Answer.equals("four")))
{
//Create a Toast because it's correct
Toast.makeText(OneActivity.this, "Correct!",
Toast.LENGTH_LONG).show();
//Here create intent to the new activity - for example
//If you wish the user will have time to see the toast, you can use a Handler with post delayed
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent newLevel= new Intent(OneActivity.this, TwoActivity.class);
startActivity(newLevel);
finish(); //finish the activity of the current level
}
}, 3000); //the code inside run() will be executed after 3 seconds so the user can see the toast
}
else
{
//It's not the correct answer
Toast.makeText(OneActivity.this, "Wrong! Try Again",
Toast.LENGTH_LONG).show();
}
To go to the second level you should add this Intent inside your correct Toast as follows :
Intent i = new Intent(OneActivity.this, TwoActivity.class);
startActivity(i);
finish();
This should be your code :
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
//Here you must get the text on your EditText
String Answer = (String) typeh.getText().toString(); //here you have the text typed by the user
//You can make an if statement to check if it's correct or not
if(Answer.equals("4") || (Answer.equals("four")))
{
//Create a Toast because it's correct
Toast.makeText(OneActivity.this, "Correct! Going to Level 2...",
Toast.LENGTH_LONG).show();
Intent i = new Intent(OneActivity.this, TwoActivity.class);
startActivity(i);
finish();
}
else{
//It's not the correct answer
Toast.makeText(OneActivity.this, "Wrong! Try Again",
Toast.LENGTH_LONG).show();
}
}
});
EDIT
This edit will cancel the Toast when you are on your TwoActivity.class, you have to change some stuff, I'll exaplain to you.
1.- Create a global Toast variable.
private Toast toast;
2.- Initialize it on your onCreate() like this :
toast = Toast.makeText(OneActivity.this, "", Toast.LENGTH_SHORT);
3.- Then change your two Toast messages to this :
//Correct Toast
toast.setText("Correct! Going to Level 2...");
toast.show();
//Incorrect Toast
toast.setText("Wrong! Try Again");
toast.show();
4.- You want to make a finish() to avoid the back button to return to OneActivity() so you will call it, and it calls onDestroy() so you have to add this method aswell to cancel the Toast
#Override
protected void onDestroy() {
super.onDestroy();
if(toast!= null) {
toast.cancel();
}
}
You can use intents to switch to another activity.
Intent myIntent = new Intent(this, MyActivity.class);
startActivity(myIntent);
You could simply have an if statement. If the answer is correct, create an intent and start activity two, otherwise reloop in activity one or do whatever other behaviour you want to do if the answer is wrong.

nullpointerexception upon setOnClickListener

I have a button that brings up a dialog with an OK button, and I'm getting a nullpointerexception when I click on the OK button. Does anyone know what's wrong?
Here's my java code.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylist);
myListView = (ListView)findViewById(R.id.list);
new GetStuff().execute();
Button importButton = (Button)findViewById(R.id.doButton);
importButton.setEnabled(false);
importButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final Dialog pwdDialog = new Dialog(context);
pwdDialog.setContentView(R.layout.pwdentry);
pwdDialog.setTitle("Enter password");
TextView pwdText = (TextView)pwdDialog.findViewById(R.id.pwdText);
pwdText.setText("Enter password");
Button okBut = (Button)findViewById(R.id.okBut);
okBut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pwdDialog.dismiss();
}
});
pwdDialog.show();
}
});
}
Here's the XML file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/pwdText"
android:layout_width="fill_parent"
android:layout_height="50dip"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Enter password"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/pwdEntry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/pwdText"
android:ems="10"
android:inputType="numberPassword" >
<requestFocus />
</EditText>
<Button
android:id="#+id/okBut"
style="?android:attr/buttonStyleSmall"
android:layout_width="100px"
android:layout_height="wrap_content"
android:layout_below="#+id/pwdEntry"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:text="OK" />
</RelativeLayout>
Thanks!
The problem is okBut will be null
Button okBut = (Button)findViewById(R.id.okBut);
you need to make this as
Button okBut = (Button)pwdDialog.findViewById(R.id.okBut);
Here you are retrieving a Button by using the id, R.id.okBut from your main layout R.layout.mylist.
Button okBut = (Button)findViewById(R.id.okBut);

Categories