Would it be possible to close an AlertDialog without having to click on/set a PositiveButton/NegativeButton?
Delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.DeleteRecord(_id);
db.close();
Snackbar.make(textEntryView, "Removed", Snackbar.LENGTH_LONG).setDuration(700).show();
}
});
Using a custom button added to my layout I want to click on it and have it close the AlertDialog aswell.
I have a total of 3 buttons currently
Update Record
Delete Record
Done (This one is using alert.setPositiveButton)
The other two I added in my layout so I could use Snackbar alert and I know I can do this by using setNeutralButton but it won't show a SnackBar alert.
I this code will work-
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
final FrameLayout customView= (FrameLayout) View.inflate(this, R.layout.custome_view, null);
final Button button = (Button) customView.findViewById(R.id.my_button);
button.setText(mTvEmail.getText().toString());
builder.setView(customView);
final AlertDialog alertDialog = builder.create();
alertDialog.show();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
To make it easier this is the whole thing
private void CreatePopup(Long id) {
final LayoutInflater Manual = LayoutInflater.from(this);
final View textEntryView = Manual.inflate(update, null);
final EditText infoData = (EditText) textEntryView.findViewById(R.id.InfoData);
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
final TextView TextSet = (TextView) textEntryView.findViewById(R.id.product);
final Button Accept = (Button) textEntryView.findViewById(R.id.button);
final Button Delete = (Button) textEntryView.findViewById(R.id.delete);
final SQLite db = new SQLite(this);
final Long _id = id;
final SQLiteDatabase X = db.getReadableDatabase();
final Cursor c;
c = X.rawQuery("SELECT Product FROM Inventory WHERE _id =" + _id, null);
c.moveToFirst();
final String Data = c.getString(c.getColumnIndexOrThrow("Product"));
TextSet.setText(Data);
c.close();
Accept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (infoData.length() != 0) {
final Editable Data = infoData.getText();
db.UpdateRecord(Data, _id);
db.close();
Snackbar.make(textEntryView, "Updated", Snackbar.LENGTH_LONG).setDuration(700).show();
}
else {
Toast toast = Toast.makeText(getApplicationContext(),
"Input Quantity!", Toast.LENGTH_SHORT);
toast.show();
}
}});
Delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.DeleteRecord(_id);
db.close();
Snackbar.make(textEntryView, "Removed", Snackbar.LENGTH_LONG).setDuration(700).show();
}
});
alert.setTitle("Update Quantity").setView(textEntryView);
alert.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
CreateListView();
}
});
alert.show();
}
Related
I have been trying to debug the issue of an alert dialog not opening on click of an image button when certain options in a spinner are selected.
The below is my MainActivity.java file which includes the relevant code for the alert dialog (left out code for the spinner as this is working as intended), any help would be much appreciated!
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialise Inputs & Fields
this.UnitSelector();
Spinner spinner = (Spinner) findViewById(R.id.options_spinner);
// UI Relationships
ImageButton tapeButton = (ImageButton)findViewById(R.id.imageButton_tape);
Log.d("SpinnerValue", spinner.getSelectedItem().toString());
EditText editText = (EditText) findViewById(R.id.value);
String message = editText.getText().toString();
// Listeners & Actions
tapeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String spinnerValue = spinner.getSelectedItem().toString();
// float messageFloat = Float.parseFloat(message);
Log.d("Button Clicked", spinnerValue);
if (spinnerValue == "Kilogram" || spinnerValue == "Celsius"){
createDialog("Nah mate", "Okay", MainActivity.this);
}
}
});
}
void createDialog( String title, String msg, Context context){
AlertDialog.Builder builder
= new AlertDialog
.Builder(context);
// Set the message show for the Alert time
builder.setMessage(msg);
// Set Alert Title
builder.setTitle(title);
// Set Cancelable false
// for when the user clicks on the outside
// the Dialog Box then it will remain show
builder.setCancelable(true);
builder.setNeutralButton("Yes", new DialogInterface.OnClickListener() {
#Override public void onClick(DialogInterface dialog, int which){
dialog.cancel();
}
});
// Create the Alert dialog
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
I think you forgot to set the adapter
Spinner spinner = (Spinner) findViewById(R.id.options_spinner);
String[] values = {"Kilogram","Celsius","other"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,values);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
ImageButton tapeButton = (ImageButton)findViewById(R.id.imageButton_tape);
tapeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String spinnerValue = spinner.getSelectedItem().toString();
if (spinnerValue.equals("Kilogram") || spinnerValue.equals("Celsius")){
createDialog("Nah mate", "Okay", MainActivity.this);
}
}
});
I want to make button when I click on it a dialog appears and I read data from that dialog. In the dialog I have only EditText for data. My data is numbers.
Here is my code:
Button mSaveButton = (Button) findViewById(R.id.saveButton);
mSaveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(ReportActivity.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_for_percent , null);
EditText savingsDialog = (EditText) mView.findViewById(R.id.percentEditText);
mBuilder.setView(mView)
.setPositiveButton(R.string.done, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Context context = getApplicationContext();
Toast.makeText(context, "Done", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog dialog = mBuilder.create();
dialog.show();
//if (savingsDialog.getText().toString().length() > 0) { I tried this if, but I receive empty data
SharedPreferences savings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = savings.edit();
editor.putString("percent", savingsDialog.getText().toString());
editor.commit();
updateSavingsView(Integer.parseInt(savingsDialog.getText().toString()));// here I want to put my data in method which update my TextView
//}
}
});
Method(if you need it)
public void updateSavingsView(int savings){
TextView savingsTextView = (TextView) findViewById(R.id.saverTextView);
savingsTextView.setText("Save " + savings + "% per month");
TextView monthlySavings = (TextView) findViewById(R.id.savingsMoney);
if(savings == 0 || Integer.parseInt(income.getText().toString()) == 0 ) {
monthlySavings.setText("0");
}
else{
monthlySavings.setText(Integer.toString((Integer.parseInt(income.getText().toString()) * savings) / 100));
}
So the problem is that when I run program without if statement I have an error java.lang.NumberFormatException: For input string: "" . It is because it reads empty string and want to parse it. Then I add if statement to avoid this problem but it doesn't work.
And my question is. How I can rewrite this listener to avoid these problems and to store correct data?
Put your code inside the positive listener
Button mSaveButton = (Button) findViewById(R.id.saveButton);
mSaveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(ReportActivity.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_for_percent , null);
final EditText savingsDialog = (EditText) mView.findViewById(R.id.percentEditText);
mBuilder.setView(mView)
.setPositiveButton(R.string.done, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Context context = getApplicationContext();
Toast.makeText(context, "Done", Toast.LENGTH_SHORT).show();
SharedPreferences savings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = savings.edit();
editor.putString("percent", savingsDialog.getText().toString());
editor.commit();
updateSavingsView(Integer.parseInt(savingsDialog.getText().toString()));
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog dialog = mBuilder.create();
dialog.show();
}
}
});
i have problem that i cannot call dialog method from another activity, the dialog get user input into sharedprefrnces
here my activity that i want check if theres stored sharedprefernce if not exist i want the dialog appear to get the user input and after i click ok its continue running the main activity
here the main
public class main extends Activity {
private Button button;
private EditText CardNumber;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkid();
}
});
}
public void checkid(){
File f = new File(
"/data/data/com.example.ahmed_samir.enjaz/shared_prefs/MyPrefs.xml");
if (f.exists())
Toast.makeText(OpreatorMobily.this, "exist:", Toast.LENGTH_LONG).show();
else {
NationalId na= new NationalId();
na.dialogmethod();
}
}
}
and here my second activity of dialog
public class NationalId extends Activity {
public static final String MyPREFERENCES = "MyPrefs";
public static final String Name = "nameKey";
SharedPreferences sharedpreferences;
final Context context = this;
private Button button;
private TextView result;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_national_id);
dialogmethod();
// components from main.xml
button = (Button) findViewById(R.id.button1);
result = (TextView) findViewById(R.id.tv1);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
// add button listener
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dialogmethod();
}
});
}
public void dialogmethod(){
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompts, null);
android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String n = userInput.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.commit();
// edit text
result.setText(userInput.getText());
Toast.makeText(NationalId.this, "saved:" + n, Toast.LENGTH_LONG).show();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
android.app.AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
}
You should not do this. A possible solution is to create a separate class which contains a static method for your dialog.
So in your activity you can call it like this:
Dialog myDialog = CustomDialog.createDialog(this);
myDialog.show();
Inside the static method:
public static Dialog createDialog(Context context) {
Dialog dialog = new Dialog(this);
//do all the initialization stuff
//return the dialog
return dialog;
}
I have written a function to handle showing of Dialog but I am not able to use OnClickListener in it. What is wrong with my code can any one tell me?
Here is my function
private void showInputDialog() {
final Dialog dialog=new Dialog(MainDashboard.this);
dialog.setContentView(R.layout.frg_dialog_change_pass);
btn_save_password=(Button) findViewById(R.id.btn_save_password);
btn_cancel_pass=(Button) findViewById(R.id.btn_cancel_pass);
edtOldpass=(EditText) findViewById(R.id.edtOldpass);
edtNewpass=(EditText) findViewById(R.id.edtNewpass);
edtConfirmpass=(EditText)findViewById(R.id.edtConfirmpass);
dialog.show();///Show the dialog.
btn_save_password.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainDashboard.this, "Success", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
}
Calling Activity.findViewById() will look for the View in the layout of your Activity (the one you've set by calling setContentView() in onCreate()).
I guess those Views are in your Dialog layout, so you need to call findViewById() on your Dialog instance:
btn_save_password = (Button) dialog.findViewById(R.id.btn_save_password);
btn_cancel_pass = (Button) dialog.findViewById(R.id.btn_cancel_pass);
edtOldpass = (EditText) dialog.findViewById(R.id.edtOldpass);
edtNewpass = (EditText) dialog.findViewById(R.id.edtNewpass);
edtConfirmpass = (EditText) dialog.findViewById(R.id.edtConfirmpass);
// Declare this globally above oncreate
private android.app.AlertDialog dialog;
android.app.AlertDialog.Builder alertDialog = new android.app.AlertDialog.Builder(MainDashboard.this);
LayoutInflater layoutInflater = getLayoutInflater();
View alertView = layoutInflater.inflate(R.layout.frg_dialog_change_pass, null);
alertDialog.setView(alertView);
alertDialog.setCancelable(false);
Button btn_save_password= (Button) alertView.findViewById(R.id.btn_save_password);
btn_save_password.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do your stuff here
}
});
if(dialog !=null)
dialog.dismiss();
dialog = alertDialog.create();
dialog.show();
Change your function to:
private void showInputDialog() {
final Dialog dialog=new Dialog(MainDashboard.this);
View view = LayoutInflater.from(MainDashboard.this).inflate(R.layout.frg_dialog_change_pass);
dialog.setContentView(view);
btn_save_password=(Button) view.findViewById(R.id.btn_save_password);
btn_cancel_pass=(Button) view.findViewById(R.id.btn_cancel_pass);
edtOldpass=(EditText) view.findViewById(R.id.edtOldpass);
edtNewpass=(EditText) view.findViewById(R.id.edtNewpass);
edtConfirmpass=(EditText)view.findViewById(R.id.edtConfirmpass);
dialog.show();///Show the dialog.
btn_save_password.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainDashboard.this, "Success", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
}
Basically you have to use findViewById with the view which is used for dialog .
When I click the calculate button for the first time it works fine but on the second click after the Result Dialog has been dismissed the app crashes.logcat shows the error The specified child already has a parent. You must call removeView on the child's parent first. What should I do now? and how do I add the removeView?
public class MainActivity extends Activity {
float Remaining,Departure,TotUplift,SG,DiscResult;
int CalUpliftResult;
TextView RemainingTV,DepartureTV,UpliftTV,SGtv,CalcUpliftTV,DiscrepancyTV,resultOne,resultTwo;
EditText RemainingET,DepartureET,TotUpliftET,SGet,CalcUpliftET,DiscrepancyET;
Button calculateButton,okButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupView();
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.dialog,null);
resultOne=(TextView)textEntryView.findViewById(R.id.resultOne); //resultone is a textview in xml dialog
resultTwo=(TextView)textEntryView.findViewById(R.id.resultTwo);
alert.setTitle("RESULT");
alert.setIcon(R.drawable.ic_launcher);
alert.setView(textEntryView);
alert.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(validationET())
{
getETvalue();
evaluation();
CalcUpliftTV.setText(String.valueOf(CalUpliftResult));
DiscrepancyTV.setText(String.valueOf(DiscResult));
resultOne.setText("Calc. Uplift (KG)= "+String.valueOf(CalUpliftResult));
resultTwo.setText("Discrepancy(%)= "+String.valueOf(DiscResult));
alert.show();
}
else
Toast.makeText(getApplicationContext(), "please give all inputs", Toast.LENGTH_SHORT).show();
}
});
}
I fixed it, the alertdialog must be created inside the onclick of the calculate button, so that each time I click it, the dialog gets created all over again thus preventing interference from previous dialog values. here's the corrected code segment:
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(validationET())
{
final AlertDialog.Builder alert = new AlertDialog.Builder(context);
LayoutInflater factory = LayoutInflater.from(context);
final View textEntryView = factory.inflate(R.layout.dialog,null);
resultOne=(TextView)textEntryView.findViewById(R.id.resultOne); //resultone is a textview in xml dialog
resultTwo=(TextView)textEntryView.findViewById(R.id.resultTwo);
alert.setTitle("RESULT");
alert.setIcon(R.drawable.ic_launcher);
alert.setView(textEntryView);
alert.setNeutralButton("OK",null);
getETvalue();
evaluation();
CalcUpliftTV.setText(String.valueOf(CalUpliftResult));
DiscrepancyTV.setText(String.valueOf(DiscResult));
resultOne.setText("Calc. Uplift (KG)= "+String.valueOf(CalUpliftResult));
resultTwo.setText("Discrepancy(%)= "+String.valueOf(DiscResult));
AlertDialog alertD = alert.create();
alertD.show();
}
else
Toast.makeText(getApplicationContext(), "please give all inputs", Toast.LENGTH_SHORT).show();
}
});