How to make toast message when button is clicked - java

I'm creating a quiz. I have 3 buttons (options) in the activity and its corresponding questions. Now, my problem is I want to show the toast message, when the user chose the correct answer the toast message will appear in a few seconds, but when the user choose the wrong answer it will again display the toast message. I do not know how to do that.
I have done many research and read forums, but seems I don't understand and it don't meet my needs. Can someone please help? thanks in advance!
So far, here is the code. But it doesn't work.
Please correct me which code is wrong. Thanks deeply.
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Button btn1 = (Button) findViewById(R.id.btnopt1_a);
btn1.isClickable();
switch(arg0.getId()){
case R.id.btnopt1_a:
if(btn1.isPressed()){
Toast.makeText(getBaseContext(), "Your answer is correct!" , Toast.LENGTH_SHORT ).show();
}
else btn1.setText("Your answer is wrong!, The correct answer is: Frog");
break;
}
}
});

To show toast message when you click button, use the following code. If you want to do some validations then use the code in your onclicklistener of button:
Button btn1 = (Button) findViewById(R.id.btnopt1_a);
btn1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getBaseContext(), "Your answer is correct!" , Toast.LENGTH_SHORT ).show();
}
});

Try this, First implements Your Activity OnClickListener . And then each end every click check condition you will get solution.
public class Deals extends Activity implements OnClickListener {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.yourxml);
//declare ur buttons here
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.menu: {
// Do your stuff here
// call method
if (isright) {
Toast.makeText(getBaseContext(), "Your answer is correct!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Your answer wrong!", Toast.LENGTH_SHORT ).show();
}
}
}
}
}

If you have many conditions in which you have to show toast. Then it would be better to make a method which shows it.
private void showToast(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}
And call the above method in the onClick() or wherever you want to show.
btn1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
..................
..........................
case R.id.btnopt1_a:
if (btn1.isPressed()) {
showToast("Your answer is correct!");
} else {
showToast("Your answer is wrong!, The correct answer is: Frog");
}
break;
});

Related

Alert Dialogue Box for Forget Password

The dialog box just works fine but as soon as I leave an empty field in the textfield ( for email) I get returned back to Login Activity. How can I keep showing the Dialogue Box without going back. How can I create a condition for Empty Email Field.
forgetPass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText resetMail = new EditText(v.getContext());
final AlertDialog.Builder passwordResetDialog = new AlertDialog.Builder(v.getContext());
passwordResetDialog.setTitle("Reset Password?");
passwordResetDialog.setMessage("Enter Your Email To Receive The Reset Link");
passwordResetDialog.setView(resetMail);
passwordResetDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String mail = resetMail.getText().toString().trim();
if (TextUtils.isEmpty(mail)) {
Toast.makeText(getApplication(), "Enter Valid Email Address.", Toast.LENGTH_SHORT).show();
return;
} else {
fAuth.sendPasswordResetEmail(mail).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(Login.this, "Reset Link Sent To Your Email.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Login.this, "Error ! Reset Link Not Sent." + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
});
passwordResetDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Close The Dialog Box
}
});
passwordResetDialog.create().show();
}
});
First i will suggest you to create your own layout of dialog in which there should be close button to close the dialog and then add this line
passwordResetDialog.setCancelable(false);
this will prevent the dialog to close and use this function dismiss();on the click of that cross/cancel button to close the dialog.
I would suggest that you build your own Dialog with your own Buttons
then you can use the button without dismiss
Button b1 = (Button) dialog.findViewById(R.id.dialog_bt_yes);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//your code with no dismiss
}
});
Button b2 = (Button) dialog.findViewById(R.id.dialog_bt_no);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// close dialog
dialog.dismiss();
}
});
when you are using Alert Dialog it's not possible to click the positive or negative button and not finishing the dialog. Use DialogFragment to manage the dialog ensures that it correctly handles lifecycle events such as when the user presses the Back button or rotates the screen. using custom Dialog Fragment it's a bit harder but it's more flexible
see the link to see how to have custom Dialogs:
https://guides.codepath.com/android/using-dialogfragment

Have to click twice to get previous array element

