What is the difference between listViewAdapter.clear() and list.clear()? - android

Okay, I think I have understood it, but I just want to make sure of it. I have got a ListViewAdapter that contains a List.What I wanna do is search thinks in the database and show in a ListView. This piece of code adds an item to my listView.
list.addAll(sqh.DisplayRecords(sqdb));
listViewAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,list);
listview.setAdapter(listViewAdapter);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listViewAdapter.clear();
list.clear();
list.addAll(sqh.DisplayRecords(sqdb));
list.add("another one");
}
});
Whit this other piece of code, only clearing the listviewAdapter and adding another item to the list, just, adds the last item, instead of all the items of the list, which should be there.
list.addAll(sqh.DisplayRecords(sqdb));
listViewAdapter = new ArrayAdapter( this,android.R.layout.simple_list_item_1,list);
listview.setAdapter(listViewAdapter);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listViewAdapter.clear();
list.add("another one");
}
});
Well, I think I understood it while I was writing this. The third one and the first one are pretty the same.
list.addAll(sqh.DisplayRecords(sqdb));
listViewAdapter = new ArrayAdapter( this,android.R.layout.simple_list_item_1,list);
listview.setAdapter(listViewAdapter);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listViewAdapter.clear();
list.addAll(sqh.DisplayRecords(sqdb));
list.add("another one");
}
});
The listViewAdapter.clear(); would be clearing the list of the adapter, right? Why, when I do just list.clear(), the list view is not cleared?

When you calling list.clear();, you'are removing all of the elements from the list. The list will be empty after this call returns. But your Adapter view isn't change yet. You need to call adapter.notifyDataSetChanged() to refresh the adapter.
In the other case, when you calling listViewAdapter.clear();, the list will be cleared first then the notifyDataSetChanged() called.
You can see the details in ArrayAdapter.clear() source code:
/**
* Remove all elements from the list.
*/
public void clear() {
synchronized (mLock) {
if (mOriginalValues != null) {
mOriginalValues.clear();
} else {
mObjects.clear();
}
mObjectsFromResources = false;
}
if (mNotifyOnChange) notifyDataSetChanged();
}

listViewAdapter.clear()
void clear ()
Remove all elements from the list.
And list.clear();
/**
* Removes all of the elements from this list. The list will
* be empty after this call returns.
*/
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
If you use in this , it was the same .It used to Removes all of the elements from this list .

Related

Adapter doesn't response after popping an AleartDialog from another fragment

Hello guys I am for first time here so if there are some mistakes with my problem just notify me to correct my self. My problem is in the adapter I think. My application is with 3 fragment tabs. In each tab I have a ListView with some items. Also I have button in each tab that updates,deletes or adds items. I make that by popping up an AleartDialog for adding a new item or clicking on the item from the list to update it or delete it. So after I login in my application I can do what ever I want with that list. Its not a problem. I can rotate the screen and my list still updates. Changing the tabs its not a problem also. The problem comes when I go to other fragment I click on the button for adding or on some of the items for updating and the AleartDialog pops up. After that when I close it I return to the first tab. Trying to add an item doesn't update the list and I see the same items. Deleting the item from the list then throws exception IndexOutOfBounds because the item its not in the list. I think I use arrayAdapter.notifyDataSetChanged() properly. Here I will share some other code.
Like that I update my list. In the jsonObject is list the with the items.
private void fillList(Gson gson, String jsonObject) {
listWithNames.clear();
Type collectionType = new TypeToken<ArrayList<PersonalSaveDTO>>() {
}.getType();
personalSaveList = gson.fromJson(jsonObject, collectionType);
Log.wtf(TAG, "OT REQUEST: " + personalSaveList);
for (int i = 0; i < personalSaveList.size(); i++) {
listWithNames.add(personalSaveList.get(i).getName());
}
Log.wtf(TAG, "fillList: " + listWithNames);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
arrayAdapter.notifyDataSetChanged();
buttonEnable(true);
}
});
}
Like that I starts the fragment.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View viewFragment = inflater.inflate(R.layout.user_fragment, container, false);
listViewUser = (ListView) viewFragment.findViewById(R.id.listViewForUser);
addItem = (Button) viewFragment.findViewById(R.id.buttonAddUserElements);
updateList = (Button) viewFragment.findViewById(R.id.refreshListUser);
updateList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
makeRequestForList(viewFragment);
}
});
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addElement(viewFragment);
}
});
configureArrayAdapter(viewFragment);
setListenerForUserList(viewFragment);
if (savedInstanceState != null) {
isRequestMade = savedInstanceState.getBoolean("isRequestMade");
listWithNames = savedInstanceState.getStringArrayList("listWithNames");
personalSaveList = savedInstanceState.getParcelableArrayList("personalSaveList");
arrayAdapter.addAll(listWithNames);
arrayAdapter.notifyDataSetChanged();
}
if (!isRequestMade) {
makeRequestForList(viewFragment);
isRequestMade = true;
}
return viewFragment;
}
And here is how I create the adapter.
private void configureArrayAdapter(View view) {
listWithNames = new ArrayList<>();
arrayAdapter = new ArrayAdapter<String>(view.getContext(),
R.layout.list_personal_group_fragment, R.id.adapterFragmentPersonalGroups, listWithNames);
arrayAdapter.clear();
listViewUser.setAdapter(arrayAdapter);
}

