AlertDialog with builder.setSingleChoiceItems. Disable items - android

I am using the following method do set the mapType of a GoogleMap object named mMap.
private void setMapType() {
final CharSequence[] MAP_TYPE_ITEMS =
{"Road", "Satellite", "Hybrid"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Set map type");
int checkItem = 0;
builder.setSingleChoiceItems(
MAP_TYPE_ITEMS,
checkItem,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0:
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
break;
case 1:
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case 3:
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
}
dialog.dismiss();
}
}
);
AlertDialog fMapTypeDialog = builder.create();
fMapTypeDialog.show();
}
What I am trying to do is disable one of the choices, let's say the 1st one (Road).
How could I do that?
P.S.1 I read this AlertDialog with single choice list - I need some items nonclickable but I don't understand how could I make it work in my case.
P.S.2 I tried, this solution too: Android: AlertDialog - how to disable certain choices that are not available Nothing happens. All options are enabled.

It is possible to do this in a standard AlertDialog, but using a custom list adapter. Perhaps the reason the first link you posted did not work for you is because it is important that the list items are updated prior to the dialog being populated.
Creating your dialog:
final CharSequence[] MAP_TYPE_ITEMS =
{"Road", "Satellite", "Hybrid"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Set map type");
int checkItem = 0;
ArrayList<Integer> list = new ArrayList<Integer>();
//specify index 1 is disabled, 0 and 2 will be enabled as normal
list.add(Integer.valueOf(1));
final MyCustomAdapter adapter = new MyCustomAdapter(MAP_TYPE_ITEMS, list);
builder.setAdapter(adapter, null );
builder.setSingleChoiceItems(
MAP_TYPE_ITEMS,
checkItem,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0:
Toast.makeText(InitialActivity.this, "Item 0 clicked ", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(InitialActivity.this, "Item 1 clicked ", Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(InitialActivity.this, "Item 2 clicked ", Toast.LENGTH_SHORT).show();
break;
}
if( adapter.getItemViewType(item) == 0 ){
dialog.dismiss();
}
}
}
);
AlertDialog fMapTypeDialog = builder.create();
fMapTypeDialog.show();
The custom adapter:
private class MyCustomAdapter extends BaseAdapter {
private ArrayList<String> mData = new ArrayList<String>();
private ArrayList<Integer> mDisabled = new ArrayList<Integer>();
private LayoutInflater mInflater;
public MyCustomAdapter(CharSequence[] items,
ArrayList<Integer> disabledItems) {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mDisabled = disabledItems;
for( int i = 0; i< items.length; ++i ){
addItem( items[i].toString());
}
}
public void addItem(final String item) {
mData.add(item);
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
if( mDisabled.contains(position))
return 1; //disabled
return 0; //enabled as normal
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public String getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
switch(type) {
case 1:
convertView = mInflater.inflate(android.R.layout.simple_list_item_1, null);
holder.textView = (TextView)convertView.findViewById(android.R.id.text1);
convertView.setEnabled(false);
convertView.setClickable(false);
break;
case 0:
convertView = mInflater.inflate(android.R.layout.simple_list_item_1, null);
holder.textView = (TextView)convertView.findViewById(android.R.id.text1);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.textView.setText(mData.get(position));
return convertView;
}
}

Basically, you cann't do it, with simple AlertDialog and Builder. What you trying to do, it's exchange your Views during some interaction, but that items doesn't have such behavior.
But it isn't problem to do it with Custom Dialog. Just for Example...
// create a Dialog component
final Dialog dialog = new Dialog(context);
//Tell the Dialog to use the dialog.xml as it's layout description
// With your own Layouts and CheckBoxs
dialog.setContentView(R.layout.dialog);
dialog.setTitle("Android Custom Dialog Box");
TextView headerTextView = (TextView) dialog.findViewById(R.id.txt);
headerTextView .setText("This is an Android custom Dialog Box Example! Enjoy!");
Button dialogButton1 = (Button) dialog.findViewById(R.id.dialogButton1);
dialogButton1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialogButton1.setEnabled(false);
dialog.dismiss();
}
});
// And so on, with other buttons
dialog.show();

