i tried to delete an item in sharedPreferences, in recyclerView adapter. but that item doesn't disappear till I go back from the activity and come back. I need it to disappear soon after being deleted.
Method
public boolean RemoveFromWantToRead(AllBooksActivityModel book) {
ArrayList<AllBooksActivityModel>books = getWantToReadBooks();
if (null != books){
for (AllBooksActivityModel b: books){
if (b.getBookID() == book.getBookID()){
if (books.remove(b)){
//We create a 'if' loop here is if only the thing happened, the loop actions.
Gson gson = new Gson();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove(WANT_TO_READ_BOOKS);
editor.putString(WANT_TO_READ_BOOKS,gson.toJson(books));
editor.commit();
return true;
}
} }
}return false;
}
This is how I tried to delete an item.
holder.BtnDltTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Do you want to delete this massage");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String EleName = allBooksActivityModels.get(position).getBookName();
if( Ulitls.getInstance(context).RemoveFromCurrenlyReading(allBooksActivityModels.get(position))){
Toast.makeText(context, EleName + " Removed", Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
}else{
Toast.makeText(context, "Something Wrong Happens, Try again", Toast.LENGTH_SHORT).show();
}
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.create().show();
}
});
Related
I'm having this error out of the blue and have no idea what's causing it or where it has come from.
Basically I've got a RecyclerView that gets populated with products. When a product is selected, I've got a custom Dialog that pops up where the user can increase product quantity or remove the product. This all works, however if I click the same product a second time it crashes the app with the following error:
System services not available to Activities before onCreate()
This is my RecyclerView.Adapter with the onBindViewHolder()
public class OrderAdapter extends RecyclerView.Adapter<OrderAdapter.MyViewHolder>{
#Override
public void onBindViewHolder(#NonNull OrderAdapter.MyViewHolder holder, int position) {
final Item Item = ItemList.get(position);
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog = new Dialog(context,R.style.Custom_Theme_Dialog);
//Code breaks on this line
dialog.setContentView(R.layout.dialog_cart_edit);
cartProdDesc = dialog.findViewById(R.id.lblcartProdDesc);
cartQuantity = dialog.findViewById(R.id.edit_quantity);
btnDone = dialog.findViewById(R.id.btn_dialog_done);
btnRemove = dialog.findViewById(R.id.btn_dialog_remove);
addQuantity = dialog.findViewById(R.id.addition_action);
minusQuantity = dialog.findViewById(R.id.minus_action);
cartProdDesc.setText(cartItem.getProductDescription());
cartPackSize.setText(cartItem.getPackSize());
addQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
quantity = Integer.parseInt(cartQuantity.getText().toString());
} catch (NumberFormatException nf) {
Log.e("Number Exception","Number Is Blank");
quantity = 0;
} catch (Exception e){
Log.e("ERROR",e.toString());
}
cartQuantity.setText(String.valueOf(++quantity));
}
});
minusQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
quantity = Integer.parseInt(cartQuantity.getText().toString());
} catch (NumberFormatException nf) {
Log.e("Number Exception","Number Is Blank");
quantity = 0;
} catch (Exception e){
Log.e("ERROR",e.toString());
}
cartQuantity.setText(String.valueOf(--quantity));
}
});
btnDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(cartQuantity.getText().toString().isEmpty() || cartQuantity.getText().toString().equals("0") || cartQuantity.getText().toString().contains("-")){
cartQuantity.setError("Enter a valid quantity");
} else {
newQuantity = cartQuantity.getText().toString();
db.updateCartItem(new CartItem(cartItem.getId(),cartItem.getProductCode(),cartItem.getBarcode(),cartItem.getNappiCode(),cartItem.getProductDescription(),cartItem.getPackSize(),newQuantity));
updateDataSet();
notifyDataSetChanged();
dialog.dismiss();
}
}
});
btnRemove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogInterface.OnClickListener dialogClickListner = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
db.deleteCartItem(cartItem.getId());
updateDataSet();
dialog.dismiss();
break;
case DialogInterface.BUTTON_NEGATIVE:
dialog.dismiss();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Are you sure you want to remove " + cartItem.getProductDescription()).setPositiveButton("Yes",dialogClickListner).setNegativeButton("No",dialogClickListner).show();
}
});
dialog.show();
}
});
}
}
I've got a private Dialog dialog; declaration further up on the Activity in case anyone was wondering.
The code breaks on the dialog = new Dialog(context,R.style.Custom_Theme_Dialog); however if I comment out the dialog.show() at the end I have no issues, apart from the dialog not showing, but that tells me that the problem isn't with the assigning of the dialog, or am I wrong on this train of thought ?
This is a line of code in my OrderActivity where I'm calling the adapter, I'm sending the context from here.
OrderAdapter = new OrderAdapter(this,ItemList);
This is my constructor where I'm assigning Context
public OrderAdapter(Context context, List<CartItem> cartItemList){
this.context = context;
this.cartItemList = cartItemList;
}
Depending on where that Context is coming from exactly, it might have already been "destroyed" by the time onClick() is called (well not really, because the Dialog is holding an implicit reference to it). In this case this is also a memory leak.
I'd suggest you to change the following:
#Override
public void onClick(View view) {
dialog = new Dialog(context, R.style.Custom_Theme_Dialog);
To this:
#Override
public void onClick(View view) {
dialog = new Dialog(view.getContext(), R.style.Custom_Theme_Dialog);
This way you'll always reference the Context the corresponding View is associated with.
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();
}
}
In my android application, when i click on text view, i want to display an alert dialog box which contain list of items. How is it possible. kindly guide.
i code it as:
cus_name_txt = (TextView)findViewById(R.id.cus_name_txta);
cus_name_txt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Onclick_click1(cus_name_txt);
// TODO Auto-generated method stub
}
});
contact_no_txt = (TextView)findViewById(R.id.contact_no_txta);
attend_by_txtbx = (EditText)findViewById(R.id.attend_by_txt);
attend_by_txtbx.setText(My_Task.attend_by_txt);
ticket_no_txt = (TextView)findViewById(R.id.ticket_no_txta);
task_detail_txt = (TextView)findViewById(R.id.task_detail_txt);
How can i get the alert box of list of items by clicking on textView. Please guide. I'll be thankful to u
If you want to show the progressBar Before loading of the List in alert dialog, then use AsyncTask for that.
e.g.:
private class LoadingTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute(){
super.onPreExecute();
progressDialog.show();
}
#Override
protected String doInBackground(String... str) {
String response = "";
// Call Web Service here and return response
response = API.getDealsByCategory(str[0], str[1]);
// e.g.: above is my WebService Function which returns response in string
return response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("result is: "+result);
new Thread(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
}
}).start();
// SHOW THE ALERT DIALOG HERE.....
}
}
Call AsyncTask as like below :
LoadingTask task = new LoadingTask();
task.execute("YOUR_PARAMETER","YOUR_PARAMETER");
//==============================
Just put below code in the Post Excution of the AsyncTask and you will get what you want.
final CharSequence[] items = {"","50","100","150","200","250","300","350","400","450","500","550","600","650","700","750","800","850","900","1000"};
AlertDialog.Builder builder = new AlertDialog.Builder(getParent());
builder.setTitle("Select Country");
//builder.setI
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
//Toast.makeText(getApplicationContext(), con.get(item).getCountrName(), Toast.LENGTH_SHORT).show();
selectDistanceTV.setText(items[item]);
System.out.println("Item is: "+items[item]);
/*CONTRY_ID = con.get(item).getCountryId();
stateET.requestFocus();*/
}
});
AlertDialog alert = builder.create();
alert.show();
Hope it will help you.
If you need more help on how to use AsyncTask then see here:Vogella
Comment me for any query.
Enjoy Coding... :)
Put following code in onClick of textView:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Color Mode");
ListView modeList = new ListView(this);
String[] stringArray = new String[] { "Bright Mode", "Normal Mode" };
ArrayAdapter<String> modeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, stringArray);
modeList.setAdapter(modeAdapter);
builder.setView(modeList);
final Dialog dialog = builder.create();
dialog.show();
Or
Dialog dialog = new Dialog(**Your Context**);
dialog.setContentView(R.layout.**Your Layout File**);
dialog.show();
In this layout file you can make your layout as per your requirements. When you want to use ListView from your Dialog Layout file then you have to write
ListView listView = (ListView)**dialog**.findViewById(R.id.**Your ListView Id**)
You can pass list of items in an String Array and display it in AlertBox..
For Example:
private void SingleChoice() {
String[] selectFruit = new String[] {"Apple","orange","mango"};
Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Single your Choice");
builder.setItems(selectFruit, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this,
selectFruit[which] + " Selected", Toast.LENGTH_LONG)
.show();
dialog.dismiss();
}
});
builder.setNegativeButton("cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
button.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
new AlertDialog.Builder(MainActivity.this)
.setSingleChoiceItems(arrClientName,0, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
name.setText(arrClientName[which]);
}
})
.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
}
})
.show();
}
});
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();
}
I'm using this pieces of code, in the activity:
public void carregaListaDemanda(){
setContentView(R.layout.listaviewdemanda);
lstDem = (ListView) findViewById(R.id.listViewDemanda);
DemandaAdapter adapter = new DemandaAdapter(ctx,
bancodedados.getAllDem(), this);
lstDem.setAdapter(adapter);
lstDem.setItemsCanFocus(true);
teste=0;
}
and in the adapter:
public void onClick(View v) {
AlertDialog alertDialog = new AlertDialog.Builder(ctx).create();
alertDialog.setTitle("Do you wanna delete?");
alertDialog.setIcon(R.drawable.icon);
alertDialog.setMessage("if 'yes' the demand '"
+ dem.getNr_demanda() + "' will be deleted!");
alertDialog.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// if yes delete, and REFRESH the screen
DemandaDAO dbHelper;
try {
dbHelper = new DemandaDAO(ctx);
dbHelper.DeleteDem(dem);
} catch (FileNotFoundException e) {
e.printStackTrace();
}}
});
alertDialog.setButton2("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
return;
}
});
alertDialog.show();
}
});
I want to refresh the listview after deleting a demand, but it results in a forceclose if I call the method in activity again.
call adapter.notifyDataSetChanged() , it Notifies the attached View that the underlying data has been changed and it should refresh itself.