I've created a listview which takes the input from the alertDialog editText and populate it. Everything is working fine but after deleting the item from the row and adding something again it adds up the previous deleted item also which is not a good thing. I know the clear picture of my problem but it is difficult to find out whether how to do that.
This is my code where I'm adding the list inside the listView :
Adding Items
{ items[items.length - 1] = value;
List<String> newList = new LinkedList<String>(Arrays.asList(items));
//Log.e("STRIING", newArray.toString());
adapter = new MyListAdapter(RecyclerActivity.this, newList);
mListView.setAdapter(adapter);
String[] temp = new String[items.length + 1];
for (int i = 0; i < items.length; i++)
temp[i] = items[i];
items = temp;
alertDialog.dismiss();
adapter.notifyDataSetChanged();
input.getText().clear();
}
In here I have to notify the changes of the deleted item in order to get the desired result but i don't know how.
Here is the place where I'm deleting the item from the listview:
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> adapterView, View view, int i, long l) {
final String pos = mListView.getItemAtPosition(i).toString();
Log.e("POS", pos);
deleteDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
adapter.remove(pos);
adapter.notifyDataSetChanged();
}
});
deleteDialog.show();
}
});
and here is the MyAdapter class which binds the data :
public class MyListAdapter extends ArrayAdapter<String>{
private final Context context;
private final List<String> values;
class ViewHolder {
public TextView text;
}
public MyListAdapter(Context context, List<String> newList) {
super(context, R.layout.row_item, newList);
this.context = context;
this.values = newList;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.row_item, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.tvItem);
textView.setText(values.get(position));
return rowView;
}
}
My adapter is the Global Variable
I've tried using this in order to see whether the problem is getting fixed or not by following this link :
Deleting the items for the listview
The code looked like this now . :
newList.remove(pos);
adapter.notifyDataSetChanged();
newList is nothing but a List<> of type String
Please help me with this because I have wasted a long hour in this only. Thanks in advance.
EDITS
I've tried adding this in my Adapter Class, but this is giving me the same result :
public void removeItem(String position) {
values.remove(position);
notifyDataSetChanged();
}
Calling this method like this
adapter.removeItem(pos);
But same result
SOLVED
I've solved this problem by defining the single ArrayList in Global and using it. Made my work easy.
In my add section I've changed it like this
{
newArrayList.add(value);
adapter = new MyListAdapter(RecyclerActivity.this, newList);
mListView.setAdapter(adapter);
String[] temp = new String[items.length + 1];
for (int i = 0; i < items.length; i++)
temp[i] = items[i];
items = temp;
alertDialog.dismiss();
adapter.notifyDataSetChanged();
input.getText().clear();
}
Just creation of single variable as the array works smoothly.
Related
After a tremendous amount of time searching in here, and everywhere else I am hopeless to find a solution.
So here is my problem.
I have created a list-view and on top of that I added a search-bar.
When I use the search-bar, to filter the results... when I click on item 7, instead of opening the specific clicked activity i.e. 7, it always starts from the first one.
I am looking forward to your help guys; because I need it!
public class Group extends ListActivity {
// ArrayList thats going to hold the search results
ArrayList<HashMap<String, Object>> searchResults;
// ArrayList that will hold the original Data
ArrayList<HashMap<String, Object>> originalValues;
LayoutInflater inflater;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grouplist);
final EditText searchBox = (EditText) findViewById(R.id.searchBox);
ListView playersListView = (ListView) findViewById(android.R.id.list);
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final EditText searchBox = (EditText) findViewById(R.id.searchBox);
ListView playersListView = (ListView) findViewById(android.R.id.list);
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// these arrays are just the data that
// I'll be using to populate the ArrayList
String names[] = {/*list of names*/ };
String teams[] = {/*list of teams*/};
Integer[] photos = {R.drawable.... /*list of drawables*/};
Integer[] id ={/*Position*/};
originalValues = new ArrayList<HashMap<String, Object>>();
// temporary HashMap for populating the Items in the ListView
HashMap<String, Object> temp;
// total number of rows in the ListView
int noOfPlayers = names.length;
// now populate the ArrayList players
for (int i = 0; i < noOfPlayers; i++) {
temp = new HashMap<String, Object>();
temp.put("name", names[i]);
temp.put("team", teams[i]);
temp.put("photo", photos[i]);
temp.put("id", id[i]);
// add the row to the ArrayList
originalValues.add(temp);
}
// searchResults=OriginalValues initially
searchResults = new ArrayList<HashMap<String, Object>>(originalValues);
final CustomAdapter adapter = new CustomAdapter(this, R.layout.players, searchResults);
// finally,set the adapter to the default ListView
playersListView.setAdapter(adapter);
searchBox.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
// get the text in the EditText
String searchString = searchBox.getText().toString();
int textLength = searchString.length();
// clear the initial data set
searchResults.clear();
for (int i = 0; i < originalValues.size(); i++) {
String playerName = originalValues.get(i).get("name").toString();
if (textLength <= playerName.length()) {
// compare the String in EditText with Names in the
// ArrayList
if (searchString.equalsIgnoreCase(playerName.substring(0, textLength)))
searchResults.add(originalValues.get(i));
}
}
adapter.notifyDataSetChanged();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
}
});
// listening to single list item on click
playersListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int pos=Integer.ParseInt(searchResults.get(position).get("id").toString());
switch (pos) {
case 0:
Intent newActivity = new Intent(TeamsList.this, Barca.class);
startActivity(newActivity);
break;
case 1:
etc...
}
}
}
});
}
Custom adapter Class:
private class CustomAdapter extends ArrayAdapter<HashMap<String, Object>> {
public CustomAdapter(Context context, int textViewResourceId, ArrayList<HashMap<String, Object>> Strings) {
// let android do the initializing :)
super(context, textViewResourceId, Strings);
}
// class for caching the views in a row
private class ViewHolder {
ImageView photo;
TextView name, team;
}
ViewHolder viewHolder;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.players, null);
viewHolder = new ViewHolder();
// cache the views
viewHolder.photo = (ImageView) convertView.findViewById(R.id.photo);
viewHolder.name = (TextView) convertView.findViewById(R.id.name);
viewHolder.team = (TextView) convertView.findViewById(R.id.team);
//Take one textview in listview design named id
viewHolder.id = (TextView) convertView.findViewById(R.id.id);
// link the cached views to the convert view
convertView.setTag(viewHolder);
} else
viewHolder = (ViewHolder) convertView.getTag();
int photoId = (Integer) searchResults.get(position).get("photo");
// set the data to be displayed
viewHolder.photo.setImageDrawable(getResources().getDrawable(photoId));
viewHolder.name.setText(searchResults.get(position).get("name").toString());
viewHolder.team.setText(searchResults.get(position).get("team").toString());
viewHolder.id.setText(searchResults.get(position).get("id").toString());
// return the view to be displayed
return convertView;
}
}
}
I think you cant find correct position on listview item click. so u can use one textview with visibility="Gone" and insert the position in that textview in every row. now u can easily access position while clicking on item with the value of textview which shows perfect position. Hope it works. Thanx
The problem is that Adapter is populated once but with search results it gets overViewed by the searched items so on clicking it refers to the original items of list instead of the filtered list once , so we have to use the filtered lists' positions instead of the original one, i also faced this problem, try this:
In your listView.setOnItemClickListener
playersListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
//Object objFilteredItem = parent.getItemAtPosition(position);
//String a = searchResults.get(position);
switch (Integer.parseInt((String) adapter.getItem(position))) {
case 0:..
Intent newActivity = new Intent(TeamsList.this,Barca.class);
startActivity(newActivity);
break;
case 1:
etc...
break;
}
}
});
As from my previously answered question here, you have to override the getItem(position) method in your CustomAdapter. You are setting the onItemClick somewhat correctly but the list adapter doesn't know what exactly it's getting from getItem(position).
EDIT (details): You need to add something like this in your custom adapter -
#Override
public Object getItem(int position) {
return list.get(position);
}
You should already have the list in your custom adapter. If not, you can add a list reference to your CustomAdapter:
private ArrayList<HashMap<String, Object>> list;
Then setting it using a setter in your Group activity:
customAdapter.setList(searchResults);
This is a follow on from an earlier question: ImageButton within row of ListView android not working
But after suggestions from SO gurus it has been suggested I post a new question.
The issue is that I have a custom adapter that is not showing any data. I have looked into other questions, but it didn't provide a solution.
In my Main Activity I have a couple of buttons, one of them: ToDo, should create a row that displays data from a SQLite database, and depending on some factors (dates mainly), it shows a type of traffic light that is stored as a drawable.
Part of the Items in this Row is an Image Button that I want the user to be able to click and the image should change. The user should be able also to click on the actual row and a new activity starts.
The issue I have is that NO DATA is being displayed.
So, here is my code:
public class MainActivity extends Activity {
// definitions etc ...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// definitions etc ...
}
public void ToDo(View v){ // the user has clicked in the ToDo button
IgroDatabaseHelper helper = new IgroDatabaseHelper(getBaseContext()); // create instance of SQLIte database
numRows = helper.NumEntries("ToDo"); // Get the number of rows in table
int i = 1;
ArrayList<RowItem> rowItems = new ArrayList<>();
RowItem myItem1;
while (i <= numRows){
// get items from database
// depending on value select different drawable
// put data into List Array of RowItem
myItem1 = new RowItem(TheWhat, R.drawable.teamworka, R.drawable.redtrafficlight, R.drawable.checkbox, TheWhenBy);
rowItems.add(myItem1);
//
i = i+ 1;
}
ListView yourListView = (ListView) findViewById(R.id.list);
CustomListViewAdapter customAdapter = new CustomListViewAdapter(this, R.layout.todo_row, rowItems);
yourListView.setAdapter(customAdapter);
}
The CustomListViewAdapter looks like this:
public class CustomListViewAdapter extends ArrayAdapter<RowItem> {
Context context;
ArrayList<RowItem> _rowItems;
public CustomListViewAdapter(Context context, int resourceId,
ArrayList<RowItem> rowItems) {
super(context, resourceId);
this.context = context;
_rowItems = rowItems;
System.out.println("I am in the custom Adapter class "+ _rowItems);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
System.out.println("This is the get view");
View row = convertView;
RowItem item = _rowItems.get(position);
// you can now get your string and drawable from the item
// which you can use however you want in your list
String columnName = item.getColumnName();
int drawable = item.getDrawable();
if (row == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = mInflater.inflate(R.layout.todo_row, parent, false);
}
ImageButton chkDone = (ImageButton) row.findViewById(R.id.chkDone);
chkDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentRow = (View) v.getParent();
ListView listView = (ListView) parentRow.getParent();
final int position = listView.getPositionForView(parentRow);
System.out.println("I am in position "+ position);
}
});
return row;
}
}
The RowItem Class looks like:
public class RowItem {
private String _heading;
private int _icon;
private int _lights;
private int _chkdone;
private String _date;
public RowItem(String heading, int icon, int lights, int chkDone, String date) {
_heading = heading;
_icon = icon;
_lights = lights;
_chkdone = chkDone;
_date = date;
System.out.println("adding stuff to my rows");
System.out.println("my column Name is " + heading);
System.out.println("My drawable int is "+ icon);
}
public String getColumnName() {
System.out.println("column Names is "+ _heading);
return _heading;
}
public int getDrawable() {
return _icon;
}
public int getLights(){
return _lights;
}
public int getchkDone(){
return _chkdone;
}
public String getDate(){
return _date;
}
}
I am obviously missing something, as I mentioned earlier, no data gets shown. I know that there are 2 row items that get passed to the CustomListViewAdapter. But I also know that the View getView inside the CustomListViewAdapter does not actually get called.
I hope I have put enough information/code, but if you feel I need to explain something further, please say.
Thanking all very much in advance!
I don't see a getCount() method. You should be overriding it like this:
#Override
public int getCount() {
return _rowItems.getCount();
}
Alternatively, calling super(context, resourceId, rowItems); should also fix it.
Your ListView thinks there are no items to display. If you are using your own array, you must override the getCount() method to indicate the number of items you want to display.
I have implemented a custom adapter and listItemView. The adapter sets an onlclick listener to a button that is on the listItemView. The onclick listener simply calls a private method I have in the adapter and passes it the position of the item to be removed. I know the position is correct because the database removes the proper item. I have found similar questions but have not been able to adapt the answers to work for me. Ideas and thoughts are greatly appreciated. Thanks.
Here is the full adapter class
public class FoodListAdapter extends ArrayAdapter<FoodListItem> {
//private
private int type;
public FoodListAdapter(Context context, ArrayList<FoodListItem> _objects) {
super(context, 0, _objects);
type = 0;
}
public FoodListAdapter(Context context, ArrayList<FoodListItem> _objects, int _type) {
super(context, 0, _objects);
type = _type;
}
#Override
public View getView(int position, View reusableView, ViewGroup parent)
{
//Cast the reusable view to a listAdpaterItemView
FoodListItemView listItemView = (FoodListItemView) reusableView;
//Check if the listAdapterItem is null
if(listItemView == null)
{
//If it is null, then create a view.
listItemView = FoodListItemView.inflate(parent, this, type);
}
if (type == 2)
{
Button deleteButton = (Button) listItemView.findViewById(R.id.listItemViewDeleteBTN);
deleteButton.setTag(new Integer(position));
}
//Now we need to set the view to display the data.
listItemView.setData(getItem(position));
return listItemView;
}
}
Here is a portion of my code used in fragment. Note that I have a private variable decalred in the class for listAdapter, though I don't think I need that.
private void displayListForDate(Calendar _date)
{
//get the list view
ListView listView = (ListView) getView().findViewById(1);
//Clear the listview by removing the listadapter and setting it to null.
//listView.setAdapter(null);
//First we must get the items.
Global global = (Global) getActivity().getApplicationContext();
DietSQLiteHelper database = global.getDatabase();
//Create a list to hold the items we ate. This list will then be added to the listView.
final ArrayList<FoodListItem> consumedList;
//Add the items to the array.
consumedList = database.getConsumed(_date.getTimeInMillis());
//Create an adapter to be used by the listView
listAdapter = new FoodListAdapter(getActivity().getBaseContext(), consumedList, 2);
//Add the adapter to the listView.
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
consumedList.remove(position);
listAdapter.notifyDataSetChanged();
}
});
}
If you didn't implement "equals" method of FoodListItem, try to implements it.
I would suggest,
that you just update the underlying data, in your case its ArrayList<FoodItems>.
In your Adapter make this simple method and change :
private List<FoodListItem> myList = new ArrayList<FoodListItem>();
public FoodListAdapter(Context context, List<FoodListItem> myList) {
super(context, 0, myList);
type = 0;
this.myList = myList;
}
public FoodListAdapter(Context context, List<FoodListItem> myList, int _type) {
super(context, 0, myList);
type = _type;
this.myList = myList;
}
// Also update your getView() method to use myList!
#Override
public View getView(int position, View reusableView, ViewGroup parent)
{
...
listItemView.setData(myList.get(position));
public void removeItem(int positio){
if(myList != null){
myList.remove(position);
}
}
And then in class, you are creating the adapter (Activity/Fragment), just call the method.
// Update the underlying ArrayAdapter
adapter.removeItem(position);
// Notify the adapter, the data has changed
adapter.notifyDataSetChanged();
Also, you shouldnt open connection to your SQLiteDatabase on UI thread, because you are blocking it. You never know, how fast is the reading from disk going to be. If it takes too long, user can think, that your application froze and therefore, he leaves, which you dont want. I would suggest to use AsyncTask, you will find a lot of examples.
I went through and cleaned up my code and it now works, here is the working code. I really don't know exactly the difference other than I updated the IDs that I was using to assign and get views. If anyone can explain the cause for the issue I was having I would appreciate it.
Here is the snippet from my fragment where I create the list view and assign an adapter.
private void displayListForDate(Calendar _date)
{
//get the list view
ListView listView = (ListView) getView().findViewById(R.id.listView);
//Clear the listview by removing the listadapter and setting it to null.
//listView.setAdapter(null);
//First we must get the items.
Global global = (Global) getActivity().getApplicationContext();
DietSQLiteHelper database = global.getDatabase();
//Create a list to hold the items we ate. This list will then be added to the listView.
ArrayList<FoodListItem> consumedList;
//Add the items to the array.
consumedList = database.getConsumed(_date.getTimeInMillis());
//Create an adapter to be used by the listView
listAdapter = new FoodListAdapter(getActivity().getBaseContext(), consumedList, 2);
//Add the adapter to the listView.
listView.setAdapter(listAdapter);
}
and here is my adapter class.
public class FoodListAdapter extends ArrayAdapter<FoodListItem>
{
//private
private int type;
public FoodListAdapter(Context context, ArrayList<FoodListItem> _objects) {
super(context, 0, _objects);
type = 0;
}
public FoodListAdapter(Context context, ArrayList<FoodListItem> _objects, int _type) {
super(context, 0, _objects);
type = _type;
}
#Override
public View getView(int position, View reusableView, ViewGroup parent)
{
//Cast the reusable view to a listAdpaterItemView
FoodListItemView listItemView = (FoodListItemView) reusableView;
//Check if the listAdapterItem is null
if(listItemView == null)
{
//If it is null, then create a view.
listItemView = FoodListItemView.inflate(parent, type);
}
if (type == 2)
{
Button deleteButton = (Button) listItemView.findViewById(R.id.listItemViewDeleteBTN);
deleteButton.setTag(new Integer(position));
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Integer tag = (Integer) view.getTag();
deleteItem(tag.intValue());
}
});
}
//Now we need to set the view to display the data.
listItemView.setData(getItem(position));
return listItemView;
}
private void deleteItem(int position)
{
FoodListItem item = getItem(position);
Global global = (Global) getContext().getApplicationContext();
DietSQLiteHelper database = global.getDatabase();
database.removeConsumed(item.getID());
remove(getItem(position));
}
}
So I have a listview that I want to add checkboxes to.
lv = (ListView)findViewById(R.id.list);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, listItems);
lv.setAdapter(adapter);
lv.setItemsCanFocus(true);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
This works and the checkboxes show up. Then I have my setOnItemClickListener() for my listview because the user needs to select an item, then the next acitivty will be launched
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
Intent components = new Intent();
components.setClass(context, ComponentsActivity.class);
components.putExtra("studyID", studyID);
components.putExtra("studyName", studyName);
startActivity(components);
}
});
However, I want to add a checkbox so that the user can tick that item in the listview to perform other actions. The problem is I can't differentiate the events. When I click on the checkbox, it gets checked but then the list item also gets selected and the new activity starts. I only want the checkbox to be affected when they click on it, not have it launch the new acitivty. I know you can also just create your own adapter but why bother if I can make a checkbox in 2 lines of code. Any suggestions? I just want to be able to check the textbox and get the id of the checked items.
I never managed to find anything for what I was looking for so I bit the bullet and decided to learn how to make my own custom adapter class. Here is my code if anybody ever runs into this problem. This adapter class is for a listview with text(TextView) and a checkbox.
public class CustomAdapter extends BaseAdapter
{
ArrayList<String> studies;
Context context;
LayoutInflater myInflater;
ArrayList<Boolean> positionArray;
public CustomAdapter(ArrayList<String> arr, Context c)
{
studies = arr;
context = c;
myInflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
positionArray = new ArrayList<Boolean>();
for(int i = 0; i < studies.size(); ++i)
{
positionArray.add(false);
}
}
#Override
public int getCount() {
return studies.size();
}
#Override
public Object getItem(int i) {
return studies.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
public void remove(int i)
{
this.studies.remove(i);
this.positionArray.remove(i);
}
#Override
public View getView(int position, View view, ViewGroup viewGroup)
{
final int pos = position;
Holder holder = null;
//Create the views and populate it with an element from teh array
if(view == null)
view = myInflater.inflate(R.layout.custom_list_layout, viewGroup, false);//made my own layout for each listview 'cell'
holder = new Holder();
TextView study = (TextView)view.findViewById(R.id.adapterTextView);
holder.ckbox = (CheckBox)view.findViewById(R.id.adapterCheckBox);
holder.ckbox.setOnCheckedChangeListener(null);
study.setText(studies.get(position));
holder.ckbox.setFocusable(false);
//Since this method gets called whenever we scroll(view recycling), we have to re-check the checkboxes
holder.ckbox.setChecked(positionArray.get(position));
holder.ckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
//checkBoxArray[pos].setChecked(isChecked);
positionArray.set(pos, isChecked);
}
});
return view;
}
static class Holder
{
CheckBox ckbox;
}
}
I've tried searching for a solution for this problem for a couple of days and I'm stumped.
Here's what I have so far:
Custom BaseAdapter class:
public static class ImageAdapter extends BaseAdapter {
private static LayoutInflater mInflater;
// Keep all Images in array
private static Bitmap[] mThumbIds;
private static int mViewResourceId, pos;
private static CheckBox cb;
// Constructor
public ImageAdapter(Context ctx, int viewResourceId, Bitmap[] pics) {
mInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mThumbIds = pics;
mViewResourceId = viewResourceId;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#SuppressWarnings("deprecation")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(mViewResourceId, list, false);
cb = (CheckBox) convertView.findViewById(R.id.select);
Drawable background = new BitmapDrawable(mThumbIds[position]);
cb.setBackgroundDrawable(background);
pos = position;
System.out.println("Setting checkbox set: "+imageIsDup[pos]);
cb.setChecked(imageIsDup[pos]);
System.out.println("Has checkbox been set? "+cb.isChecked());
cb.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (cb.isChecked()) {
imageIsDup[pos] = true;
} else
imageIsDup[pos] = false;
}
});
return convertView;
}
}
Code for setting the gridView:
final Dialog dialog = new Dialog(longOperationContext);
dialog.setContentView(R.layout.activity_list);
TextView no = (TextView) dialog
.findViewById(R.id.noOfDups);
no.setText("Found " + noOfImages
+ " duplicates. Please verify.");
dialog.setTitle("Images Found");
dialog.setCancelable(false);
list = (GridView) dialog
.findViewById(R.id.grid_view);
ImageAdapter empty=new ImageAdapter(longOperationContext, R.layout.row, new Bitmap[0]);
imageAdapter = new ImageAdapter(
longOperationContext, R.layout.row, thumb);
dialog.show();
imageAdapter.notifyDataSetChanged();
list.invalidateViews();
list.setAdapter(empty);
list.setEmptyView(new View(longOperationContext));
list.invalidateViews();
list.setAdapter(imageAdapter);
I assumed that this code would set the gridView to an empty view in the beginning and then to the adapter's contents.
I read from the documentation that the removeView functions cannot be called as they throw an Unsupported Exception. How do I clear the previous contents of the grid view if any and set the new contents?
The whole idea with refreshing adapter's elements in Android is just repopulate them using the same array of objects. For example if I have a GridView like in your case and I want to repopulate the objects the thing you need to do is declare an array of objects first :
private ArrayList<Object> mMyObjects;
populate it with data and create your adapter.
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
mMyObjects = new ArrayList<Object>();
mMyObject.add("StringObject"); // just an example
mMyAdapter = new MyCustomAdapter(this, mMyObject);
mMyGridView.setAdapter(mMyAdapter);
}
So we populate the array of objects and create our adapter. The thing we should do before updating the adapter / gridview's children is just repopulate your array :
mMyObjects.clear();
mMyObjects.add("NewStringObject");
and call : mMyAdapter.notifySetDataChanged(); Doing that BaseAdapter knows that there are changes in out data and it's redrawing it's views and your ListView / GridView will get updated with the new items.
So in your case, to update your GridView just need to clear your array of bitmaps and repopulate it.
I solved my problem with this piece of code:
try{
imageAdapter.notifyDataSetChanged();
}
catch(NullPointerException e)
{
imageAdapter = new ImageAdapter(
longOperationContext, R.layout.row, thumb);
}