how to reload listview from another activity (adapter) class

i have tried all the things but i cant get proper result,i also try
adapter.clearAll()
adapter.notifyDataSetChanged()
but i cant get result when i delete row from list view its deleted from its position but when i change value of another row than the delete process working perfectly but changed value not set.getting value from database perfectly.
Here is my code please help me and tell where i m doing wrong.
Thank you in advance
Delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Identifier_fev = null;
String Default_Option = null;
String Quantity1 = null;
jffDatabase.open();
Cursor identifie = jffDatabase.getALL();
if (identifie.moveToPosition(position)) {
Identifier_fev = identifie.getString(identifie.getColumnIndexOrThrow("identifier"));
Default_Option = identifie.getString(identifie.getColumnIndexOrThrow("default_option"));
}
jffDatabase.delete(Identifier_fev, Default_Option);
identifier.remove(position);
title.remove(position);
defaultPrice.remove(position);
default_option.remove(position);
price.remove(position);
quantity.remove(position);
Cursor c1 = jffDatabase.getALL();
if (c1.moveToFirst()) {
do {
Quantity1 = c1.getString(c1.getColumnIndexOrThrow("quantity"));
update_quantity.add(Quantity1);
} while (c1.moveToNext());
}
for (int i = 0; i < update_quantity.size(); i++) {
Toast.makeText(ctx, "" + update_quantity, Toast.LENGTH_LONG).show();
Quantitylbl.setText(update_quantity.get(i).toString());
Toast.makeText(ctx, "set " + Quantitylbl.getText().toString(), Toast.LENGTH_LONG).show();
}
Quantity();
notifyDataSetChanged()
AddtoCartActivity.Cartcount.setText(String.valueOf(sum));
}
});
Good practice is use Interface
Create new Interface
public interface MyCustomObjectListener {
public void RefreshList();
//add parameter for delete if required ex-
//public void RefreshList(String Item_id);
}
then implement Activity by this Interface
YourActivityName extends Activity implements MyCustomObjectListener
And Implement Method
#Override
public void RefreshList() {
// Do your delete task and clear current List and get updated list task here
}
and from Base adapter onClick you can call method RefreshList like this
((YourActivityName)mContext).RefreshList();
you can delete and refresh list from #Override RefreshList

RecyclerView onItemClick() imitation, is it good practice?