I want to make a gallery app with previous and next button. I made an array of photos. Whenever I reached the last photo, I have to click the previous button twice to get the previous photo. And also when I get to the first photo, I have to click the next button twice to get to the next photo. My code:
public class MainActivity extends AppCompatActivity {
ImageView ivphoto;
Button btnext;
Button btprevious;
int a=0;
int photoarray[]={R.drawable.cat, R.drawable.dog, R.drawable.duck, R.drawable.elephant, R.drawable.monkey, R.drawable.pig, R.drawable.rabbit, R.drawable.tiger};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ivphoto = findViewById(R.id.ivphoto);
btnext = findViewById(R.id.btnext);
btprevious = findViewById(R.id.btprevious);
btnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ivphoto.setImageResource(photoarray[a]);
a++;
if (a==8){
a=7;
Toast.makeText(MainActivity.this, "This is last photo", Toast.LENGTH_SHORT).show();
}
}
});
btprevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ivphoto.setImageResource(photoarray[a]);
a--;
if(a==-1){
a=0;
Toast.makeText(MainActivity.this, "This is first photo.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Any one please help me with this. Thanks.
Try this code in next button:
if(a == photoarray.lenght - 1)
Toast.makeText(MainActivity.this, "This is last photo", Toast.LENGTH_SHORT).show();
else
ivphoto.setImageResource(photoarray[++a]);
And this code in back button:
if(a == 0)
Toast.makeText(MainActivity.this, "This is first photo.", Toast.LENGTH_SHORT).show();
else
ivphoto.setImageResource(photoarray[--a]);
The error is in this line:
btnext:
if (a==8){
a=7;
Toast.makeText(MainActivity.this, "This is last photo", Toast.LENGTH_SHORT).show();
}
If a is 8, it becomes 7. Then on clicking btprevious, image 7 is displayed again, then a becomes 6. On the next click, a becomes 5, and image 6 is shown.
A similar error is present in btprevious.
You need to changea before changing the image.

Why is does this Toast(Android Studio) works only at the second click

I have made a EditText clickable, and I in the Java class I made this private void:
private void incaseofclick() {
EditText Ct=(EditText) findViewById(R.id.CODIGOnumero);//The EditText
Ct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),R.string.INDICA3, Toast.LENGTH_LONG).show();//
}
});
}
... The problem is that, in the emulator, I have to press twice(EditText) for the toast to work, I want to know why, and how to fix it...
Summarized: What I want is to press it once and the toast and the keyboard(Not a problem) to appear
.
Why don't you do it just like this?
private void incaseofclick() {
Toast.makeText(getApplicationContext(),R.string.INDICA3, Toast.LENGTH_LONG).show();
}

Getting rid of "==" syntax error in android

The elseif(v == button2) line gives an error saying that "Syntax error on token '==', delete this token". I got the idea of using this from the topic "Variable OnClick listener android" from this website. Can anyone please tell me how to use it?
Here is my code:
View.OnClickListener yourListener = new View.OnClickListener(){
public void onClick(View v){
if( v == button1){
new AlertDialog.Builder(this)
.setTitle("Paracettamol")
.setMessage("This medicine is generally used to cure Fever")
.setNeutralButton("OK", null)
.show();}
}
elseif( v == button2){
new AlertDialog.Builder(this)
.setTitle("sertraline")
.setMessage("This medicine is generally used to cure Head aches")
.setNeutralButton("OK", null)
.show();
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
} ;
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
The answer of the asked question mentioned above has the following code:
Button btn1, btn2;
public void onCreate(Bundle b)
{
// here you do normal things like assigning a
// content view to the activity, initiate buttons, etc.
// then you assign the same listener to both buttons
btn1.setOnClickListener(yourListener);
btn2.setOnClickListener(yourListener);
}
// declare a OnClickListener that will execute different actions
// depending on the view that was clicked
View.OnClickListener yourListener = new View.OnClickListener(){
public void onClick (View v){
if( v == btn1 ){
// do something
}
elseif( v == btn1 ){
// do another thing
}
}
};
You might missed space between else and if - "elseif( v == button2) "
ah...
Your code sample is a mess...
I've re-formatted it and correct errors. Now it should work.
View.OnClickListener yourListener = new View.OnClickListener() {
public void onClick(View v) {
if (v == button1) {
new AlertDialog.Builder(v.getContext())
.setTitle("Paracettamol")
.setMessage(
"This medicine is generally used to cure Fever")
.setNeutralButton("OK", null).show();
} else if (v == button2) {
new AlertDialog.Builder(v.getContext())
.setTitle("sertraline")
.setMessage(
"This medicine is generally used to cure Head aches")
.setNeutralButton("OK", null).show();
}
}
};
Could you be more accurate asking question next time?

Android/ Java closure onClick problem?

Here is basically my code:
private Dialog mDialog;
private BluetoothAdapter mBluetoothAdapter;
...
private void onCreate(Bundle savedInstanceState) {
...
enabltBTButton = getMyButton();
enableBtButton.setOnClickListener(this.enableBT);
...
}
...
public View.OnClickListener enableBT = (new View.OnClickListener() {
public void onClick(View view) {
mDialog.hide();
mBluetoothAdapter.enable();
Toast.makeText(Main.this, "Bluetooth enabled", Toast.LENGTH_LONG).show();
return;
}
});
The problem: when I click the button nothing happens! I am positive that enableBTButton is referring to the correct object, but my guess is that this has something to do with my referencing mDialog and mBluetoothAdapter, both of which are declared outside of the inner onClick function.
What is an alternative solution to this?
In the pasted code you have:
private void onCreate()
but it should be:
protected void onCreate (Bundle savedInstanceState)
If it really is a "private onCreate()" in your code, then it won't get called by the framework because it doesn't override Activity.onCreate(Bundle), which means the onClickListener is not set up for your button either.
I think the problem is that you are calling a function setOnClickEventListener, but you should be calling setOnClickListener. Is setOnClickEventListener a function you wrote?
(By the way, you can test your guess about referencing mDialog and/or mBluetoothAdapter by commenting out those lines. I don't think that's the problem.)
Rather then keep fumbling with what I had, I decided that to use an AlertDialog, which seems to get the job done quite well. Thank you everyone for your solutions.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Bluetooth is not enabled...")
.setCancelable(false)
.setPositiveButton("Enable it!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getApplicationContext(), "Bluetooth enabled", Toast.LENGTH_LONG).show();
...
}
})
.setNegativeButton("Leave it!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getApplicationContext(), "Bluetooth still disabled", Toast.LENGTH_LONG).show();
}
});
AlertDialog mAlert = builder.create();
mAlert.show();

Categories