I answered a pretty similar question here. Basically you can set a listener when a view is added in a given ListView and disable it.

Related

Updating ListView after selecting Item from Dialog Window

I've got the following Problem.
I have a ListView which displays me Articles with different Categories.
When I select a Category from my Dialog Window and press the PositiveButton "OK", I want to update my ListView, that it now lists only the Articles from the Category, selected in the Dialog Window.
I created an interface in the DialogFragment, which is a callback to get value from the Dialog.
This is the Class:
public class SelectFilterDialog extends DialogFragment implements DialogInterface.OnClickListener{
private static int mSelectedIndex;
private static String mSelectedCategory;
private String[] categories = {"All", "Announcements","Commerce","Development", "Distributions", "Front","Kernel","Legal", "Letters", "Press", "Security"};
static OnDialogSelectListener mDialogSelectorCallback;
//callback method to get values from a Dialog
public interface OnDialogSelectListener{
public void onSelectedOption();
}
public static SelectFilterDialog newInstance(int selected) {
final SelectFilterDialog dialog = new SelectFilterDialog();
mSelectedIndex = selected;
return dialog;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select Filter");
builder.setPositiveButton("OK", this);
builder.setNegativeButton("Cancel", this);
builder.setSingleChoiceItems(categories, mSelectedIndex, this);
return builder.create();
}
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case Dialog.BUTTON_POSITIVE:{
dialog.dismiss();
mDialogSelectorCallback.onSelectedOption();
}break;
case Dialog.BUTTON_NEGATIVE:{
dialog.cancel();
}break;
default:
mSelectedIndex = which;
setSelectedCategory(categories[which]);
break;
}
}
public void setDialogSelectListener(OnDialogSelectListener listener){
this.mDialogSelectorCallback = listener;
}
public void setSelectedCategory(String category){
this.mSelectedCategory = category;
}
public static String getSelectedCategory(){
return mSelectedCategory;
}
public static int getSelectedIndex(){
return mSelectedIndex;
}
}
In my SearchFragment Class , i show the List and implement the Interface from the SelectFilterDialog Fragment.
In the Method, i update the selectedCategory, after pressing the OK button, and then update the adapter with notifyDataSetChanged()
SearchFragment:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_bar_filter: {
showDialog();
}
}
return super.onOptionsItemSelected(item);
}
void showDialog() {
SelectFilterDialog dialog = SelectFilterDialog.newInstance(preSelectedValue);
dialog.setDialogSelectListener(this);
dialog.show(getActivity().getFragmentManager(), "dialog");
}
#Override
public void onSelectedOption() {
selectedCategory = dialog.getSelectedCategory();
preSelectedValue = dialog.getSelectedIndex();
Log.i(TAG, "selectedCategory : " +selectedCategory);
article_list_adapter.updateCategory(selectedCategory);
}
In my Adapter, i receive the Category in my updateCategory and fill the currentArticle List with the Articles with the correct Category.
This works fine.
After that i call NotifyDataSetChanged to update the view.
public void updateCategory(String category) {
this.currentArticles.clear();
this.selectedCategory = category;
for (Article article : entireArticles) {
if (category.equals(article.getCategory())) {
currentArticles.add(article);
}
}
notifyDataSetChanged();
}
notifyDataSetChanged();
}
But in the getView it throws an IndexOutOfBounce exception.
After selecting a Category from the dialog, e.g "Kernel", it adds only my 3 Kernel Categories to the currentArticle List, which is fine.
But int the getView statement:
Article currentArticle = currentArticles.get(_position);
It points on index 3 , though there are only 3 elements in the list.
java.lang.IndexOutOfBoundsException: Invalid index 3, size is 3
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at klinar.kronlachner.binder.app.Article_List_Adapter.getView(Article_List_Adapter.java:99)
Can you help me ? :)
public Article_List_Adapter(Context _c, int textViewResourceId, List<Article> articles) {
super(_c, textViewResourceId, articles);
this.entireArticles = new ArrayList<Article>();
this.currentArticles = new ArrayList<Article>();
entireArticles.addAll(articles);
currentArticles.addAll(articles);
this.storedArticles = new ArrayList<Article>(articles);
}
public View getView(int _position, View _convertView, ViewGroup _parent) {
View view = _convertView;
ViewHolder viewHolder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.article_list_row, null);
viewHolder = new ViewHolder();
viewHolder.article_icon = (ImageView) view.findViewById(R.id.article_category_icon);
viewHolder.articleTitle = (TextView) view.findViewById(R.id.article_title);
viewHolder.articleCategory = (TextView) view.findViewById(R.id.article_category);
viewHolder.articleDate = (TextView) view.findViewById(R.id.article_date);
viewHolder.articleAuthor = (TextView) view.findViewById(R.id.article_author);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) _convertView.getTag();
}
//Find the article to work with
Article currentArticle = currentArticles.get(_position);
//fill the Article_View
switch (currentArticle.getCategory()) {
case "Kernel": {
viewHolder.article_icon.setImageResource(R.drawable.ic_list_letter_k);
}
break;
case "Security": {
viewHolder.article_icon.setImageResource(R.drawable.ic_list_letter_s);
}
break;
default: {
viewHolder.article_icon.setImageResource(R.drawable.ic_list_letter_s);
}
}
viewHolder.articleTitle.setText(currentArticle.getTitle());
viewHolder.articleCategory.setText(currentArticle.getCategory());
viewHolder.articleDate.setText(currentArticle.getDate());
viewHolder.articleAuthor.setText(currentArticle.getAuthor());
return view;
Do this in your adapter class
create two List one for AllCategoryArticle and another for currentCategoryArticle.
class ArticleAdapter{
ArrayList<Model> currentArticle;
ArrayList<Model> entireArticle;
String selectedCategory="all"; //setting default category as "all"
public ArticleAdapter(ArrayList<Model> categoryList){
this.entireList=categoryList;
this.currentList=this.entireList;
}
//create updateCategory in adapter
/*call this method(updateCategory()) in you frgament/activity to update the adapter
according to you category that is selected in dialog
*/
public void updateCategory(String category){
this.currentArticle.clear();
this.selectedCategory=category;
for(Model item: entireArticle){
if(category.equals(item.getCategory()))
{
currentArticle.add(item);
}
}
notifyDataSetChanged();
}
........
........
#Override
public View getView(int _position, View _convertView, ViewGroup _parent) {
View view = _convertView;
ViewHolder viewHolder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.article_list_row, null);
viewHolder = new ViewHolder();
viewHolder.article_icon = (ImageView) view.findViewById(R.id.article_category_icon);
viewHolder.articleTitle = (TextView) view.findViewById(R.id.article_title);
viewHolder.articleCategory = (TextView) view.findViewById(R.id.article_category);
viewHolder.articleDate = (TextView) view.findViewById(R.id.article_date);
viewHolder.articleAuthor = (TextView) view.findViewById(R.id.article_author);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) _convertView.getTag();
}
//Find the article to work with
Article currentArticle = articles.get(_position);
//just remove if condition because already you have filtered article by category in currentArticle
//fill the Article_View
switch (currentArticle.getCategory()) {
case "Kernel":
viewHolder.article_icon.setImageResource(R.drawable.ic_list_letter_k);
break;
case "Security":
viewHolder.article_icon.setImageResource(R.drawable.ic_list_letter_s);
break;
default:
viewHolder.article_icon.setImageResource(R.drawable.ic_list_letter_s);
}
viewHolder.articleTitle.setText(currentArticle.getTitle());
viewHolder.articleCategory.setText(currentArticle.getCategory());
viewHolder.articleDate.setText(currentArticle.getDate());
viewHolder.articleAuthor.setText(currentArticle.getAuthor());
return view;
}
}
Do this in your Activity/Fragment which has tha ArticleAdapter
modification in onSelectedOption() method in your activity/Fragment
#Override
public void onSelectedOption() {
selectedCategory = dialog.getSelectedCategory();
preSelectedValue = dialog.getSelectedIndex();
Log.i(TAG, "selectedCategory : " +selectedCategory);
article_list_adapter.updateSelectedCategory(selectedCategory);
Log.i(TAG, "adapter Category : " +article_list_adapter.getSelectedCategory());
/*
call updateCategory() instead of notifyDataSetChanged()
updateCategory() will update your adapter
*/
//article_list_adapter.notifyDataSetChanged();
article_list_adapter.updateCategory(selectedCategory);
}
Problem in your code is
your trying to update the adapter using notifyDataSetChanged without updating your list.
notifyDataSetChanged() will work when there is an update in adapter model not in any variable in your adapter . see this how notifyDataSetChanged works in listView
EDIT:changes in adapter class
class Adapter{
ArrayList entireArticle;
ArrayList currentArticle;
public Adapter(Context context,ArrayList list){
this.entireArticle=new ArrayList();
this.currentArticle=new ArrayList();
entireArticle.addAll(list);
currentArticle.addAll(list);
}
public void updateCategory(String category){
this.currentArticle.clear();
this.selectedCategory=category;
if(category.equals("All")){ // add all article from entrieArticle if category=="all"
this.currentArticle.addAll(entireArticle);
}else{ //otherwise filter the article
for(Model item: entireArticle){
if(category.equals(item.getCategory()))
{
currentArticle.add(item);
}
}
}
notifyDataSetChanged();
}
...............
.................
}
do this changes in your adapter class and it will work i've checked this.
I hope this will help you.

