I made a list view u can delete an item by touch the row of that listview, but it always deleting the last item, and after some delete times it shows index out of bound error
system was when u toch an item a dialogue box open u click print then item will removed the item and open an activity for few seconds.
here is the list adapter class
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final int positionplayer = position;
ViewHolderaway1 holder;
if (convertView == null) {
View row = inflater.inflate(R.layout.readonlyvendorlist, parent,
false);
row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// set title
try {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder.setTitle(values.get(positionplayer).Voucherref
+ " Sell");
// set dialog message
alertDialogBuilder
.setMessage(
values.get(positionplayer)
.getVoucherref() + "For Print")
.setCancelable(false)
.setPositiveButton("Print Voucher",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int id) {
// if this button is clicked,
// close
PrintTestAcitvity.printettext = values
.get(positionplayer).PrinterText;
ListService.printerlist
.remove(positionplayer);
Datasync.storedataprint(context);
notifyDataSetChanged();
Intent ia = new Intent(context,
PrintTestAcitvity.class);
context.startActivity(ia);
}
})
.setNegativeButton("Cancell",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int id) {
// if this button is clicked,
// just close
// the dialog box and do nothing
Toast.makeText(
context,
"Printing Data store for locally",
Toast.LENGTH_LONG)
.show();
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
} catch (IndexOutOfBoundsException e) {
// TODO: handle exception
notifyDataSetChanged();
}
}
});
holder = new ViewHolderaway1();
holder.ProductItemID = (TextView) row
.findViewById(R.id.ProductItemID);
holder.VoucherCost = (TextView) row.findViewById(R.id.VoucherCost);
holder.SupplierID = (TextView) row.findViewById(R.id.SupplierID);
Log.d("goru", "gadha");
row.setTag(holder);
holder = (ViewHolderaway1) row.getTag();
// Printer Productsdata = values.get(positionplayer);
// if (Productsdata != null) {
// holder.ProductItemID.setText("Print");
// holder.VoucherCost.setText(Productsdata.getVoucherref());
// // holder.SupplierID.setText(resid)
// // holder.SupplierID.setVisibility(View.GONE);
//
// if (Productsdata.getVoucherref().contains("Voda")) {
// holder.VoucherCost.setBackgroundColor(Color.RED);
// holder.VoucherCost.setTextColor(Color.WHITE);
// holder.SupplierID.setBackgroundDrawable(getContext()
// .getResources().getDrawable(R.drawable.voda));
// }
// if (Productsdata.getVoucherref().contains("Eco")) {
// holder.VoucherCost.setBackgroundColor(Color.BLUE);
// holder.VoucherCost.setTextColor(Color.WHITE);
// holder.SupplierID.setBackgroundDrawable(getContext()
// .getResources().getDrawable(R.drawable.eco));
// }
//
// }
convertView = row;
}else
{
holder = (ViewHolderaway1) convertView.getTag();
}
Printer Productsdata = values.get(positionplayer);
if (Productsdata != null) {
holder.ProductItemID.setText("Print");
holder.VoucherCost.setText(Productsdata.getVoucherref());
// holder.SupplierID.setText(resid)
// holder.SupplierID.setVisibility(View.GONE);
if (Productsdata.getVoucherref().contains("Voda")) {
holder.VoucherCost.setBackgroundColor(Color.RED);
holder.VoucherCost.setTextColor(Color.WHITE);
holder.SupplierID.setBackgroundDrawable(getContext()
.getResources().getDrawable(R.drawable.voda));
}
if (Productsdata.getVoucherref().contains("Eco")) {
holder.VoucherCost.setBackgroundColor(Color.BLUE);
holder.VoucherCost.setTextColor(Color.WHITE);
holder.SupplierID.setBackgroundDrawable(getContext()
.getResources().getDrawable(R.drawable.eco));
}
}
return convertView;
}
There are some major flaws with your logic in getView(), this is the biggest one:
if (convertView != null)
{
holder = new ViewHolderaway1();
return convertView;
}
This returns the recycled row without altering it... At a minimum you need to change the written content of the layout.
Look at the code in this answer: https://stackoverflow.com/a/4145996/1267661. You should use this as template. It demonstrates how to properly use a ViewHolder and display accurate data after Views are returned from ListView's RecycleBin.
Addition
This new code is much more efficient! Also I think I see why only the last row is deleted. In your AlertDialog you reference positionplayer but this onClick() code is run after getView() has finished, so positionplayer is not helpful here. Since your OnClickListener refers to the whole row, you should use the OnItemClickListener in your Activity instead and this will help delete the appropriate row:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Move your AlertDialog code here and use position instead of positionplayer
}
});
Related
I hope my title makes sense, basically I have a button inside a listview a layout as an adapter in a listview inside a fragment.
My problem is that my onClick method deleteQuote(View v) is not recognized when I declare it in the fragment class. It errors out something about not found in the main activity. So I transferred it to the main activity, but the problem is that I needed the view tag to get a primary key in the entry via the getTag to delete that entry in the database and in the adapter of the listview. Where should I put my onClick method where in i can still get the view tag or What is the best way to do this implementing setonclicklisteners?
Fragment class
public class QuotationList extends Fragment{
ListView lvQuotationsMotorcar;
ArrayList<Quotation> menuList_motorcar;
CustomMotorcarQuoteAdapter cmqa;
ListView lvQuotationsFire;
ArrayList<Quotation> menuList_fire;
CustomFireQuoteAdapter cfqa;
Button btnDeleteQuote_motorcar;
Spinner spQuotationType;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_online_quotation_list, container, false);
lvQuotationsMotorcar = (ListView) rootView.findViewById(R.id.lvQuotationsMotorcar);
menuList_motorcar = new ArrayList<Quotation>();
cmqa = new CustomMotorcarQuoteAdapter(getActivity(), R.layout.motorcarquotationlayout, menuList_motorcar);
lvQuotationsMotorcar.setAdapter(cmqa);
lvQuotationsFire = (ListView) rootView.findViewById(R.id.lvQuotationsFire);
menuList_fire = new ArrayList<Quotation>();
cfqa = new CustomFireQuoteAdapter(getActivity(), R.layout.firequotationlayout, menuList_fire);
lvQuotationsFire.setAdapter(cfqa);
final SQLiteDatabase mydatabase = getActivity().openOrCreateDatabase("INLIS", Context.MODE_PRIVATE, null);
spQuotationType = (Spinner) rootView.findViewById(R.id.spQuotationType);
btnDeleteQuote_motorcar = (Button) getActivity().findViewById(R.id.btnDeleteMotorcarQuote);
Cursor resultSet = mydatabase.rawQuery("Select * from QuotationMotorcar", null);
if (resultSet != null){
if (resultSet .moveToFirst()) {
while (!resultSet.isAfterLast()) {
//stuff
cmqa.add(q);
resultSet.moveToNext();
}
}
}else{
Toast.makeText(getActivity(), "No Pending Motorcar Quotations", Toast.LENGTH_LONG).show();
}
Cursor resultSet1 = mydatabase.rawQuery("Select * from QuotationFire", null);
if (resultSet1 != null){
if (resultSet1 .moveToFirst()) {
while (!resultSet1.isAfterLast()) {
//stuff
cfqa.add(q);
resultSet1.moveToNext();
}
}
}else{
Toast.makeText(getActivity(), "No Pending Fire Quotations", Toast.LENGTH_LONG).show();
}
mydatabase.close();
//more code
return rootView;
}
onClick method deleteQuote
public void deleteQuote_motorcar(final View v){
final SQLiteDatabase mydatabase = getActivity().openOrCreateDatabase("INLIS", Context.MODE_PRIVATE, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setTitle("Warning!");
alertDialogBuilder
.setMessage("Are you sure you want to delete this quote?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Quotation itemToRemove = (Quotation)v.getTag();
cmqa.remove(itemToRemove);
mydatabase.execSQL("DELETE FROM QoutationMotorcar WHERE QuoteNumber =" + itemToRemove.getQuoteNumber() + "; ");
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
This works perfectly fine if it just extends an activity class. Hope someone can help. I'm really annoyed on how this onClick is not working on Fragments.
How and where can I declare my method where in it can be called properly with the view tag?
Use this declaration of OnClickListener in your custom Adapter getView method
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.your_lv_item_layout, parent, false);
view.findViewById(R.id.your_bt).setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0) {
//do what ever you want
}
});
return view;
}
Instead of public void deleteQuote_motorcar(final View v)
I have an application which retrieves data from DB and displays it in a list view. I have a custom adapter for the same. So when I press the "delete" button, a delete button for each row in the list is displayed. If I press that, the particular row gets deleted in the DB and the same should be reflected in the listview also. The problem is, its not reflecting this change, I should close the app and reopen or move into some other activity and get back to see the updated results.
So my question is: where do I call the notifyDataSetChanged() method to get it updated instantly?
Here is my customadapter view:
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
MenuListItems menuListItems = menuList.get(position);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.customlist, parent, false);
}
Button ck = (Button) convertView.findViewById(R.id.delbox);
if(i){
ck.setVisibility(View.VISIBLE);}
else{
ck.setVisibility(View.GONE);
}
ck.setTag(menuListItems.getSlno());
ck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final Integer Index = Integer.parseInt((String) v.getTag());
final DataHandler enter = new DataHandler(c);
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
enter.open();
enter.delet(Index);
enter.close();
notifyDataSetChanged();
dialog.dismiss();
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
dialog.dismiss();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(c);
builder.setMessage("Are you sure you want to Delete?").setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
});
TextView id = (TextView) convertView.findViewById(R.id.tvhide);
id.setText(menuListItems.getSlno());
TextView title = (TextView) convertView.findViewById(R.id.tvtitle);
title.setText(menuListItems.getTitle());
TextView phone = (TextView) convertView.findViewById(R.id.tvpnumber);
phone.setText(menuListItems.getPhone());
// ck.setChecked(menuList.)
notifyDataSetChanged();
return convertView;
}
You need to delete the data from the adapter of the listview via adapter.remove(adapter.getItem(position)); and then call notifyDataSetChanged() on adapter.
You are storing the data that shows your ListView in a List somewhere (which you didn't show in the code your paste. It would be nice to update your question)
Then, when you remove your data from the dialog, you are deleting the real data, but not the one stored in your List, that you adapter uses to show the ListView. So you simply need to remove this data from this List and then call notifyDataSetChanged() and it will work.
A very basic solution to this would be restarting the activity.
In the Delete button click listener, after you delete the record, restart the activity.
Now it will fetch recent data!
Intent myIntent = new Intent(context,MainActivityName.class);
context.startActivity(myIntent);
There seems to be a problem when there are more than 5 records to
display on Manage Practice. For e.g. if there are 6 records to display on
Manage Practice. If I check the check box number 1, the check box number 6 also
gets checked. If there are 7 records, and if I check on 2nd record, then
the 7th record also gets automatically checked.I don't what's going on there I am very confusing, Please check my code let me know what's problem is there.
public class ManagePracticeLogAdapter extends BaseAdapter
{
//Variables to save class object.
Context context;
// variable to instantiates a layout XML file into its corresponding View objects.
LayoutInflater inflater;
MenuItem menu,addlog;
List<Integer> SelectedBox= new ArrayList<Integer>();;
// Variable to accept list data from Produce log activity
ArrayList<HashMap<String, String>> data;
ArrayList<HashMap<String, String>> temp_data;
HashMap<String, String> resultp = new HashMap<String, String>();
List<String> deleteData=new ArrayList<String>();
// Constructor to accept class instance and data.
public ManagePracticeLogAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist,MenuItem mymenu,MenuItem myaddlog)
{
this.context = context;
data = arraylist;
//temp_data.addAll(data);
menu=mymenu;
addlog=myaddlog;
}
#Override
public int getCount()
{
return data.size();
}
#Override
public Object getItem(int position)
{
return null;
}
#Override
public long getItemId(int position)
{
return 0;
}
// Method to display data of Produce log Activity in list view
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
if(convertView==null)
{
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView= inflater.inflate(R.layout.logitem1, parent, false);
}
TextView datetime;
TextView totminutes;
TextView skills;
TextView weather;
TextView day_night_icon;
final CheckBox chkdelete;
TextView approval_icon;
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
datetime = (TextView) convertView.findViewById(R.id.id_datetime);
totminutes = (TextView) convertView.findViewById(R.id.totminutes);
skills= (TextView) convertView.findViewById(R.id.id_skills);
weather=(TextView)convertView.findViewById(R.id.id_weather);
day_night_icon=(TextView)convertView.findViewById(R.id.day_night_icon);
approval_icon=(TextView)convertView.findViewById(R.id.conditions);
chkdelete=(CheckBox)convertView.findViewById(R.id.id_chkDelete);
// Capture position and set results to the TextViews
datetime.setText(resultp.get("date_time"));
if(!resultp.get("Day_minutes").toString().equalsIgnoreCase("0"))
{
totminutes.setText(resultp.get("Day_minutes")+" min");
day_night_icon.setBackgroundResource(R.drawable.sun);
}else
{
totminutes.setText(resultp.get("Night_minutes")+" min");
day_night_icon.setBackgroundResource(R.drawable.moon);
}
skills.setText(resultp.get("Skill"));
weather.setText(resultp.get("weather"));
String supervisorText=resultp.get("super");
Log.w("SUPERVISOR", supervisorText);
if(supervisorText.equals("No supervisor"))
{
approval_icon.setBackgroundResource(R.drawable.pending);
}else
{
approval_icon.setBackgroundResource(R.drawable.approve);
}
String fontPath = "fonts/Roboto-Light.ttf";
Typeface tf = Typeface.createFromAsset(context.getAssets(), fontPath);
datetime.setTypeface(tf);
totminutes.setTypeface(tf);
skills.setTypeface(tf);
weather.setTypeface(tf);
// chkdelete.setTag(R.id.id_chkDelete);
chkdelete.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
// int checkBoxId = (Integer) buttonView.getTag();
if(SelectedBox.size()-1==0)
{
menu.setVisible(false);
addlog.setVisible(true);
}else
{
addlog.setVisible(false);
}
if(isChecked)
{
SelectedBox.add(position);
menu.setVisible(true);
addlog.setVisible(false);
}else /*if(!isChecked)*/
{
SelectedBox.remove(SelectedBox.indexOf(position));
}
}
});
menu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
// TODO Auto-generated method stub
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle("Student Driving Practice Log");
// set dialog message
alertDialogBuilder
.setMessage("Are you sure want to Delete Record!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
try
{
NewNewDataHelper db=new NewNewDataHelper(context);
if(!SelectedBox.isEmpty())
{
for(int i=0;i<SelectedBox.size();i++)
{
resultp=data.get(SelectedBox.get(i));
String str[]=resultp.get("date_time").split(" ");
Log.d("Checked Element",str[0]+"\n"+str[1]+"\n"+resultp.get("Skill"));
db.DeleteSingleLog(resultp.get("Skill"),str[0],str[1]);
/*resultp=data.get(SelectedBox.get(i));
String str[]=resultp.get("date_time").split(" ");
db.DeleteSingleLog(resultp.get("Skill"),str[0],str[1]);*/
Toast.makeText(context,"Record Deleted", Toast.LENGTH_LONG).show();
}
Log.d("LISTSTSTSTST", SelectedBox.toString());
Intent intent = new Intent(context,ManagePracticeLogActivity.class);
intent.putExtra("s11", "delete");
context.startActivity(intent);
}
}catch(Exception e)
{
}
}
})
.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();
return false;
}
});
convertView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
resultp = data.get(position);
String str1 = null;
String str[]=resultp.get("date_time").toString().split(" ");
str1=str[0]+"~"+resultp.get("Skill")+"~"+str[1];
Log.d("PARTICULAR SKILLLLL", str1);
Intent intent = new Intent(context,LogEdit.class);
intent.putExtra("s11","Update Practice");
intent.putExtra("dataupdate",str1);
context.startActivity(intent);
}
});
return convertView;
}
private void deleteItems(List<Integer> list)
{
data.clear();
}
}
The problem is, view gets recycled due to recycling of ListView and the value of Checkbox(check or uncheck) is not maintained. You can check this link.
just have a look at this. This will explain the "problem" with checkboxes in listviews. There's also a link with a solution, if needed :)
When you load the view in getView, you need to set the check state for that particular item. I assume for each row you store this information somewhere? Just retrieve the correct state for the row (position) and set the correct state on the checkbox. The reason why you are seeing the behavior is because in a ListView rows are reused. The 6th row is in fact the 1st row. It is done this way to conserve memory and optimize a ListView for speed.
Inside your getView() add :
if(SelectedBox.contains(new Integer(position))) {
chkdelete.setChecked(true);
} else {
chkdelete.setChecked(false);
}
In my application im using custom list view with two buttons and a image view in each row of the list view. I want to do something like this:
when a user press DONE button on the list view it should open a dialog box. In the dialog box i have something to show.
When dialog box is closed the background of the relevent list view item should be changed to some color and
when I refresh the list view that color change should be there
How can i do this. I know how to show a dialog box on a click event on the list button, but to changing the color of the background, *I have no idea how to do it... please give me some logics , code samples ideas....please...
public View getView(final int position, final View convertView, final ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.row_for_appoinments,null);
final TextView firstname = (TextView) vi.findViewById(R.id.first_name);
final TextView lastname = (TextView) vi.findViewById(R.id.last_name);
final TextView startTime = (TextView) vi.findViewById(R.id.start_time);
final TextView endTime = (TextView) vi.findViewById(R.id.end_time);
final TextView date = (TextView) vi.findViewById(R.id.empty_field);
final TextView hidID = (TextView) vi.findViewById(R.id.row_id_pationt);
final TextView hidAppid = (TextView) vi.findViewById(R.id.appoinment_id_row);
img = (ImageView) vi.findViewById(R.id.image);
HashMap<String, String> song = data.get(position);
firstname.setText(song.get("FirstName"));
//Log.w("viewFirstName", firstName.toString());
lastname.setText(song.get("LastName"));
startTime.setText(song.get("StartTime"));
endTime.setText(song.get("EndTime"));
date.setText(song.get("Date"));
hidID.setText(song.get("PersonId"));
//Log.w("viewhidID", hidID.getText().toString());
hidAppid.setText(song.get("AppointmentId"));
theUrl = song.get("ImageURL");
if(theUrl==null || theUrl.equalsIgnoreCase("") || theUrl.equalsIgnoreCase("")){
Bitmap bImage = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.propic);
img.setImageBitmap(bImage);
}
else{
if (cancelPotentialDownload(theUrl, img)) {
BitmapDownloaderTask2 task = new BitmapDownloaderTask2(img);
DownloadedDrawable2 downloadedDrawable = new DownloadedDrawable2(task);
img.setImageDrawable(downloadedDrawable);
task.execute(theUrl);
}
}
/*ImageButton direction = (ImageButton) vi.findViewById(R.id.direction);
direction.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "under construction", Toast.LENGTH_LONG).show();
}
});
*/
vi.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String getPname = hidID.getText().toString();
Intent zoom=new Intent(parent.getContext(), Profile.class);
zoom.putExtra("PatientID", getPname);
parent.getContext().startActivity(zoom);
}
});
Button btnDone = (Button) vi.findViewById(R.id.btnDone);
btnDone.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//convertView.setBackgroundColor(Color.GREEN);
long id = getItemId(position);
String s = String.valueOf(id);
//Toast.makeText(mContext, s, Toast.LENGTH_LONG).show();
//((ViewGroup) convertView).getChildAt(position).setBackgroundColor(Color.GREEN);
/* //convertView.setBackgroundColor(Color.GREEN);
if(convertView.getId() == position){
convertView.setBackgroundColor(Color.GREEN);
}
else{
Toast.makeText(mContext, s, Toast.LENGTH_LONG).show();
}*/
// HERE I WANT TO CHNAGE THE BACKGROUND COLOR
// LIKE CHANGING COLOR OF THE ITEM WHEN WE TOUCH
//BUT THE COLOR SHOULD REMAIN
}
});
return vi;
}
_button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LayoutInflater li= LayoutInflater.from(classname.this);
View dialogView =li.inflate(R.layout.layoutname, null);
AlertDialog.Builder dialogwindow = new AlertDialog.Builder(classname.this);
dialogwindow.setView(dialogView);
_dialogTextView=(TextView)dialogView.findViewById(R.id.dialog_textview);
dialogwindow.setCancelable(false).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// get user input and set it to result
//
dialog.cancel(); }
})
.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
_listview.setBackgroundColor(color);
}
});
// create alert dialog
AlertDialog alertDialog = dialogwindow.create();
// show it
alertDialog.show();
}
});
}
});
try this.it may be help you.
I have a DialogFragment that shows a list of items to pick from (similar to the attach dialog in Messaging).
My problem is that I cannot get this dialog to dismiss when an item is selected. I've tried calling dismiss() and getDialog().dismiss() inside the OnItemClickListener, no luck. I've tried to remove the dialog through the FragmentManager, I've tried fragmentManager.popBackStack(), all to no avail. I cannot get this dialog to dismiss. It goes away fine when clicking outside the dialog or hitting the back button, but nothing in my code will make it go away.
Has anyone seen this before? How do I get the dialog to dismiss correctly?
Dialog Code:
public class ShareDialog extends DialogFragment {
public enum ShareType {
Camera, Gallery, Web, Whiteboard, Browse,
}
BaseAdapter mShareAdapter = new BaseAdapter() {
#Override
public View getView(int position, View contentView, ViewGroup parent) {
TextView view = null;
if (contentView == null) {
view = (TextView) getLayoutInflater(null).inflate(android.R.layout.simple_list_item_1, parent, false);
} else {
view = (TextView) contentView;
}
int draw = 0;
switch (ShareType.values()[position]) {
case Browse:
view.setText("Browse Content...");
draw = R.drawable.ic_share_browse;
break;
case Camera:
view.setText("Image from Camera...");
draw = R.drawable.ic_share_camera;
break;
case Gallery:
view.setText("Image from Gallery...");
draw = R.drawable.ic_share_gallery;
break;
case Web:
view.setText("New Browsing Session");
draw = R.drawable.ic_share_web;
break;
case Whiteboard:
view.setText("New Whiteboard");
draw = R.drawable.ic_share_whiteboard;
break;
}
view.setCompoundDrawablesWithIntrinsicBounds(draw, 0, 0, 0);
view.setCompoundDrawablePadding(8);
return view;
}
#Override
public long getItemId(int position) {
return ShareType.values()[position].ordinal();
}
#Override
public Object getItem(int position) {
return ShareType.values()[position];
}
#Override
public int getCount() {
return ShareType.values().length;
}
};
public Dialog onCreateDialog(android.os.Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Share which?");
ListView list = new ListView(getActivity());
list.setAdapter(mShareAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long itemId) {
dismiss(); // WHY DOESN'T THIS WORK???
if (listener != null)
listener.newShare((ShareType) mShareAdapter.getItem(position));
}
});
builder.setView(list);
return builder.create();
}
public interface ShareDialogListener {
void newShare(ShareType type);
}
private ShareDialogListener listener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the AutoconnectListener so we can send events to the host
listener = (ShareDialogListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString() + " must implement ShareDialogListener");
}
}
}
Why not use the methods available on AlertDialog.Builder to build the list, instead of creating your own ListView and populating it?
I have modified your sample code to show how this would work, and in this example the dialog dismiss() functions fine.
public Dialog onCreateDialog(android.os.Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setSingleChoiceItems(mShareAdapter, 0, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (listener != null) {
listener.newShare((ShareType) mShareAdapter.getItem(which));
}
}
});
builder.setTitle("Share which?");
return builder.create();
}
For some - unknown to me - reason, the dialog reference you get back from getDialog() isn't the one you want to work with when inside the listener. You need a reference to the dialog as provided you when you call builder.create();
For example:
final AlertDialog dialog = builder.create();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
dialog.dismiss();
}
});
return dialog;
HA....
I've found it...
The reason for this is actually ours... we were trying to inflate an xml, and have called:
DialogFragment.this.getLayoutInflater(null).inflate(...);
This call causes, like I've stated in the comment to create 4 dialogs, and then everything gets messed up.
The proper way to do this would be to call:
LayoutInflater layoutInflater = (LayoutInflater) getActivity().getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutInflater.inflate(...);
This fix solved the annoying bug for me on the first go!