I saw some different ways of implementing onItemClickListener for RecyclerView. My favourite is to use interface callback:
Interface:
public interface OnClickListener {
void onCardClick(View v);
void onFavouriteButtonClick(View v);
void onRemoveClick(View v);
//Other clickable areas
}
In adapter:
currentView.favouriteButton.setTag(currentItem.getId());
currentView.favouriteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (OnClickListener != null){
OnClickListener.onFavouriteButtonClick(v);
}
}
});
In main activity/fragment
adapter = new CardAdapter( .... new OnClickListener() {
#Override
public void onFavouriteButtonClick(View v) {
int id = Integer.parse(v.getTag().toString());
//Do your stuff
}
....
});
So, I have some questions:
is it good way of handling things?
will performance be slow if number of items will grow?
any reasons why I shouldn't use this approach?
I think you could improve upon this by not passing the view outside of the adapter.
// Create an object that encapulates the information for each card
public class CardInfo {
// Whatever you want to show in your card
}
// Create a listener for items instead of views
public interface OnCardAction {
void onCardSelected(CardInfo cardInfo);
void onFavoriteSelected(CardInfo cardInfo);
void onCardRemoved(CardInfo cardInfo);
}
// In your adapter
favoriteButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
// You many need to check if onCardActionLisetner is null
CardInfo cardInfo = getItemAt(viewHolder.getAdapterPosition());
onCardActionListener.onFavoriteSelected(cardInfo);
}
});
NOTE: If you are passing the listener in the constructor can either make it required (throw error if it is null) or not even create View.OnClickListner to reduce the number of null checks.

How to delete multiple Checked Listview items from sqlite database in android using baseAdapter

i want to delete multiple checked listview item from sqlite database in android. i have extends baseAdapter for listview. can any one suggest me how can i delete multiple checked items from sqlite database.
SparseBooleanArray sba=new SparseBooleanArray(); // declare globally in adapter
convertview.onClickListener(new View.onClickListener(){
#Override
public void onClick()
{
if(checkbox.isChecked())
{
sba.put(position,true);
}
else
{
sba.put(position,false);
}
});
on delete selected button click method
ArrayList itemstodeletelist=new ArrayList();
deleteselectedbutton.onClickListener(new View.onClickListener(){
#Override
public void onClick(){
for(int position=0;position<array.size();position++)
{
if(array.get(position))
{
itemstodeletelist.Add(itemslist[position]);
}
}
}
Now in db loop delete method with for each item in itemstodeletelist

ListFragment's setListShown method not working

I'm using ListFragment with ParseQueryAdapter in order to show list of leagues (custom model).
I managed to get my desired state except that the loading animation is not showing at all.
It seems like the animation is hidden when the listsAdapter is set (by setListAdapter method), so I set the adapter only after my list is fetched, but the parseQueryAdapter fetches the list only after setting the adapter to a list.
So I found that I can use the setListShown method in order to hide/show the animation, but in my current implementation it doesn't work.
My code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// Create query factory
ParseQueryAdapter.QueryFactory<League> factory = new ParseQueryAdapter.QueryFactory<League>() {
public ParseQuery<League> create() {
ParseQuery<League> query = League.getQuery();
query.whereEqualTo(League.FIELD_USER, ParseUser.getCurrentUser());
query.orderByDescending(League.FIELD_CREATED_AT);
return query;
}
};
// Create adapter
leagueListAdapter = new LeagueAdapter(getActivity(), factory);
// Loading listener
leagueListAdapter.addOnQueryLoadListener(new ParseQueryAdapter.OnQueryLoadListener<League>() {
#Override
public void onLoading() {
// Show ListFragment's loading animation while loading
setListShown(false);
}
#Override
public void onLoaded(List<League> leagues, Exception e) {
if(e == null){
// Hide loading animation and show the list
setListShown(true);
// Put leagues in the cache
LeaguesCache.getInstance().setCachedLeagues(leagues);
} else {
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
// Set fragment's adapter
setListAdapter(leagueListAdapter);
// Dialogs
addLeagueDialog = new addLeagueDialog(this);
}

Categories

Resources