How to delete data by selecting a particular button - java

I am working with android. I want to delete the particular button that i have selected.. I am using onContextItemSelected for selecting the button.What do I write inside
public void onClick(DialogInterface dialog,int id) {} of setPositiveButton??
#Override
public boolean onContextItemSelected(MenuItem item)
{
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
String number;
final Context context = this;
try
{
//number=new ContactListAdapter (this).numberList.get(info.position);
if(item.getTitle()=="View ")
{
Dialog dialog=new Dialog(HubActivity.this);
dialog.setContentView(R.layout.driver_details);
dialog.setTitle("Driver Details");
dialog.show();
}
else if(item.getTitle()=="Edit ")
{
Dialog dialog=new Dialog(HubActivity.this);
dialog.setContentView(R.layout.activity_driver);
dialog.setTitle("Edit Details");
dialog.show();
}
else if(item.getTitle()=="Delete ")
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Delete");
// set dialog message
alertDialogBuilder
.setMessage("Are you sure to delete ?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
//MainActivity.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}

If you have defined the button in your xml layout, you cannot delete it but you can remove it from the view by setting (and this is the most common case):
// Button button = findViewById(R.id.button);
button.setVisibility(View.GONE);
The above line will go inside your public void onClick(DialogInterface dialog,int id) {}.
If you have added the button dynamically within the code, you can remove it by getting the parent layout and doing:
ViewGroup.removeView(button);

Related

The button that I have created does not work. Is there something wrong with my code?

I am building an app in Android studio and basically I want a window to popup when a user clicks the add button. I used the setOnClickListener but when I run the app, nothing happens. Could there possibly something wrong with my code?
Here's my MainActivity code
public class MainActivity extends AppCompatActivity {
Button addBtn;
ListView itemListView;
DatePickerDialog.OnDateSetListener dateSetListener;
String dateString = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addBtn = (Button)findViewById(R.id.addBtn);
itemListView = (ListView)findViewById(R.id.itemListView);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
View view = getLayoutInflater().inflate(R.layout.activity_popup_window, null);
EditText itemName = (EditText)view.findViewById(R.id.itemName);
Button expirationDateBtn = (Button)view.findViewById(R.id.expirationDateBtn);
builder.setView(view)
.setTitle("Add Item")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (itemName.getText().toString().isEmpty() || dateString == null) {
Toast.makeText(MainActivity.this,
"Item name or expiration date is missing",
Toast.LENGTH_LONG).show();
}
else{
//do action
}
}
});
//when clicked on Expiration Date Btn
//display date on button
AlertDialogBuilder doesn't create and show a new AlertDialog implicitly. It only prepares the dialog before explicitly calling create() (or you can directly call show() if you need to display your dialog in the moment it gets built).
Your code misses the following lines at the end of onClick():
AlertDialog dialog = builder.create();
dialog.show();
or just:
builder.show();

Prevent AlertDialog from closing when EditText is empty

So without having to create a custom dialog as I currently have a number of dialog layouts and don't want to have to do it for each one, is there a way to prevent this dialog from closing when the positive button is pressed and the EditText is empty?
Currently it closes the dialog every time I hit enter and there is nothing in the EditText field.
public AlertDialog webpageDialog() {
AlertDialog.Builder webpageDialogBuilder = new AlertDialog.Builder(context);
LayoutInflater inflater = LayoutInflater.from(context);
webpageDialogBuilder.setView(inflater.inflate(R.layout.dialog_webpage, null))
.setNegativeButton(context.getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
final AlertDialog webpageDialog = webpageDialogBuilder.create();
webpageDialog.setButton(DialogInterface.BUTTON_POSITIVE, context.getString(R.string.enter), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
EditText webpageInput = (EditText) webpageDialog.findViewById(R.id.dw_et_webpage_address);
Log.d(TAG, "Positive on click");
if(TextUtils.isEmpty(webpageInput.getText().toString())){
Log.d(TAG, "Edit text empty");
webpageInput.setError(context.getString(R.string.error_web_required));
} else {
Log.d(TAG, "Edit text not empty");
ms.setUriString("http://" + webpageInput.getText().toString());
ms.returnWithResult(1);
dialog.cancel();
}
Log.d(TAG, "Returning");
}
});
Log.d(TAG, "Returning dialog");
return webpageDialog;
}
this is how I'm doing it.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
EditText yourEditText = new EditText(this);
layout.addView(yourEditText);
builder.setView(layout);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
final AlertDialog dialog = builder.create();
dialog.show();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ("".equals(yourEditText.getText().toString().trim())) {
//this will stop your dialog from closing
yourEditText.setError("This field is required!");
return;
}
//you logic here
dialog.dismiss();
}
});
I hope following line can help,
webpageDialogBuilder.setCancelable(false);

Alert Dialog was disappearing when user clicks out side

