I'm trying to get the text from edt_nominal and input it into my database. but I don't know the code.
this is DonasiDetail.class code :
private void showAlertDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(DonasiDetail.this);
alertDialog.setTitle("Melakukan Donasi");
alertDialog.setMessage("Masukan Nominal Donasi: ");
final EditText edt_nominal = new EditText(DonasiDetail.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
);
edt_nominal.setLayoutParams(lp);
alertDialog.setView(edt_nominal); //Menambahkan edittest ke alertdialog
alertDialog.setIcon(R.drawable.ic_handshake);
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
new Database(getBaseContext()).addToDonasi(new Transaksi(
donasiId,
currentDonasi.getNama(),
edt_nominal.getText().toString()
));
Toast.makeText(DonasiDetail.this, "Data Telah Masuk ke Donasi", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
this is Transaksi.class code:
public class Transaksi {
private String Id_Donasi;
private String Nama_Donasi;
private String Nominal_Donasi;
public Transaksi(String id_Donasi, String nama_Donasi, String nominal_Donasi) {
Id_Donasi = id_Donasi;
Nama_Donasi = nama_Donasi;
Nominal_Donasi = nominal_Donasi;
}
public String getId_Donasi() {
return Id_Donasi;
}
public void setId_Donasi(String id_Donasi) {
Id_Donasi = id_Donasi;
}
public String getNama_Donasi() {
return Nama_Donasi;
}
public void setNama_Donasi(String nama_Donasi) {
Nama_Donasi = nama_Donasi;
}
public String getNominal_Donasi() {
return Nominal_Donasi;
}
public void setNominal_Donasi(String nominal_Donasi) {
Nominal_Donasi = nominal_Donasi;
} }
I want to set data from edt_nominal.getText().toString() to Nominal_Donasi at Transaksi.class
I'm fairly new to Android programming and I am still getting used to it, any help would be greatly appreciated! Thanks
You'll have to learn how to store data in android. Go through this article. Decide which option works for you the best. If you have less data, you can store it in SharedPreferences otherwise go for SQLite database.
Related
So, I want to detect button pressed by the user when an alert dialog pops up. This is my code.
public class AlertUtils {
private int BTN_PRESSED;
private AlertDialog.Builder builder;
public AlertUtils(Context context){
builder = new AlertDialog.Builder(context);
}
public int ShowAlertWithTwoButtons(String Title,String Message,String PositiveButtonText,
String NegativeButtonText){
builder.setTitle(Title);
builder.setMessage(Message);
builder.setPositiveButton(PositiveButtonText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
BTN_PRESSED = i;
}
});
builder.setNegativeButton(NegativeButtonText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
BTN_PRESSED = i;
dialogInterface.dismiss();
}
});
builder.show();
return BTN_PRESSED;
}
}
By calling ShowAlertWithTwoButtons method, returns int value detecting Positive or Negative Button pressed. My Problem is it's giving me default 0 value when I chose from an alert dialog and when I again open us alert dialog it returns the correct value.
Try in this way. Make AlertUtils class like this.
public class AlertUtils {
private AlertDialog.Builder builder;
private AlertDialogListener alertDialogListener;
// Interface to send back the response of click
interface AlertDialogListener {
void onClick(int a);
}
public AlertUtils(Context context, AlertDialogListener alertDialogListener) {
builder = new AlertDialog.Builder(context);
this.alertDialogListener = alertDialogListener;
}
public void ShowAlertWithTwoButtons(String Title, String Message, String PositiveButtonText,
String NegativeButtonText) {
builder.setTitle(Title);
builder.setMessage(Message);
builder.setPositiveButton(PositiveButtonText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// if you want to pass the actual value of i,then pass the i in onClick or if you want 1 on
// positive button click then pass 1 here.
alertDialogListener.onClick(1);
}
});
builder.setNegativeButton(NegativeButtonText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// if you want to pass the actual value of i, then pass the i in onClick or if you want 1 on
// negative button click then pass 0 here.
alertDialogListener.onClick(0);
dialogInterface.dismiss();
}
});
builder.show();
}
}
Call the dialog in this way where you need this.
AlertUtils alertUtils = new AlertUtils(getContext(), new AlertUtils.AlertDialogListener() {
#Override
public void onClick(int a) {
if (a == 1) {
// Do your work on Positive button click
} else {
// Do your work on Negative button click
}
}
});
alertUtils.ShowAlertWithTwoButtons("Alert Dialog", "Alert Dialog Description ", "Positive", "Negative");
You'll always get BTN_PRESSED with 0 value whenever you're instantiating your AlertUtils object and the calling the ShowAlertWithTwoButtons method. But you'll get another value if you're recalling the ShowAlertWithTwoButtons again.
I think what you're currently doing is like the following:
// First, you're instantiating the object
AlertUtils alertUtils = new AlertUtils(getContext());
// then you're calling the method
int pressedButton = alertUtils.ShowAlertWithTwoButtons("title", "message", "yes", "no");
// which will return pressedButton as 0
// then you calling the method again after clicked yes or no
int anotherPressedButton = alertUtils.ShowAlertWithTwoButtons("title", "message", "yes", "no");
// which will not zero. But can be -1, -2, -3 like in the
// https://developer.android.com/reference/android/content/DialogInterface.html
Which is incorrect if want to get the button value directly after the click because of asynchronous nature of AlertDialog interface.
Instead, you need to add a listener (ohh no, another listener) to your AlertUtils.
UPDATE
You need to add another listener for click button, something like this:
public class AlertUtils {
public interface Listener {
void onButtonClicked(int pressedButton);
}
private Listener mListener;
private AlertDialog.Builder builder;
public AlertUtils(Context context, Listener listener){
builder = new AlertDialog.Builder(context);
mListener = listener;
}
public void ShowAlertWithTwoButtons(String Title,String Message,String PositiveButtonText,
String NegativeButtonText){
...
builder.setPositiveButton(PositiveButtonText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
mListener.onButtonClicked(i);
}
});
builder.setNegativeButton(NegativeButtonText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
mListener.onButtonClicked(i);
dialogInterface.dismiss();
}
});
builder.show();
}
}
then you can create and call the method with:
// create the listener to listen for the clicked button.
AlertUtils.Listener listener = new AlertUtils.Listener() {
#Override
public void onButtonClicked(int pressedButton) {
// here you'll receive the button value
// do something here.
}
};
AlertUtils alertUtils = new AlertUtils(getContext(), listener);
// then you're calling the method
alertUtils.ShowAlertWithTwoButtons("title", "message", "yes", "no");
I am attempting to save data from an edit text field within a dialog to an ArrayList. I followed the methods of an answer to a similar question (found here How to store edit text data from an Android dialog?) however my code isn't exactly saving data. From my understanding I should be able to do the following(note it isnt the entire class, only the method in question):
public class StartNewGameActivity extends AppCompatActivity {
private ListView lv;
ArrayList<String> game_players = new ArrayList<String>();
public void addPlayerToGame(View view) {
DialogFragment newFragment = new CreatePlayerDialogFragment(
new CreatePlayerDialogFragment.MyMessageDialogListener(){
#Override
public void onClosed(String name) {
game_players.add(name);
}
});
newFragment.show(getSupportFragmentManager(), "players");
}
While using the following class:
public class CreatePlayerDialogFragment extends DialogFragment {
public interface MyMessageDialogListener {
public void onClosed(String name);
}
public AlertDialog onCreateDialog(final MyMessageDialogListener listener) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final EditText input = new EditText(getActivity());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
builder.setView(input);
builder.setMessage(R.string.player_name_dialog)
.setPositiveButton(R.string.player_name_dialog_add, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Add Player
{
if(listener != null) {
listener.onClosed(input.getText().toString());
}
dialog.cancel();
}
}
})
.setNegativeButton(R.string.player_name_dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
However with my code I get an error "CreatePlayerDialogFrament() in CreatePlayerDialogFragment cannot be applied to CreatePlayerDialogFrament.MyMessageDialogListener"
Is it possibly because I am trying to do everything in my OnCreate() method? Im not quite sure what the issue is or how to go about solving it.
I am coding to make a application to manage account and password, everything
is good, only Button Edit has problem. I click it one time, it works normaly, when i click it in second time, it crash. Can you help me?
This is logcat
private ListView listview_account;
private Button add_new;
private EditText newtype, oldtype;
private EditText newusername, oldusername;
private EditText newpassword, oldpassword;
private List<Account> list_accounts;
private String[] list_type;
private MyDatabaseHelper helper = new MyDatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
listview_account = (ListView)findViewById(R.id.list_account);
add_new = (Button)findViewById(R.id.ADD);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView_addnew = inflater.inflate(R.layout.dialog_addnew, null);
final View dialogView_change = inflater.inflate(R.layout.dialog_change, null);
newtype = (EditText)dialogView_addnew.findViewById(R.id.type);
newusername = (EditText)dialogView_addnew.findViewById(R.id.username);
newpassword = (EditText)dialogView_addnew.findViewById(R.id.password);
oldtype = (EditText)dialogView_change.findViewById(R.id.type_old);
oldusername = (EditText)dialogView_change.findViewById(R.id.username_old);
oldpassword = (EditText)dialogView_change.findViewById(R.id.password_old);
update_show();
final AlertDialog.Builder builder_show = new AlertDialog.Builder(this);
final AlertDialog.Builder builder_add = new AlertDialog.Builder(this);
final AlertDialog.Builder builder_delete = new AlertDialog.Builder(this);
final AlertDialog.Builder builder_change = new AlertDialog.Builder(this);
builder_add.setView(dialogView_addnew);
builder_change.setView(dialogView_change);
builder_delete.setTitle("Delete Account");
builder_delete.setIcon(android.R.drawable.ic_delete);
builder_delete.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder_change.setTitle("Edit");
builder_change.setIcon(android.R.drawable.ic_input_get);
builder_change.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder_add.setTitle("Add new account");
builder_add.setIcon(android.R.drawable.ic_input_add);
builder_add.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
add_new_account();
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show();
}
}
}
);
builder_add.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
newtype.setText("");
newusername.setText("");
newpassword.setText("");
newtype.requestFocus();
}
}
);
final AlertDialog alert_add_new = builder_add.create();
add_new.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
alert_add_new.show();
}
}
);
listview_account.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v,final int pos, long id) {
builder_show.setTitle(list_type[pos]);
builder_show.setIcon(android.R.drawable.ic_dialog_info);
builder_show.setMessage("Username: " + list_accounts.get(pos).getUSERNAME()
+ "\nPassword: " + list_accounts.get(pos).getPASSWORD());
builder_show.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
builder_delete.setMessage("Do you want to remove " + list_type[pos]+ "?\nUsername: " + list_accounts.get(pos).getUSERNAME() + "\nPassword: " + list_accounts.get(pos).getPASSWORD());
builder_delete.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
helper.DeleteAcc(list_type[pos]);
Toast.makeText(getApplicationContext(), "Success.", Toast.LENGTH_SHORT).show();
update_show();
}
});
final AlertDialog dialog_delete = builder_delete.create();
dialog_delete.show();
}
}
);
builder_show.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
oldtype.setText(list_type[pos]);
oldusername.setText(list_accounts.get(pos).getUSERNAME());
oldpassword.setText(list_accounts.get(pos).getPASSWORD());
builder_change.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
helper.DeleteAcc(list_type[pos]);
change();
}
});
AlertDialog alert_change = builder_change.create();
alert_change.show();
}
}
);
AlertDialog alert1_show = builder_show.create();
alert1_show.show();
}
});
}
private void add_new_account()
{
String new_type = newtype.getText().toString();
String new_username = newusername.getText().toString();
String new_password = newpassword.getText().toString();
Account new_acc = new Account(new_type, new_username, new_password);
helper.AddAccount(new_acc);
update_show();
newtype.setText("");
newusername.setText("");
newpassword.setText("");
newtype.requestFocus();
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
}
private void change()
{
String old_type = oldtype.getText().toString();
String old_username = oldusername.getText().toString();
String old_password = oldpassword.getText().toString();
Account new_acc = new Account(old_type, old_username, old_password);
helper.AddAccount(new_acc);
update_show();
Toast.makeText(getApplicationContext(), "Đã lưu.", Toast.LENGTH_SHORT).show();
}
private void update_show()
{
list_accounts = helper.getListAccount();
list_type = new String[list_accounts.size()];
int i = 0;
for (Account acc: list_accounts) { list_type[i++] = acc.TYPE; }
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, list_type);
listview_account.setAdapter(adapter);
}
As for me, the problem is that you create your builder_show dialog inside your ItemClickListener.
listview_account.setOnItemClickListener(new AdapterView.OnItemClickListener()
Actually, you create it every time and on second time system shows you error, that "The specified child already has a parent. You must call removeView() on the child's parent first." Because dialog already exists.
If you wish to preserve everything as is, you should remove your dialog before every show() call. Check this for details.
But correct (for this issue) would be to move dialog creation code outside ItemClickListener.
I am cleaning up some code where a DialogFrament i supposed to diaplay items from an ArrayList (ref. "arr" in the code) and then the user can choose severeal items from it and then hit OK. This work fine, no problemo. But, only on Samsung Phones, the DialogFrament lists the item from the ArrayList twice. so, on all the other phone the list displays the values arr[0]->arr[n] but on Samsung(again ONLY on Samsung) the values are arr[0]->arr[n] + arr[0]->arr[n]. Since it's the same code for all android phones but the problem only occurs on Samsung Phones, im out of ideas.
A quick google search pointed me towards a difference in layout rules by Samsung depending on the resolution of their phone but it seeamed unlikely.
Have any of you heard about this before?
CODE FOR MY FRAGMENT
public ArrayList mSelectedItems;
public int type;
public boolean single = false;
int count;
boolean search;
public int single_item = -1;
public interface CategoriesDialogFragmentListener {
public void onOkay(ArrayList items, int type);
public void onCancel();
public void onSingleOkay(int item, int type);
}
CategoriesDialogFragmentListener mListener;
public void setType(int type_id) {
/*
1 = Category
2 = Genre
3 = Availability
*/
type = type_id;
}
public void setSearch(boolean isSearch) {
search = isSearch;
}
public void setList(ArrayList temp) {
mSelectedItems = temp;
}
public void isSingle(boolean is_single){
single = is_single;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
mListener = (CategoriesDialogFragmentListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement NoticeDialogListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
mSelectedItems = new ArrayList(); // Where we track the selected items
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Set the dialog title
CharSequence[] arr;
String title;
switch(type){
case 1:
title = "Välj kategori";
arr = MainActivity.CATEGORY_STRINGS.toArray(new CharSequence[MainActivity.CATEGORY_STRINGS.size()]);
single = true;
break;
case 2:
title = "Välj genre";
arr = MainActivity.GENRE_STRINGS.toArray(new CharSequence[MainActivity.GENRE_STRINGS.size()]);
single = false;
break;
case 3:
title = "Välj tillgängligheter";
arr = MainActivity.AVAIL_STRINGS.toArray(new CharSequence[MainActivity.AVAIL_STRINGS.size()]);
single = false;
break;
default:
title = "ett fel uppstod";
arr = MainActivity.CATEGORY_STRINGS.toArray(new CharSequence[MainActivity.CATEGORY_STRINGS.size()]);
}
if(!single) {
if(type == 2 && search == false) {
count = 0;
builder.setTitle(title).setMultiChoiceItems(arr, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
//Kod för att starta fragment med valda entiteter
/*
if(mSelectedItems != null || !mSelectedItems.isEmpty()){
for(Object e : mSelectedItems){
}
}
*/
if (isChecked) {
if (count < 5) {
mSelectedItems.add(which);
count++;
} else {
new android.app.AlertDialog.Builder(getActivity())
.setTitle(R.string.five)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
((AlertDialog) dialog).getListView().setItemChecked(which, false);
}
} else if (mSelectedItems.contains(which)) {
// Else, if the item is already in the array, remove it
mSelectedItems.remove(Integer.valueOf(which));
count--;
}
}
})
// Set the action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
mListener.onOkay(mSelectedItems, type);
}
})
.setNegativeButton("Avbryt", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
CategoriesDialogFragment.this.getDialog().cancel();
}
});
}else{
builder.setTitle(title).setMultiChoiceItems(arr, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked) {
mSelectedItems.add(which);
} else if (mSelectedItems.contains(which)) {
// Else, if the item is already in the array, remove it
mSelectedItems.remove(Integer.valueOf(which));
}
}
})
// Set the action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
mListener.onOkay(mSelectedItems, type);
}
})
.setNegativeButton("Avbryt", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
CategoriesDialogFragment.this.getDialog().cancel();
}
});
}
} else {
builder.setTitle(title).setSingleChoiceItems(arr, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
single_item = item;
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
mListener.onSingleOkay(single_item, type);
}
})
.setNegativeButton("Avbryt", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
CategoriesDialogFragment.this.getDialog().cancel();
}
});;
}
return builder.create();
}
}
I am having trouble with an alert dialog that I cannot hide.
when the user press a button I show a dialog that is created with this code :
new AlertDialog.Builder(this)
.setTitle(R.string.enterPassword)
.setView(textEntryView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String password = pwdText.getText().toString();
dialog.dismiss();
processUserAction(password,targetUri);
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.
create();
There are some heavy operations performed in the 'processUserAction' method, and inside it I am using an AysncTask that displays a ProgressDialog.
The problem I am having is that the dialog prompting for the password never goes of the screen (I have tried with dismiss(), cancel()).
I guess it stays there until the onClick method is finished.
So, my question is how to close that AlertDialog, so I can show the ProgressDialog?
Another approach I have been trying is to set a DismissListener in the AlertDialog and calling the heavy operations from there, but I have had no luck ( it didn't get called ).
EDIT: Adding AsyncTask code
public class BkgCryptOperations extends AsyncTask<File,Void,Integer>{
#Override
protected Integer doInBackground(File... files) {
if (files!=null && files.length > 0){
File source = files[0];
File target = files[1];
return cryptAction.process(source,password, target);
}
return Constants.RetCodeKO;
}
CryptAction cryptAction;
String password;
ProgressDialog progressDialog;
public BkgCryptOperations (CryptAction cryptAction,String password,ProgressDialog progressDialog){
this.cryptAction=cryptAction;
this.password=password;
this.progressDialog=progressDialog;
}
#Override
protected void onPreExecute() {
if (progressDialog!=null){
progressDialog.show();
}
}
protected void onPostExecute(Integer i) {
if (progressDialog!=null){
progressDialog.dismiss();
}
}
}
Thanks in advance
Here is a excample how I do it:
public void daten_remove_on_click(View button) {
// Nachfragen
if (spinadapter.getCount() > 0) {
AlertDialog Result = new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle(getString(R.string.dialog_data_remove_titel))
.setMessage(getString(R.string.dialog_data_remove_text))
.setNegativeButton(getString(R.string.dialog_no),
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialogInterface, int i) {
// Nicht löschen
dialogInterface.cancel();
}
})
.setPositiveButton(getString(R.string.dialog_yes),
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialogInterface, int i) {
String _quellenName = myCursor.getString(1);
deleteQuellenRecord(_quellenName);
zuletztGelöscht = _quellenName;
}
}).show();
} else {
// Keine Daten mehr vorhanden
Toast toast = Toast.makeText(Daten.this,
getString(R.string.dialog_data_remove_empty),
Toast.LENGTH_SHORT);
toast.show();
}
}
Here is the code of deleteQuellenRecord:
private void deleteQuellenRecord(String _quellenName) {
String DialogTitel = getString(R.string.daten_delete_titel);
String DialogText = getString(R.string.daten_delete_text);
// Dialogdefinition Prograssbar
dialog = new ProgressDialog(this) {
#Override
public boolean onSearchRequested() {
return false;
}
};
dialog.setCancelable(false);
dialog.setTitle(DialogTitel);
dialog.setIcon(R.drawable.icon);
dialog.setMessage(DialogText);
// set the progress to be horizontal
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// reset the bar to the default value of 0
dialog.setProgress(0);
// set the maximum value
dialog.setMax(4);
// display the progressbar
increment = 1;
dialog.show();
// Thread starten
new Thread(new MyDeleteDataThread(_quellenName)) {
#Override
public void run() {
try {
// Datensatz löschen
myDB.execSQL("DELETE ... ');");
progressHandler
.sendMessage(progressHandler.obtainMessage());
myDB.execSQL("DELETE ...);");
// active the update handler
progressHandler
.sendMessage(progressHandler.obtainMessage());
myDB.execSQL("DELETE ...;");
// active the update handler
progressHandler
.sendMessage(progressHandler.obtainMessage());
// Einstellung speichern
try {
settings.edit().putString("LetzteQuelle", "-1")
.commit();
} catch (Exception ex) {
settings.edit().putString("LetzteQuelle", "").commit();
}
} catch (Exception ex) {
// Wait dialog beenden
dialog.dismiss();
Log.e("Glutenfrei Viewer",
"Error in activity MAIN - remove data", ex); // log
// the
// error
}
// Wait dialog beenden
dialog.dismiss();
}
}.start();
this.onCreate(null);
}
Wiht Async Task I do it this way:
private class RunningAlternativSearch extends
AsyncTask<Integer, Integer, Void> {
final ProgressDialog dialog = new ProgressDialog(SearchResult.this) {
#Override
public boolean onSearchRequested() {
return false;
}
};
#Override
protected void onPreExecute() {
alternativeSucheBeendet = false;
String DialogTitel = getString(R.string.daten_wait_titel);
DialogText = getString(R.string.dialog_alternativ_text);
DialogZweiteChance = getString(R.string.dialog_zweite_chance);
DialogDritteChance = getString(R.string.dialog_dritte_chance);
sucheNach = getString(R.string.dialog_suche_nach);
dialog.setCancelable(true);
dialog.setTitle(DialogTitel);
dialog.setIcon(R.drawable.icon);
dialog.setMessage(DialogText);
dialog.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface arg0) {
// TODO Auto-generated method stub
cancleBarcodeWorker();
if (alternativeSucheBeendet==false){
// Activity nur beenden wenn die Suche
// nicht beendet wurde, also vom User abgebrochen
Toast toast = Toast.makeText(SearchResult.this, SearchResult.this
.getString(R.string.toast_suche_abgebrochen),
Toast.LENGTH_LONG);
toast.show();
myDB.close();
SearchResult.this.finish();
}
}
});
dialog.show();
}
...
Can you show the code for processUserAction(..)? There is no need to include the dismiss.
I did something very similar and had no problems...
Here's the code:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Export data.\nContinue?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String file = getObra().getNome();
d = new ProgressDialog(MenuActivity.this);
d.setTitle("Exporting...");
d.setMessage("please wait...");
d.setIndeterminate(true);
d.setCancelable(false);
d.show();
export(file);
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
In export(file) I open the thread:
private void export(final String file) {
new Thread() {
public void run() {
try {
ExportData ede = new ExportData(
getApplicationContext(), getPmo().getId(),
file);
ede.export();
handlerMessage("Done!!");
} catch (Exception e) {
handlerMessage(e.getMessage());
System.out.println("ERROR!!!" + e.getMessage());
}
}
}.start();
}
In handlerMessage I dismiss the progressDialog and show the final message.
Hope it helps you.
You could create a listener outside of the AlertDialog, to abstract out the logic within the OnClickListener for the positive button. That way, the listener can be notified, and the AlertDialog will be dismissed immediately. Then, whatever processing of the user's input from the AlertDialog can take place independently of the AlertDialog. I'm not sure if this is the best way to accomplish this or not, but it's worked well for me in the past.
As far as I can tell, I don't see any obvious problems with your AsyncTask code.
public interface IPasswordListener {
public void onReceivePassword(String password);
}
IPasswordListener m_passwordListener = new IPasswordListener {
#Override
public void onReceivePassword(String password) {
processUserAction(password,targetUri);
}
}
public void showPasswordDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.enterPassword);
builder.setView(textEntryView);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
m_passwordListener.onReceivePassword(pwdText.getText().toString());
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
builder.show();
}