Android ListAdapter not refreshing immediately after delete

In my android application, I have a list in fragment using an adapter which extends ArrayAdapter. Whenever you hold a row item for long you can delete that row by clicking Yes on an alert-dialogue. But when you click Yes, last row seems to be deleted. When you close that fragment and come back on it then the view is fine with proper row deleted. After debugging for so many days I am unable to fix this.Can anyone please figure out whats wrong ?
Thanks in advance.
AdapterClass
public class DuasListAdapter extends ArrayAdapter<String> {
// class variables
private final Context context;// to save context
private final List<String> duas;// to save list of stores
LayoutInflater inflater;// so save layout inflater for the view
public DuasListAdapter(Context ctx, List<String> duasList) {
super(ctx, R.layout.adapter_list_duas, duasList);
context = ctx;// save context
duas = duasList;// save list of stores
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);// save inflater layout
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
// if view is not loaded
if (!(convertView instanceof View)) {
convertView = inflater.inflate(R.layout.adapter_list_duas, parent, false);
// load the view from holder class
holder = new ViewHolder(convertView);
// set the tag for future use
convertView.setTag(holder);
}
// if view is loaded
else
// get view from tag
holder = (ViewHolder) convertView.getTag();
holder.duaIndex = position;
convertView.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
final View view = v;
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
ViewHolder holder = (ViewHolder) view.getTag();
int index = holder.duaIndex;
((MainActivity) context).removeItemFromList(index);
Toast.makeText(view.getContext(), "Deleted", Toast.LENGTH_LONG).show();
break;
case DialogInterface.BUTTON_NEGATIVE:
// No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Delete Dua from Favorites?").setPositiveButton("Yes", dialogClickListener).setNegativeButton("No", dialogClickListener).show();
return false;
}
});
return convertView;
}
ListFragment
public void removeItemFromList(int index) {
String verses = new SharedPreferencesSupplication().read(SingletonClass.keyListOfVerses, "a1");
String[] versesList = verses.split(",");
String identifier = versesList[index];
new FavoriteDuas().removeDua(identifier);
updatedData();
}
#Override
public void onResume() {
lvDuaas.setAdapter(duasAdapter);
updatedData();
super.onResume();
}
#Override
public void onPause() {
// TODO Auto-generated method stub
lvDuaas.setAdapter(duasAdapter);
updatedData();
super.onPause();
}
public void updatedData() {
boolean keyIsFavSel = new SharedPreferencesSupplication().read(SingletonClass.keyIsFavSelected, false);
if (keyIsFavSel)
new SharedPreferencesSupplication().save(SingletonClass.keyListOfVerses, new SharedPreferencesSupplication().read(SingletonClass.keyFavVerses, "a1"));
String verses = new SharedPreferencesSupplication().read(SingletonClass.keyListOfVerses, "a1");
String[] versesList = verses.split(",");
ArrayList<String> duas = new ArrayList<String>();
for (int i = 0; i < versesList.length; i++) {
if (versesList[i].length() > 0)
duas.add(versesList[i]);
}
duasAdapter.clear();
if (duas.size() > 0) {
for (String object : duas) {
duasAdapter.insert(object, duasAdapter.getCount());
}
}
duasAdapter.notifyDataSetChanged();
}
Delete-Method
public void removeDua(String duaIdentifier) {
String verses = new SharedPreferencesSupplication().read(SingletonClass.keyFavVerses, "");
String[] versesList = verses.split(",");
int indexFound = -1;
for (int i = 0; i < versesList.length; i++) {
if (versesList[i].equals(duaIdentifier)) {
indexFound = i;
break;
}
}
if (indexFound >= 0) {
verses = "";
for (int i = 0; i < versesList.length; i++) {
if (indexFound != i) {
if (verses.isEmpty())
verses = versesList[i];
else
verses = verses + "," + versesList[i];
}
}
new SharedPreferencesSupplication().save(SingletonClass.keyFavVerses, verses);
}
}
You can try to re-instantiate the duasAdapter
duasAdapter = new DuasListAdapter(your_context_here, duas);
instead of
duasAdapter.clear();
if (duas.size() > 0) {
for (String object : duas) {
duasAdapter.insert(object, duasAdapter.getCount());
}
}
duasAdapter.notifyDataSetChanged();
You are using setOnLongClickListener() on your view, use setOnItemLongClickListener() instead.