Hi everyone i have a alert box with two text box's, and here the problem is the alert dialog was disappearing when user clicks outside of that pop up or the Alert dialog is disappearing when user clicks Ok button too.
So please help me in this regards
Thanks in advance...
final AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Sign In Failed");
final EditText input1=new EditText(MainActivity.this);
final EditText input2=new EditText(MainActivity.this);
input1.setHint("eNTER name1");
input2.setHint("Enter Name2");
LinearLayout linearLayout= new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
builder.setMessage("Invalid username or password");
linearLayout.addView(input1);
linearLayout.addView(input2);
builder.setView(linearLayout);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
because by default it is Cancelable
Add this after builder.setView(linearLayout) -
builder.setCancelable(false);
UPDATE
As per your code snippet below-
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
on positive button ("OK") click, you are setting dialog.cancel() Don't do this, you should set some action as you required on positive button click.
See This :
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel(); // close the current dialog
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Perform any Intent Action or perform validation as you want
}
});
UPDATE 2
Just copy & paste below code - working perfectly
final EditText input1 = new EditText(MainActivity.this);
final EditText input2 = new EditText(MainActivity.this);
input1.setHint("Enter name1");
input2.setHint("Enter Name2");
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.addView(input1);
linearLayout.addView(input2);
final AlertDialog builder = new AlertDialog.Builder(MainActivity.this)
.setTitle("Sign In Failed")
.setCancelable(false)
.setMessage("Invalid username or password").setView(linearLayout).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).create();
builder.show();
builder.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (input1.length() <= 0) {
Toast.makeText(MainActivity.this, "Please Enter Name", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "OK", Toast.LENGTH_SHORT).show();
builder.dismiss();
}
}
});
You need to set outside touch false try this:
setCanceledOnTouchOutside(false);
Simply set cancelable false:
.setCancelable(false)

How do I code for user input in an alert dialog for an android app?

I have an android app that has two buttons. So basically what I am trying to do is when a user clicks the 'Share Button' on the page, an alert dialog box will appear that will prompt the user to enter their email address. Here is what I have so far. I've tried an EditView but it hasn't been working well for me.
Thanks in advance!
package com.colors;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
final Context context = this;
private Button button;
private Button shareButton;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
shareButton = (Button) findViewById(R.id.shareButton);
// add button listener for Welcome Message.
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set the title of the Alert Dialog
alertDialogBuilder.setTitle("Welcome!");
// set dialog message
alertDialogBuilder
.setMessage("Program Description here...")
.setCancelable(false)
.setNegativeButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// if no is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
// Button listener for Share Button
shareButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set the title of the Alert Dialog
alertDialogBuilder.setTitle("Share");
// set dialog message
alertDialogBuilder
.setMessage("Would like to a user input here.")
.setCancelable(false)
.setPositiveButton("Send!",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// if no is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// if no is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
}
}
This may helpful to you.
shareButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder al1 = new Builder(
AgriListView.this);
al1.setMessage("Share Something");
al1.setPositiveButton("Share",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
final EditText input = new EditText(
AgriListView.this);
input.setSingleLine();
AlertDialog.Builder al = new Builder(
AgriListView.this);
al.setTitle("Enter New Value");
al.setView(input);
al.setCancelable(true);
al.setIcon(R.drawable.bt);
al.setPositiveButton(
"OK",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
int len = input
.length();
if (!(len == 0)) {
Toast.makeText(
AgriListView.this,
"Entered text is: "+input.getText()
,
Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(
getApplicationContext(),
"Enter Value Properly",
Toast.LENGTH_LONG)
.show();
}
}
});
al.setNegativeButton(
"Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
dialog.cancel();
}
});
AlertDialog alert = al.create();
alert.show();
}
});
al1.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
dialog.cancel();
}
});
AlertDialog alert1 = al1.create();
alert1.show();
}
});
This code create dialog with Edittext value.
You could do something like this.
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Title");
alert.setMessage("Message");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText();
// Do something with value!
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();

How do you disable a button inside of an AlertDialog?

I am trying to write an AlertDialog with 3 buttons. I want the middle, Neutral Button to be disabled if a certain condition is not met.
Code
int playerint = settings.getPlayerInt();
int monsterint = settings.getMonsterInt();
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setMessage("You have Encountered a Monster");
alertbox.setPositiveButton("Fight!",
new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
createMonster();
fight();
}
});
alertbox.setNeutralButton("Try to Outwit",
new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
// This should not be static
// createTrivia();
trivia();
}
});
// Return to Last Saved CheckPoint
alertbox.setNegativeButton("Run Away!",
new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
runAway();
}
});
// show the alert box
alertbox.show();
// Intellect Check
Button button = ((AlertDialog) alertbox).getButton(AlertDialog.BUTTON_NEUTRAL);
if(monsterint > playerint) {
button.setEnabled(false);
}
}
The line:
Button button = ((AlertDialog) alertbox).getButton(AlertDialog.BUTTON_NEUTRAL);
Gives error:
Cannot cast from AlertDialog.Builder to AlertDialog
How do I fix this?
You can't call getButton() on the AlertDialog.Builder. It has to be called on the resulting AlertDialog after creation. In other words
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
//...All your code to set up the buttons initially
AlertDialog dialog = alertbox.create();
Button button = dialog.getButton(AlertDialog.BUTTON_NEUTRAL);
if(monsterint > playerint) {
button.setEnabled(false);
}
The builder is just a class to make constructing the dialog easier...it isn't the actual dialog itself.
HTH
Better solution in my opinion:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setPositiveButton("Positive", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// some code
}
});
AlertDialog alertDialog = builder.create();
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
if(**some condition**)
{
Button button = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
if (button != null) {
button.setEnabled(false);
}
}
}
});
The trick is that you need to use the AlertDialog object retuned by AlertDialog.Builder.show() method. No need to call AlertDialog.Builder.create().
Example:
AlertDialog dialog = alertbox.show();
if(monsterint > playerint) {
Button button = dialog.getButton(AlertDialog.BUTTON_NEUTRAL);
button.setEnabled(false);
}

Categories