android dialog single choice change items search

I'm in an Android project.
I want to show a AlertDialog on which the user can pick one item (about 100 items, it's dynamic). I want to add the possibility of searching also.
My real problem is that it seems I can't change the items once the Dialog is created.
The creation code:
// The List with the beaches with radio buttons, single choice!
public void showBeachesDialog(final Activity context, boolean isFromZonas)
{
AlertDialog.Builder builder = new AlertDialog.Builder(context);
searchAdapter = new SearchDialogAdapater(orderedBeaches, orderedBeachesIds, context);
builder.setSingleChoiceItems(searchAdapter, -1, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
index = which;
if (!((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE).isEnabled())
((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
}
});
DialogOkOnClickListener listener = new DialogOkOnClickListener(context, isFromZonas);
builder.setPositiveButton(R.string.searchOK, listener);
builder.setNegativeButton(R.string.cancelar, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// User cancelled the dialog: nothing happens
}
});
builder.setIcon(context.getResources().getDrawable(R.drawable.icon_beach));
builder.setTitle(StaticUtils.DIALOG_TITLE);
View dialogView = context.getLayoutInflater().inflate(R.layout.dialog_beaches, null);
SearchView searchView = (SearchView)dialogView.findViewById(R.id.search_beach);
searchView.setOnQueryTextListener(new SearchQueryListener(searchAdapter));
builder.setView(dialogView);
AlertDialog dialog = builder.create();
dialog.show();
dialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(false);
}
So, now I have the dialog with all the elements I want (the SearchDialogAdapater is fine).
The DialogOnClickListener is also working.
The search view is appearing on the dialog, and my SearchQueryListener is working perfectly, so I won't post here the code, but in Debug I can see that if I type "d" the elements without the "d" are filtered out.
Now I would like to not throw away all the code and find a way to change the items of the dialog without showing a new one...
Sorry for long question and if there is a obvious way I am missing...
Thank you all.
I solved this using a class that implements 4 interfaces so it can handles everything that I want.
The code is now like this, hope it's useful to someone who want to make its own Dialog with personalized search.
public void showBeachesDialog(final Activity context, boolean isFromZonas)
{
AlertDialog.Builder builder = new AlertDialog.Builder(context);
searchAdapter = new SearchDialogAdapater
(orderedBeaches, orderedBeachesIds, context, isFromZonas);
builder.setSingleChoiceItems(searchAdapter, -1, null);
builder.setPositiveButton(R.string.searchOK, searchAdapter);
builder.setNegativeButton(R.string.cancelar, null);
builder.setIcon(context.getResources().getDrawable(R.drawable.icon_beach));
builder.setTitle(StaticUtils.DIALOG_TITLE);
View dialogView = context.getLayoutInflater().inflate
(R.layout.dialog_beaches, null);
SearchView searchView = SearchView)dialogView.findViewById
(R.id.search_beach);
searchView.setOnQueryTextListener(searchAdapter);
builder.setView(dialogView);
AlertDialog dialog = builder.create();
dialog.show();
dialog.getListView().setOnItemClickListener(searchAdapter);
searchAdapter.setDialog(dialog);
dialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(false);
}
The orderedBeaches and orderedBeachesIds are String[] and int[], my data to display.
Below is my adapter which uses a stack to handle the items available at any moment of the searching:
public class SearchDialogAdapater implements ListAdapter, OnQueryTextListener,
OnItemClickListener, OnClickListener {
protected Stack<String[]> stackBeaches;
protected Stack<int[]> stackBeachesIds;
protected Activity context;
protected TreeMap<String, Integer> orderedBeaches;
protected ListView listView;
protected String lastFilter = "";
public SearchDialogAdapater(String[] bs, int[] bIds, Activity cont) {
this.stackBeaches = new Stack<String[]>();
this.stackBeachesIds = new Stack<int[]>();
this.stackBeaches.push(bs);
this.stackBeachesIds.push(bIds);
this.context = cont;
}
#Override
public boolean onQueryTextChange(String newText) {
filter(newText);
this.listView.setAdapter(this);
return true;
}
public void filter(String search) {
// no longer valid the previous selected, must clean selections
selectedPosition = -1;
lastView = null;
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
// hitted "backspace"
if (search.length() < lastFilter.length()) {
if (stackBeaches.size() > 1) {
stackBeaches.pop();
stackBeachesIds.pop();
}
lastFilter = search;
return;
}
// filter
ArrayList<String> filtBs = new ArrayList<String>();
ArrayList<Integer> filtBsIds = new ArrayList<Integer>();
for (int i = 0; i < stackBeaches.peek().length; i++) {
String beach = new String(stackBeaches.peek()[i]);
if (Pattern
.compile(Pattern.quote(search), Pattern.CASE_INSENSITIVE)
.matcher(beach).find()) {
filtBs.add(beach);
filtBsIds.add(stackBeachesIds.peek()[i]);
}
}
String[] beaches = new String[filtBs.size()];
int[] ids = new int[filtBsIds.size()];
int size = filtBs.size();
for (int i = 0; i < size; i++) {
ids[i] = filtBsIds.remove(0);// head
beaches[i] = filtBs.remove(0);
}
stackBeachesIds.push(ids);
stackBeaches.push(beaches);
lastFilter = search;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
String beach = stackBeaches.peek()[position];
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.dialog_item, null);
TextView txtBeach = (TextView) convertView
.findViewById(R.id.dialBeach);
txtBeach.setText(beach);
}
if (position == selectedPosition)// the same color below
convertView.setBackgroundColor(Color.argb(128, 0, 64, 192));
return convertView;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return stackBeachesIds.peek()[position];
}
#Override
public int getCount() {
return stackBeaches.peek().length;
}
#Override
public boolean isEmpty() {
return stackBeaches.peek().length == 0;
}
private View lastView;
private int selectedPosition = -1;
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long arg3) {
// some color...
view.setBackgroundColor(Color.argb(128, 133, 181, 255));
selectedPosition = position;
if (lastView != null)
lastView.setBackground(null);
lastView = view;
((SurfApplication) context.getApplication()).setBeachId(stackBeachesIds
.peek()[position]);
if (!dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled())
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
}
protected AlertDialog dialog;
public void setDialog(AlertDialog dial) {
this.dialog = dial;
this.listView = dialog.getListView();
}
#Override
public void onClick(DialogInterface dialog, int which) {
((ProgressBar) context.findViewById(R.id.pBar))
.setVisibility(ProgressBar.VISIBLE);
int beachId = stackBeachesIds.peek()[selectedPosition];
String beach = stackBeaches.peek()[selectedPosition];
// do something... Here I am creating a new Intent and starting
// the new activity within my context
}
}
Same methods are not here because they return null or do nothing at all.
Sorry for long post, but I need to answer this properly.
Thank you all and I hope someone find this useful.
Your adapter needs to implement Filterable or extend from an adapter class that does. Adapters that already implement this interface, like ArrayAdapter, should do the filtering automatically for you.
Just call Adapter.getFilter().filter(...); with the value from the search view.

Deleting list item form list view in android

I read many more realted to this problem but not getting more idea. After this, i am trying to post, here in this picture I have 3 items on list, I have 2 item click. So I want to delete these two checked item. But i am the newbie for android, So could not get more idea behind this.
Code
public class CountryList extends Activity implements OnClickListener,
OnItemClickListener {
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return tempCountry.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.bookmarks_list_item,
null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView
.findViewById(R.id.country);
holder.checkBox = (CheckedTextView) convertView
.findViewById(android.R.id.checkbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtcnt.setText(country[position]);
return convertView;
}
static class ViewHolder {
TextView txtcnt;
CheckBox checkBox;
}}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bokmarksjoks);
try {
db = (new DatabaseHelper(this)).getWritableDatabase();
} catch (IOException e) {
e.printStackTrace();
}
lv = (ListView) findViewById(R.id.list);
btn_delete = (Button) findViewById(R.id.delete);
btn_delete.setOnClickListener(this);
checkbox = (CheckBox) findViewById(R.id.checkbox);
txtname= (TextView) findViewById(R.id.body);
String name= pref.getString("name", "");
country= name.split(",");
lv.setAdapter(new EfficientAdapter(this));
lv.setItemsCanFocus(false);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setOnItemClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.delete:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder .setMessage("Are you Sure want to delete checked country ?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// how to remove country
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.setTitle("Delete Country");
alert.show();
case R.id.checkbox:
//What is the procedue in this section
default:
break;
}
}
public void onItemClick(AdapterView<?> pareant, View view, int position,
long id) {
try {
// I have trying this but could not proper output or only errors
SparseBooleanArray sp = lv.getCheckedItemPositions();
/*String str = "";
for (int i = 0; i < sp.size(); i++) {
str += country[sp.keyAt(i)] + ",";
}*/
} catch (Exception e) {
e.printStackTrace();
}}}
This is the only three country, actually, I have more then hundreds countries.
Delete items from tempCountry and then call adapter.notifyDataSetChanged().
Have a button on list and let it onclick feature in xml
like to get postion first
public void OnClickButton(View V){
final int postion = listView.getPositionForView(V);
System.out.println("postion selected is : "+postion);
Delete(postion);
}
public void Delete(int position){
if (adapter.getCount() > 0) {
//Log.d("largest no is",""+largestitemno);
//deleting the latest added by subtracting one 1
comment = (GenrricStoring) adapter.getItem(position);
//Log.d("Deleting item is: ",""+comment);
dbconnection.deleteComment(comment);
List<GenrricStoring> values = dbconnection.getAllComments();
//updating the content on the screen
this.adapter = new UserItemAdapter(this, android.R.layout.simple_list_item_1, values);
listView.setAdapter(adapter);
}
else
{
int duration = Toast.LENGTH_SHORT;
//for showing nothing is left in the list
Toast toast = Toast.makeText(getApplicationContext(),"Db is empty", duration);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}

Nothing to deleted checked item in listview in android

I am trying to deleted checked item in listview in android, but I haven't achive this, why? my code is below. please response . I have try this code as well , which has not get more idea.
How to delete check box items from list
and many more related to delete list item form list view.
public class BookmarksJokes extends Activity implements OnClickListener,
OnItemClickListener {
ListView lv;
static ArrayList<Integer> checks=new ArrayList<Integer>();
static String[] tempTitle = new String[100];
static String[] tempBody = new String[100];
static String[] pos = new String[100];
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return tempTitle.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.bookmarks_list_item,
null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView
.findViewById(R.id.titleJok);
holder.text2 = (TextView) convertView
.findViewById(R.id.bodyJok);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.checkBox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(((CheckBox)v).isChecked()){
checks.set(position, 1);
}
else{
checks.set(position, 0);
}
}
});
holder.text1.setText(tempTitle[position]);
holder.text2.setText(tempBody[position]);
return convertView;
}
class ViewHolder {
TextView text1;
TextView text2;
CheckBox checkBox;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bokmarksjoks);
try {
db = (new DatabaseHelper(this)).getWritableDatabase();
} catch (IOException e) {
e.printStackTrace();
}
setUpViews();
for(int b=0;b<tempTitle.length;b++){
checks.add(b,0); //Assign 0 by default in each position of ArrayList
}
String one = pref.getString("title", "");
String two = pref.getString("body", "");
tempTitle = one.split(",");
tempBody = two.split(",");
lv.setAdapter(new EfficientAdapter(this));
lv.setItemsCanFocus(false);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setOnItemClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.delete:
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setMessage("Are you Sure want to delete all checked jok ?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
for(int i=0;i<checks.size();i++){
if(checks.get(i)==1){
Log.d(TAG, "i Value >>"+i);
checks.remove(i);
// i--;
Log.d(TAG, "checked Value >>"+checks);
Log.d(TAG, "i Value -- >>"+i);
}
}
((EfficientAdapter)lv.getAdapter()).notifyDataSetChanged();
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
alert.setTitle("Delete Jokes");
alert.show();
case R.id.checkbox:
default:
break;
}
}
please update this code with no errors. Or give be best idea for this.
You are removing items from a list while traversing it. At least you must make sure to account for the removed item in the counter variable and the list size (which is why there is an i-- in the original code, but you have commented it out).
I.e. after you deleted the item with index 2, the next in the list is still 2, not 3.
Un-comment the i--, that should fix it.
you want to delete checked item, but not modifying data source of list, please load data source from checks list. as Below:
public class BookmarksJokes extends Activity implements OnClickListener,
OnItemClickListener {
ListView lv;
static ArrayList<Integer> checks=new ArrayList<Integer>();
static ArrayList<String> tempTitle = new String[100];
static ArrayList<String> tempBody = new String[100];
static String[] pos = new String[100];
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return tempTitle.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.bookmarks_list_item,
null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView
.findViewById(R.id.titleJok);
holder.text2 = (TextView) convertView
.findViewById(R.id.bodyJok);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.checkBox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(((CheckBox)v).isChecked()){
checks.set(position, 1);
}
else{
checks.set(position, 0);
}
}
});
holder.text1.setText(tempTitle.get(position));
holder.text2.setText(tempBody.get(position));
return convertView;
}
class ViewHolder {
TextView text1;
TextView text2;
CheckBox checkBox;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bokmarksjoks);
try {
db = (new DatabaseHelper(this)).getWritableDatabase();
} catch (IOException e) {
e.printStackTrace();
}
setUpViews();
for(int b=0;b<tempTitle.size();b++){
checks.add(b,0); //Assign 0 by default in each position of ArrayList
}
String one = pref.getString("title", "");
String two = pref.getString("body", "");
String[] tokens = one.split(",");
tempTitle=Arrays.asList(tokens);
tokens= two.split(",");
tempBody =Arrays.asList(tokens);
lv.setAdapter(new EfficientAdapter(this));
lv.setItemsCanFocus(false);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setOnItemClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.delete:
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setMessage("Are you Sure want to delete all checked jok ?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
for(int i=0;i<checks.size();i++){
if(checks.get(i)==1){
Log.d(TAG, "i Value >>"+i);
checks.remove(i);
tempTitle.remove(i);
tempBody.remove(i);
// i--;
Log.d(TAG, "checked Value >>"+checks);
Log.d(TAG, "i Value -- >>"+i);
}
}
((EfficientAdapter)lv.getAdapter()).notifyDataSetChanged();
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
alert.setTitle("Delete Jokes");
alert.show();
case R.id.checkbox:
default:
break;
}
}

Categories

Resources