Remove multiple items from List view except Selected items - android

I am making an android app in which there is one List view. On selecting the particular item for first time, I have changed text color of that item. Multiple selection is allowed for List view. Now there is one text view named "Done". When user clicks on "Done", items which are not selected from List view should be removed. What should I do? Below is my code...
tvDone.setOnClickListener(new OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if( colorRow > 0 )
{
AlertDialog builder = new AlertDialog.Builder(NewFriendList.this).create();
builder.setTitle("Save to List");
builder.setMessage("Do You Want to Save?");
builder.setButton("Save", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
tvEdit.setVisibility(View.VISIBLE);
tvClear.setVisibility(View.VISIBLE);
tvDelete.setVisibility(View.VISIBLE);
}
});
builder.setButton2("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
chkText.setTextColor(Color.BLACK);
tvEdit.setVisibility(View.INVISIBLE);
tvClear.setVisibility(View.INVISIBLE);
tvDelete.setVisibility(View.INVISIBLE);
}
});
builder.show();
}
else
Toast.makeText(getBaseContext(), "Select Friends", 1000).show();
}
});
lvDialog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
checked = lvDialog.getCheckedItemPositions();
chkText = (CheckedTextView) arg1.findViewById(R.id.txt);
if(checked.get(arg2))
{
chkText.setTextColor(Color.CYAN);
colorRow ++;
}
else
{
chkText.setTextColor(Color.BLACK);
colorRow--;
}
}
});

The standard way to do such actions is to use Action mode of action bar.
Anyways, Here's an example:
DataModel: This exposes data manipulation methods to local code. Here its just using in-memory data structures, but in real applications, it can be backed by a database or a web service or something else.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
public class DataModel {
private static DataModel ourInstance = new DataModel();
private final List<String> mPersons;
private final HashMap<String,Set<String>> mGroups;
public static DataModel getInstance() {
return ourInstance;
}
private DataModel() {
mPersons = new ArrayList<String>();
mGroups = new HashMap<String, Set<String>>();
for (int i = 0; i < 50; i++){
mPersons.add("person_"+i);
}
}
public void updateGroup(String oldName, String newName, Set<String> members){
assert newName != null && !newName.isEmpty() && members != null : "data must not be null or empty";
if(oldName != null){
mGroups.remove(oldName);
}
mGroups.put(newName, members);
}
public void deleteGroup(String name){
mGroups.remove(name);
}
public boolean isMember(String groupName, String memberName){
return mGroups.containsKey(groupName) && mGroups.get(groupName).contains(memberName);
}
public List<String> getGroups(){
List<String> groups = new ArrayList<String>();
for (String s : mGroups.keySet()){
groups.add(s);
}
return groups;
}
public List<String> getMembersOf(String groupName){
List<String> members = new ArrayList<String>();
if(mGroups.containsKey(groupName)){
members.addAll(mGroups.get(groupName));
}
return members;
}
public List<String> getPersons(){
List<String> persons = new ArrayList<String>();
persons.addAll(mPersons);
return persons;
}
}
Activity to List data: Allows action mode by long clicking any item, or edit an item by clicking on it.
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import java.util.ArrayList;
import java.util.List;
public class GroupActivity extends ListActivity implements AbsListView.MultiChoiceModeListener, AdapterView.OnItemClickListener {
public static final int REQ_CODE_EDIT_GROUP = 101;
private List<String> mSelection;
private ArrayAdapter<String> mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSelection = new ArrayList<String>();
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1);
mAdapter.addAll(DataModel.getInstance().getGroups());
setListAdapter(mAdapter);
getListView().setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setMultiChoiceModeListener(this);
getListView().setOnItemClickListener(this);
}
private void refresh(){
mAdapter.clear();
mAdapter.addAll(DataModel.getInstance().getGroups());
mAdapter.notifyDataSetInvalidated();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item = menu.add("New");
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getTitle().equals("New")){
startEditor(null);
return true;
}
return super.onOptionsItemSelected(item);
}
private void startEditor(String groupName){
Intent i = new Intent(this,EditorActivity.class);
if(groupName != null){
i.putExtra(EditorActivity.KEY_EDIT_GROUP,groupName);
}
startActivityForResult(i,REQ_CODE_EDIT_GROUP);
}
#Override
public void onItemCheckedStateChanged(ActionMode actionMode, int i, long l, boolean checked) {
if(checked){
mSelection.add(mAdapter.getItem(i));
}else {
mSelection.remove(mAdapter.getItem(i));
}
}
#Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
MenuItem item = menu.add("Delete");
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
if(menuItem.getTitle().equals("Delete")){
for (String groupName : mSelection){
DataModel.getInstance().deleteGroup(groupName);
}
refresh();
actionMode.finish();
return true;
}else {
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode actionMode) {
mSelection.clear();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQ_CODE_EDIT_GROUP && resultCode == RESULT_OK){
refresh();
}else {
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String groupName = mAdapter.getItem(i);
startEditor(groupName);
}
}
Activity to edit data : Allows editing names and selections etc.
It has a Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:id="#+id/edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Group name"
android:inputType="text"/>
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
And Activity code:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.*;
import java.util.HashSet;
public class EditorActivity extends Activity {
public static final String KEY_EDIT_GROUP = "edit_group";
private EditText mNameEdit;
private ListView mListView;
private ArrayAdapter<String> mAdapter;
private String mOldGroupName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editor);
mNameEdit = (EditText) findViewById(R.id.edit);
mListView = (ListView) findViewById(R.id.list);
mListView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1);
mAdapter.addAll(DataModel.getInstance().getPersons());
mListView.setAdapter(mAdapter);
mOldGroupName = getIntent().getStringExtra(KEY_EDIT_GROUP);
if(mOldGroupName != null){
mNameEdit.setText(mOldGroupName);
for (int i = 0 ; i < mAdapter.getCount(); i++){
DataModel dm = DataModel.getInstance();
String member = mAdapter.getItem(i);
if(dm.isMember(mOldGroupName,member)){
mListView.setItemChecked(i,true);
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item = menu.add("Done");
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getTitle().equals("Done")){
String newGroupName = mNameEdit.getText().toString();
if(newGroupName == null || newGroupName.isEmpty()){
Toast.makeText(this,"Invalid group name",Toast.LENGTH_LONG).show();
return true;
}
HashSet<String> selectedMembers = new HashSet<String>();
for (int i = 0 ; i < mAdapter.getCount(); i++){
if(mListView.isItemChecked(i)){
selectedMembers.add(mAdapter.getItem(i));
}
}
DataModel.getInstance().updateGroup(mOldGroupName,newGroupName,selectedMembers);
setResult(RESULT_OK);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}

Related

Checking if a list view adapter contains a string

I wanna check my adapter before adding new item and if there is a duplicate item then ignore it.I tried this method but didn't work for me.
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (radioGroup.getCheckedRadioButtonId()){
case R.id.Tshirt:
radio="Tshirt";
break;
case R.id.Shoes:
radio="Shoes";
break;
default:
radio="Pants";
break;
}
if (!txtname.getText().toString().isEmpty() && !txtdes.getText().toString().isEmpty() )
list.add(new products(txtname.getText().toString(), radio, txtdes.getText().toString(), R.drawable.shop));
myadapter adapter = new myadapter(MainActivity.this, list);
lstCountries.setAdapter(adapter);
}
});
You can simply check whether your list contains a certain String and / or object already.
if(!list.contains(...) {
list.add(..);
}
You can check this thread for more information:
Check if a String is in an ArrayList of Strings
If order is not important , then you could use HashSet instead of a list, a type of SET, these are the collections that do not allow duplicate values but do not preserve insertion order too.
Java HashSet
Example usage:-
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
Here is my code:
Mainactivity.java
package com.example.esi.shopapp;
import android.content.DialogInterface;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ListView lstCountries;
public Button btnadd;
private EditText txtname;
private EditText txtdes;
private RadioGroup radioGroup;
String radio = "";
private List<products> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstCountries = (ListView) findViewById(R.id.lists);
btnadd = findViewById(R.id.button);
txtname =findViewById(R.id.txt_name);
txtdes =findViewById(R.id.txt_desc);
radioGroup = findViewById(R.id.categorize);
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (radioGroup.getCheckedRadioButtonId()){
case R.id.Tshirt:
radio="Tshirt";
break;
case R.id.Shoes:
radio="Shoes";
break;
default:
radio="Pants";
break;
}
if (!txtname.getText().toString().isEmpty() && !txtdes.getText().toString().isEmpty() )
if (!list.contains(txtname.getText().toString()))
list.add(new products(txtname.getText().toString(), radio, txtdes.getText().toString(), R.drawable.shop));
myadapter adapter = new myadapter(MainActivity.this, list);
lstCountries.setAdapter(adapter);
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.clear_form:
txtname.setText("");
txtdes.setText("");
break;
case R.id.clear_list:
lstCountries.setAdapter(null);
break;
case R.id.setting:
break;
case R.id.exit:
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Are you sure to exit?");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MainActivity.this.finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
break;
}
return super.onOptionsItemSelected(item);
}
}
myadapter.java
package com.example.esi.shopapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class myadapter extends BaseAdapter {
private Context context;
private List<products> list;
public myadapter(Context context, List<products> list) {
this.context = context;
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup root) {
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_layout, root, false);
}
TextView txtCountryName = convertView.findViewById(R.id.txt_product_name);
TextView txtCountryContinent = convertView.findViewById(R.id.txt_product_desc);
TextView txtype = convertView.findViewById(R.id.txt_product_type);
ImageView imgCountryFlag = convertView.findViewById(R.id.img_country_flag);
txtCountryName.setText(list.get(position).getName());
txtCountryContinent.setText(list.get(position).getDescribe());
txtype.setText(list.get(position).getType());
imgCountryFlag.setImageResource(list.get(position).getFlag());
return convertView;
}
}
products.java
package com.example.esi.shopapp;
public class products {
private String name;
private String describe;
private String type;
private int flag;
public products(String name, String describe, String type, int flag) {
this.name = name;
this.describe = describe;
this.type = type;
this.flag = flag;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescribe() {
return describe;
}
public void setDescribe(String describe) {
this.describe = describe;
}
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
Your logic is wrong. You are creating a new instance of the adapter in each item click. You should move
myadapter adapter = new myadapter(MainActivity.this, list);
lstCountries.setAdapter(adapter);
to the onCreate method. Make adapter a global variable and
change your current code to this.
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (radioGroup.getCheckedRadioButtonId()) {
case R.id.Tshirt:
radio = "Tshirt";
break;
case R.id.Shoes:
radio = "Shoes";
break;
default:
radio = "Pants";
break;
}
if (!txtname.getText().toString().isEmpty() && !txtdes.getText().toString().isEmpty()) {
products product = new products(txtname.getText().toString(), radio, txtdes.getText().toString(), R.drawable.shop)
if (!list.contains(product)) {
list.add(product);
adapter.notifyDataSetChanged();
}
}
}
});

How to change android:entries array list in the spinner dynamically in Android

I am working on a android project where I have 2 Custom spinner
State
City
i am using below code to to populate the spinner with Custom list view.
xml code:
<com.infantstudio.CatholicMithrulu.Spinner.SearchableSpinnerState
android:id="#+id/spinner2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:entries="#array/state"
app:hintTextState="Select"/>
SearchableListDialogState.class
package com.infantstudio.CatholicMithrulu.Spinner;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import com.infantstudio.CatholicMithrulu.R;
import java.io.Serializable;
import java.util.List;
public class SearchableListDialogState extends DialogFragment implements
SearchView.OnQueryTextListener, SearchView.OnCloseListener {
private static final String ITEMS = "items";
private ArrayAdapter listAdapter;
private ListView _listViewItems;
private SearchableListDialogState.SearchableItem _searchableItem;
private OnSearchTextChanged _onSearchTextChanged;
private SearchView _searchView;
private String _strTitle;
private String _strPositiveButtonText;
private DialogInterface.OnClickListener _onClickListener;
public SearchableListDialogState() {
}
public static SearchableListDialogState newInstance(List items) {
SearchableListDialogState multiSelectExpandableFragment = new
SearchableListDialogState();
Bundle args = new Bundle();
args.putSerializable(ITEMS, (Serializable) items);
multiSelectExpandableFragment.setArguments(args);
return multiSelectExpandableFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams
.SOFT_INPUT_STATE_HIDDEN);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Getting the layout inflater to inflate the view in an alert dialog.
LayoutInflater inflater = LayoutInflater.from(getActivity());
// Crash on orientation change #7
// Change Start
// Description: As the instance was re initializing to null on rotating the device,
// getting the instance from the saved instance
if (null != savedInstanceState) {
_searchableItem = (SearchableItem) savedInstanceState.getSerializable("item");
}
// Change End
View rootView = inflater.inflate(R.layout.searchable_list_dialog, null);
setData(rootView);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setView(rootView);
String strPositiveButton = _strPositiveButtonText == null ? "CLOSE" : _strPositiveButtonText;
alertDialog.setPositiveButton(strPositiveButton, _onClickListener);
String strTitle = _strTitle == null ? "Select Item" : _strTitle;
alertDialog.setTitle(strTitle);
final AlertDialog dialog = alertDialog.create();
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams
.SOFT_INPUT_STATE_HIDDEN);
return dialog;
}
// Crash on orientation change #7
// Change Start
// Description: Saving the instance of searchable item instance.
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putSerializable("item", _searchableItem);
super.onSaveInstanceState(outState);
}
// Change End
public void setTitle(String strTitle) {
_strTitle = strTitle;
}
public void setPositiveButton(String strPositiveButtonText) {
_strPositiveButtonText = strPositiveButtonText;
}
public void setPositiveButton(String strPositiveButtonText, DialogInterface.OnClickListener onClickListener) {
_strPositiveButtonText = strPositiveButtonText;
_onClickListener = onClickListener;
}
public void setOnSearchableItemClickListener(SearchableItem searchableItem) {
this._searchableItem = searchableItem;
}
public void setOnSearchTextChangedListener(OnSearchTextChanged onSearchTextChanged) {
this._onSearchTextChanged = onSearchTextChanged;
}
private void setData(View rootView) {
SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context
.SEARCH_SERVICE);
_searchView = (SearchView) rootView.findViewById(R.id.search);
_searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName
()));
_searchView.setIconifiedByDefault(false);
_searchView.setOnQueryTextListener(this);
_searchView.setOnCloseListener(this);
_searchView.clearFocus();
InputMethodManager mgr = (InputMethodManager) getActivity().getSystemService(Context
.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(_searchView.getWindowToken(), 0);
List items = (List) getArguments().getSerializable(ITEMS);
_listViewItems = (ListView) rootView.findViewById(R.id.listItems);
//create the adapter by passing your ArrayList data
listAdapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1,items);
//attach the adapter to the list
_listViewItems.setAdapter(listAdapter);
_listViewItems.setTextFilterEnabled(true);
_listViewItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
_searchableItem.onSearchableItemClicked(listAdapter.getItem(position), position);
getDialog().dismiss();
}
});
}
#Override
public boolean onClose() {
return false;
}
#Override
public boolean onQueryTextSubmit(String s) {
_searchView.clearFocus();
return true;
}
#Override
public boolean onQueryTextChange(String s) {
// listAdapter.filterData(s);
if (TextUtils.isEmpty(s)) {
// _listViewItems.clearTextFilter();
((ArrayAdapter) _listViewItems.getAdapter()).getFilter().filter(null);
} else {
((ArrayAdapter) _listViewItems.getAdapter()).getFilter().filter(s);
}
if (null != _onSearchTextChanged) {
_onSearchTextChanged.onSearchTextChanged(s);
}
return true;
}
public interface SearchableItem<T> extends Serializable {
void onSearchableItemClicked(T item, int position);
}
public interface OnSearchTextChanged {
void onSearchTextChanged(String strText);
}
}
SearchableSpinnerState.class
package com.infantstudio.CatholicMithrulu.Spinner;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Toast;
import com.infantstudio.CatholicMithrulu.Adddata;
import com.infantstudio.CatholicMithrulu.R;
import java.util.ArrayList;
import java.util.List;
public class SearchableSpinnerState extends Spinner implements View.OnTouchListener,
SearchableListDialogState.SearchableItem {
String selectedItem;
//this string above will store the value of selected item.
public static final int NO_ITEM_SELECTED = -1;
private Context _context;
private List _items;
private SearchableListDialogState _searchableListDialog;
private boolean _isDirty;
private ArrayAdapter _arrayAdapter;
private String _strHintText;
private boolean _isFromInit;
public SearchableSpinnerState(Context context) {
super(context);
this._context = context;
init();
}
public SearchableSpinnerState(Context context, AttributeSet attrs) {
super(context, attrs);
this._context = context;
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SearchableSpinnerState);
final int N = a.getIndexCount();
for (int i = 0; i < N; ++i) {
int attr = a.getIndex(i);
if (attr == R.styleable.SearchableSpinnerState_hintTextState) {
_strHintText = a.getString(attr);
}
}
a.recycle();
init();
}
public SearchableSpinnerState(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this._context = context;
init();
}
private void init() {
_items = new ArrayList();
System.out.println("items"+_items);
_searchableListDialog = SearchableListDialogState.newInstance
(_items);
_searchableListDialog.setOnSearchableItemClickListener(this);
setOnTouchListener(this);
_arrayAdapter = (ArrayAdapter) getAdapter();
if (!TextUtils.isEmpty(_strHintText)) {
ArrayAdapter arrayAdapter = new ArrayAdapter(_context, android.R.layout
.simple_list_item_1, new String[]{_strHintText});
_isFromInit = true;
setAdapter(arrayAdapter);
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (null != _arrayAdapter) {
// Refresh content #6
// Change Start
// Description: The items were only set initially, not reloading the data in the
// spinner every time it is loaded with items in the adapter.
_items.clear();
for (int i = 0; i < _arrayAdapter.getCount(); i++) {
_items.add(_arrayAdapter.getItem(i));
}
// Change end.
_searchableListDialog.show(scanForActivity(_context).getFragmentManager(), "TAG");
}
}
return true;
}
#Override
public void setAdapter(SpinnerAdapter adapter) {
if (!_isFromInit) {
_arrayAdapter = (ArrayAdapter) adapter;
if (!TextUtils.isEmpty(_strHintText) && !_isDirty) {
ArrayAdapter arrayAdapter = new ArrayAdapter(_context, android.R.layout
.simple_list_item_1, new String[]{_strHintText});
super.setAdapter(arrayAdapter);
} else {
super.setAdapter(adapter);
}
} else {
_isFromInit = false;
super.setAdapter(adapter);
}
}
//The method just below is executed when an item in the searchlist is tapped.This is where we store the value int string called selectedItem.
#Override
public void onSearchableItemClicked(Object item, int position) {
setSelection(_items.indexOf(item));
if (!_isDirty) {
_isDirty = true;
setAdapter(_arrayAdapter);
setSelection(_items.indexOf(item));
}
selectedItem= item.toString().trim();
Adddata.setValueSt(selectedItem);
// Toast.makeText(getContext(),"You selected "+selectedItem, Toast.LENGTH_LONG).show();
}
private Activity scanForActivity(Context cont) {
if (cont == null)
return null;
else if (cont instanceof Activity)
return (Activity) cont;
else if (cont instanceof ContextWrapper)
return scanForActivity(((ContextWrapper) cont).getBaseContext());
return null;
}
#Override
public int getSelectedItemPosition() {
if (!TextUtils.isEmpty(_strHintText) && !_isDirty) {
return NO_ITEM_SELECTED;
} else {
return super.getSelectedItemPosition();
}
}
#Override
public Object getSelectedItem() {
if (!TextUtils.isEmpty(_strHintText) && !_isDirty) {
return null;
} else {
return super.getSelectedItem();
}
}
}
The above code is working fine, but I need to change the array at run time . Array is declared in the xml file like this
android:entries="#array/state"
How can I modify this array at run time? Any help would be valuable.
--Thanks!
Create ArrayList and insert the entries that you are getting from API or add it.
List < String > list = new ArrayList < > ();
list.add("Male");
list.add("Female");
list.add("Others");
ArrayAdapter < String > dataAdapter = new ArrayAdapter < String > (this, android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerGender.setAdapter(dataAdapter);
or
List<String> list= new ArrayList<>();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerGender.setAdapter(dataAdapter);
onResposeSucessofAPI(List<String> list){
this.list = list;
dataAdapter.notifyDataSetChanged();
}
Create a arrayList of Strings
ArrayList<String> area = new ArrayList<>();
add values in area arrayList
area.add("value1");
area.add("value2");
Now set adapter
yourSpinner.setAdapter(new ArrayAdapter<String>(context
, android.R.layout.simple_list_item_1, area));
Anything declared in Resources, cannot be changed at Runtime
You must do it by java code

RecyclerView does not update or refresh when calling notifyDataSetChanged()

I have an app that uses RecyclerView. When user selects "Add New Row" from the options menu, I output a test message to the screen, and some values get appended to two different ArrayLists. That part is working great, as I have confirmed these values are successfully added by looking at the ArrayList values using the debugger.
Anyhow I am not able to get the RecyclerView to redraw the screen and show the new information. My attempt to redraw / update the screen is by using this code (line 78 of MainActivity.java):
//call notify data set changed method for the adapter
adapter.notifyDataSetChanged();
Maybe I am not calling notifyDataSetChanged on the same adapter that actually is used for RecycleView??
Here is the complete code for MainActivity.java (see options menu code at end):
package com.joshbgold.ironmax;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final int ADD_ROW = 1; //used for case statement statement to select menu item
private RecyclerView recyclerView;
public Exercises exercises = new Exercises();
public ExerciseRow adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
assert getSupportActionBar() != null;
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setIcon(R.mipmap.barbell);
actionBar.setTitle(" " + "Iron Max");
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
//ExerciseRow adapter = new ExerciseRow(this);
adapter = new ExerciseRow(this);
recyclerView.setAdapter(adapter);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
/* MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.add_row, menu);
return super.onCreateOptionsMenu(menu);*/
menu.add(0, ADD_ROW, 0, "Add New Row");
menu.getItem(0).setIcon(R.drawable.plus);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.getItem(0).setIcon(R.drawable.plus);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int length;
switch (item.getItemId()) {
case 1:
Toast msg = Toast.makeText(MainActivity.this, "Test code for adding an exercise", Toast.LENGTH_LONG);
msg.show();
exercises.addExercise("Some exercise");
exercises.addPersonalBest(500);
length = exercises.getExercisesArrayLength();
//call notify data set changed method for the adapter
adapter.notifyItemInserted(length - 1);
adapter.notifyDataSetChanged();
return super.onOptionsItemSelected(item);
default:
return super.onOptionsItemSelected(item);
}
}
}
Here is Exercises.java:
import android.support.v7.app.AppCompatActivity;
import java.util.ArrayList;
public class Exercises extends AppCompatActivity {
public ArrayList<String> exercisesArrayList = new ArrayList<>(); //stores all the lifts
private ArrayList<Integer> personalBestsArrayList = new ArrayList<>(); //stores personal bests in pounds
public ArrayList<String> getExercisesArray() { //returns the whole exercises arraylist
return exercisesArrayList;
}
public ArrayList<Integer> getPersonalBests() { //returns the whole personal bests arraylist
return personalBestsArrayList;
}
public String getExercise(int position) { //returns individual exercise from array
return exercisesArrayList.get(position);
}
public void addExercise(String exercise) {
exercisesArrayList.add(exercise);
}
public void removeExercise(int position) {
exercisesArrayList.remove(position);
}
public void editExercise(int position, String exercise) {
exercisesArrayList.set(position, exercise);
}
public int getExercisesArrayLength() {
return exercisesArrayList.size();
}
public Integer getPersonalBest(int position) { //returns individual personal best from array
return personalBestsArrayList.get(position);
}
public void addPersonalBest(int personalBest) {
personalBestsArrayList.add(personalBest);
}
public void removePersonalBest(int position) {
personalBestsArrayList.remove(position);
}
public void editPersonalBest(int position, int personalBest) {
personalBestsArrayList.set(position, personalBest);
}
public Exercises() {} //constructor
}
Here is ExerciseRow.java:
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class ExerciseRow extends RecyclerView.Adapter<ExerciseRow.ExerciseViewHolder> {
String exerciseName = "burpee";
String exercisePR = "100"; // user's personal record for this exercise in pounds
private Context context;
Exercises exercises = new Exercises();
public ExerciseRow(Context context) {
this.context = context;
}
#Override
public ExerciseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.exercise_list_item, parent, false);
return new ExerciseViewHolder(view);
}
#Override
public void onBindViewHolder(ExerciseViewHolder holder, int position) {
ArrayList<String> exercisesArray = exercises.getExercisesArray();
holder.bindExercises(exercisesArray.get(position));
}
#Override
public int getItemCount() {
return exercises.getExercisesArrayLength();
}
public class ExerciseViewHolder extends RecyclerView.ViewHolder {
public TextView exerciseNameTextView;
public TextView personalRecordTextView;
public ImageView edit_Icon;
public ImageView percentages_Icon;
public ImageView trash_Icon;
public ImageView plus_icon;
public ImageView facebook_icon;
public ImageView twitter_icon;
public ExerciseViewHolder(View itemView) {
super(itemView);
exerciseNameTextView = (TextView) itemView.findViewById(R.id.list_item_exercise_textview);
personalRecordTextView = (TextView) itemView.findViewById(R.id.list_item_amount_textview);
edit_Icon = (ImageView) itemView.findViewById(R.id.list_item_pencil);
percentages_Icon = (ImageView) itemView.findViewById(R.id.list_item_percent);
trash_Icon = (ImageView) itemView.findViewById(R.id.list_item_trash);
plus_icon = (ImageView) itemView.findViewById(R.id.list_item_plus);
facebook_icon = (ImageView) itemView.findViewById(R.id.list_item_facebook);
twitter_icon = (ImageView) itemView.findViewById(R.id.list_item_twitter);
View.OnClickListener plus = new View.OnClickListener() {
#Override
public void onClick(View view) {
// allow user to add a new exercise and personal best
exercises.addExercise("Some exercise");
exercises.addPersonalBest(500);
notifyDataSetChanged();
}
};
View.OnClickListener edit = new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getLayoutPosition(); //use getAdapterPosition() if getLayoutPosition causes a problem
if (position == 0) { //prevent user from deleting the first row.
Toast.makeText(context, "Sorry, example row cannot be edited.", Toast.LENGTH_LONG).show();
}
else{
editRow(position); //edit the row at the current position
notifyDataSetChanged();
}
}
};
View.OnClickListener percentages = new View.OnClickListener() {
#Override
public void onClick(View view) {
//get exercise name
exerciseName = exerciseNameTextView.getText().toString();
exercisePR = personalRecordTextView.getText().toString();
//show percentages layout
startPercentagesActivity(exerciseName, exercisePR);
}
};
View.OnClickListener trash = new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getLayoutPosition(); //use getAdapterPosition() if getLayoutPosition causes a problem
if (position == 0) { //prevent user from deleting the first row.
Toast.makeText(context, "Sorry, example row cannot be deleted.", Toast.LENGTH_LONG).show();
} else {
exercises.removeExercise(position);
exercises.removePersonalBest(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, exercises.getExercisesArrayLength());
}
}
};
plus_icon.setOnClickListener(plus);
edit_Icon.setOnClickListener(edit);
percentages_Icon.setOnClickListener(percentages);
trash_Icon.setOnClickListener(trash);
}
public void bindExercises(String exercises) {
Exercises exercisesObject = new Exercises();
exerciseNameTextView.setText(exercisesObject.getExercise(getAdapterPosition()));
personalRecordTextView.setText((exercisesObject.getPersonalBest(getAdapterPosition())).toString() + " pounds");
}
}
private void startPercentagesActivity(String some_exercise, String personal_record) {
Intent intent = new Intent(context, PercentagesActivity.class);
intent.putExtra("exerciseName", some_exercise);
intent.putExtra("personalRecord", personal_record);
context.startActivity(intent);
}
protected void editRow(final int position) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
//text_entry is an Layout XML file containing two text field to display in alert dialog
final View textEntryView = layoutInflater.inflate(R.layout.text_entry, null);
final EditText liftName = (EditText) textEntryView.findViewById(R.id.liftNameEditText);
final EditText PersonalBestInPounds = (EditText) textEntryView.findViewById(R.id.personalBestEditText);
final AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setIcon(R.mipmap.barbell)
.setTitle("Please make your changes:")
.setView(textEntryView)
.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//retrieve the user's input
String lift = liftName.getText().toString();
int personalBest = Integer.parseInt(PersonalBestInPounds.getText().toString());
//save the user's input to the appropriate arrays
exercises.editExercise(position, lift);
exercises.editPersonalBest(position, personalBest);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
});
alert.show();
}
}
If you have read this far, I give you credit! Please understand I am completely new to RecyclerView, so whatever error(s) I have made could be something quite simple even.
The issue is that you have two different instances of ExercisesOne in MainActivity and another in ExerciseRow You are adding the data to the wrong one.
A few other things that may help you along your way.
Exercises Should not extend AppCompatActivity (or really anything as far as I can tell)
You should avoid saving a reference to the context (as you are doing in Exercises) it can great memory issues. Instead try one of the following.
A. Use the context to get the LayoutInflater in the constructor
B. Call parent.getContext() in onCreateViewHolder

android xml: Error inflating class fragment

I am having problem with fragments.I am developing an app like 360 security and i am having problem implementing fragments ,getting "Binary XML file line #1: Error inflating class fragment".
Here is my xml file.I have tried every solution please help me.
Thanks in advance.
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/item_list"
android:name="sabby.completesecurity.MainListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ItemListActivity"
tools:layout="#android:layout/list_content" />
This is my activity file:
package sabby.completesecurity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.ImageView;
import sabby.completesecurity.R;
public class MainActivityCache extends FragmentActivity implements sabby.completesecurity.MainCallbacks {
private boolean mIsDualPane;
private boolean mIsArtShowed = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_cache);
mIsDualPane = findViewById(R.id.item_detail_container) != null;
//Show an art when no fragment is showed, we make sure no detail fragment is present.
if (mIsDualPane && getFragmentManager().findFragmentByTag(sabby.completesecurity.DetailFragment.FRAGMENT_TAG) == null) {
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.mipmap.ic_launcher);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
((FrameLayout) findViewById(R.id.item_detail_container)).addView(imageView);
mIsArtShowed = true;
}
}
#Override
public void onItemSelected(String packageName) {
if (mIsDualPane) {
//Hide art when a fragment is showed.
if (mIsArtShowed) {
((FrameLayout) findViewById(R.id.item_detail_container)).removeAllViews();
mIsArtShowed = false;
}
getFragmentManager()
.beginTransaction()
.replace(R.id.item_detail_container, DetailFragment.getInstance(packageName), DetailFragment.FRAGMENT_TAG)
.commit();
} else {
Intent intent = new Intent(this, DetailActivity.class);
intent.putExtra(DetailFragment.EXTRA_PACKAGE_NAME, packageName);
startActivity(intent);
}
}
#Override
protected void onStart() {
super.onStart();
registerReceiver(receiver, getIntentFilter());
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(receiver);
}
private void showAboutDialog() {
new AlertDialog.Builder(this)
.setTitle("About")
.setView(getLayoutInflater().inflate(R.layout.about_dialog_message, null))
.setNegativeButton(android.R.string.ok, null)
.show();
}
/**
* Used to update the list if a package is added or removed.
*/
private IntentFilter getIntentFilter() {
IntentFilter filter = new IntentFilter();
filter.addDataScheme("package");
filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
filter.addAction(Intent.ACTION_PACKAGE_FULLY_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
return filter;
}
enter code here
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
MainListFragment mainListFragment = (MainListFragment) getFragmentManager().findFragmentById(R.id.item_list);
if (mainListFragment != null)
mainListFragment.loadList();
}
};
}
MainListFragment.java
package sabby.completesecurity;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageStats;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.RemoteException;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.SectionIndexer;
import android.widget.Spinner;
import android.widget.TextView;
import sabby.completesecurity.utils.Utils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
public class MainListFragment extends ListFragment implements AdapterView.OnItemClickListener, AdapterView.OnItemSelectedListener {
private static final int SORT_NAME = 0;
private static final int SORT_PKG = 1;
private static final int SORT_DOMAIN = 2;
private static final int SORT_INSTALLATION = 3;
private static final int SORT_SIZE = 4;
private static final String INSTANCE_STATE_SORT_BY = "sort_by";
private Adapter mAdapter;
private List<Item> mItemList = new ArrayList<Item>();
private int mOnSizeFinishedItemCount;
private PackageManager mPackageManager;
private ProgressDialog mProgressDialog;
private LayoutInflater mLayoutInflater;
private MainCallbacks mCallbacks;
private Context mContext;
private Async mAsyncLoader;
private Spinner mSpinner;
private boolean mSpinnerListenerAuthorized;
private SimpleDateFormat mSimpleDateFormat;
private int mSortBy = 0;
class Item {
ApplicationInfo applicationInfo;
String label;
Long date;
Long size = -1L;
}
private int mColorGrey1;
private int mColorGrey2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mProgressDialog = new ProgressDialog(mContext);
mProgressDialog.setTitle(R.string.loading_apps);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
//Used to prevent message not showing later
mProgressDialog.setMessage("");
mPackageManager = mContext.getPackageManager();
mSimpleDateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
mColorGrey1 = getResources().getColor(R.color.grey_1);
mColorGrey2 = getResources().getColor(R.color.grey_2);
ActionBar actionBar = getActivity().getActionBar();
actionBar.setDisplayShowCustomEnabled(true);
mSpinner = new Spinner(actionBar.getThemedContext());
SpinnerAdapter spinnerAdapter = new SpinnerAdapter(actionBar.getThemedContext(),
R.array.sort_spinner_items, android.R.layout.simple_list_item_1);
mSpinner.setAdapter(spinnerAdapter);
mSpinnerListenerAuthorized = false;
mSpinner.setOnItemSelectedListener(this);
ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
actionBar.setCustomView(mSpinner, layoutParams);
if (savedInstanceState != null)
setSortBy(savedInstanceState.getInt(INSTANCE_STATE_SORT_BY, -1), false);
}
#Override
public void onStart() {
super.onStart();
mSpinner.setSelection(mSortBy);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(INSTANCE_STATE_SORT_BY, mSortBy);
}
private void onTaskEnded(List<Item> list) {
RetainedFragment retainedFragment = (RetainedFragment) getFragmentManager().findFragmentByTag(RetainedFragment.FRAGMENT_TAG);
retainedFragment.setList(list);
mItemList = list;
mAdapter.notifyDataSetChanged();
if (getListView().getAdapter() == null)
setListAdapter(mAdapter);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getListView().setOnItemClickListener(this);
getListView().setFastScrollEnabled(true);
mAdapter = new Adapter();
RetainedFragment retainedFragment = (RetainedFragment) getFragmentManager()
.findFragmentByTag(RetainedFragment.FRAGMENT_TAG);
if (retainedFragment == null) {
retainedFragment = new RetainedFragment();
getFragmentManager()
.beginTransaction()
.add(retainedFragment, RetainedFragment.FRAGMENT_TAG)
.commit();
}
if (retainedFragment.getList() != null) {
onTaskEnded(retainedFragment.getList());
mOnSizeFinishedItemCount = mItemList.size();
//Notify spinner that size sort is available
SpinnerAdapter adapter = (SpinnerAdapter) mSpinner.getAdapter();
adapter.notifyDataSetChanged();
} else
loadList();
}
public void loadList() {
mAsyncLoader = new Async();
mAsyncLoader.execute();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallbacks = (MainCallbacks) activity;
mContext = activity;
mLayoutInflater = activity.getLayoutInflater();
}
#Override
public void onDetach() {
super.onDetach();
if (mAsyncLoader != null)
mAsyncLoader.cancel(true);
mCallbacks = null;
mContext = null;
mLayoutInflater = null;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (mCallbacks != null)
mCallbacks.onItemSelected(mItemList.get(i).applicationInfo.packageName);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragment_main_list, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
loadList();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (mSpinnerListenerAuthorized)
setSortBy(i, true);
mSpinnerListenerAuthorized = true;
}
/**
* Sort main list if provided value is valid.
* #param sort Must be one of SORT_*
* #param checkViews Set if views have to be updated, eg. when restoring state, views aren't
* created yet, so value must be false
*/
public void setSortBy(int sort, boolean checkViews) {
if (sort >= SORT_NAME && sort <= SORT_SIZE) {
mSortBy = sort;
if (checkViews) {
checkFastScroll();
sortApplicationList(mItemList, mSortBy);
mAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
private void checkFastScroll() {
getListView().setFastScrollEnabled(mSortBy == SORT_NAME);
}
public void sortApplicationList(List<Item> list, final int sortBy) {
Collections.sort(list, new Comparator<Item>() {
#Override
public int compare(Item item1, Item item2) {
switch (sortBy) {
case SORT_NAME:
return item1.label.compareTo(item2.label);
case SORT_PKG:
return item1.applicationInfo.packageName.compareTo(item2.applicationInfo.packageName);
case SORT_DOMAIN:
boolean isSystem1 = (item1.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
boolean isSystem2 = (item2.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
return Utils.compareBooleans(isSystem1, isSystem2);
case SORT_INSTALLATION:
//Sort in decreasing order
return -item1.date.compareTo(item2.date);
case SORT_SIZE:
return -item1.size.compareTo(item2.size);
default:
return 0;
}
}
});
}
/**
* This method is called by each item when it has finished retrieving its size
* When all items have finished, we set size sort available in spinner, and invalidate
* main list to display sizes in UI.
*/
private void onItemFinishedSizeProcess() {
mOnSizeFinishedItemCount ++;
if (mOnSizeFinishedItemCount == mItemList.size()) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
SpinnerAdapter adapter = (SpinnerAdapter) mSpinner.getAdapter();
adapter.notifyDataSetChanged();
mAdapter.notifyDataSetChanged();
}
});
}
}
class Adapter extends BaseAdapter implements SectionIndexer {
class ViewHolder {
ImageView icon;
TextView label;
TextView packageName;
TextView version;
TextView isSystemApp;
TextView date;
TextView size;
IconAsyncTask iconLoader;
}
String sections = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
#Override
public int getCount() {
return mItemList.size();
}
#Override
public Object getItem(int i) {
return mItemList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder holder;
if (view == null) {
view = mLayoutInflater.inflate(R.layout.main_list_item, null);
holder = new ViewHolder();
holder.icon = (ImageView) view.findViewById(R.id.icon);
holder.label = (TextView) view.findViewById(R.id.label);
holder.packageName = (TextView) view.findViewById(R.id.packageName);
holder.version = (TextView) view.findViewById(R.id.version);
holder.isSystemApp = (TextView) view.findViewById(R.id.isSystem);
holder.date = (TextView) view.findViewById(R.id.date);
holder.size = (TextView) view.findViewById(R.id.size);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
holder.iconLoader.cancel(true);
}
view.setBackgroundColor(i % 2 == 0 ? mColorGrey2 : mColorGrey1);
Item item = mItemList.get(i);
ApplicationInfo info = item.applicationInfo;
try {
PackageInfo packageInfo = mPackageManager.getPackageInfo(info.packageName, 0);
holder.version.setText(packageInfo.versionName);
Date date = new Date(packageInfo.firstInstallTime);
holder.date.setText(mSimpleDateFormat.format(date));
} catch (PackageManager.NameNotFoundException e) {
//Do nothing
}
holder.iconLoader = new IconAsyncTask(holder.icon, info);
holder.iconLoader.execute();
holder.label.setText(info.loadLabel(mPackageManager));
holder.packageName.setText(info.packageName);
boolean isSystemApp = (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
holder.isSystemApp.setText(isSystemApp ? getString(R.string.system) : getString(R.string.user));
if (item.size != -1L)
holder.size.setText(Formatter.formatFileSize(getActivity(), item.size));
return view;
}
#Override
public int getPositionForSection(int section) {
for (int i = 0; i < this.getCount(); i++) {
String item = mItemList.get(i).label;
if (item.charAt(0) == sections.charAt(section))
return i;
}
return 0;
}
#Override
public int getSectionForPosition(int i) {
return 0;
}
#Override
public Object[] getSections() {
String[] sectionsArr = new String[sections.length()];
for (int i = 0; i < sections.length(); i++)
sectionsArr[i] = "" + sections.charAt(i);
return sectionsArr;
}
class IconAsyncTask extends AsyncTask<Void, Integer, Drawable> {
ImageView imageView;
ApplicationInfo info;
IconAsyncTask(ImageView imageView, ApplicationInfo info) {
this.imageView = imageView;
this.info = info;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
imageView.setVisibility(View.INVISIBLE);
}
#Override
protected Drawable doInBackground(Void... voids) {
if (!isCancelled())
return info.loadIcon(mPackageManager);
return null;
}
#Override
protected void onPostExecute(Drawable drawable) {
super.onPostExecute(drawable);
imageView.setImageDrawable(drawable);
imageView.setVisibility(View.VISIBLE);
}
}
}
class SpinnerAdapter extends BaseAdapter {
private Context mContext;
private int mLayoutResId;
private String[] mItems;
public SpinnerAdapter(Context themedContext, int arrayResId, int layoutResId) {
mContext = themedContext;
mItems = themedContext.getResources().getStringArray(arrayResId);
mLayoutResId = layoutResId;
}
#Override
public int getCount() {
return mItems.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
//It make no sense to implement recycled view system because there is only 5 items in list
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = View.inflate(mContext, mLayoutResId, null);
if (view instanceof TextView)
((TextView) view).setText(mItems[i]);
return view;
}
/**
* Set sort_by_size item disabled if all items haven't retrieved them size.
*/
#Override
public boolean isEnabled(int position) {
return position != SORT_SIZE || mItemList != null && mOnSizeFinishedItemCount == mItemList.size();
}
}
class Async extends AsyncTask<Void, Async.Progress, List<Item>> {
class Progress {
String label;
int totalSize;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected List<Item> doInBackground(Void... voids) {
List<ApplicationInfo> applicationInfos = mPackageManager.getInstalledApplications(PackageManager.GET_META_DATA);
Progress progress = new Progress();
progress.totalSize = applicationInfos.size();
List<Item> itemList = new ArrayList<Item>(applicationInfos.size());
mOnSizeFinishedItemCount = 0;
for (ApplicationInfo applicationInfo : applicationInfos) {
if (isCancelled())
break;
Item item = new Item();
item.applicationInfo = applicationInfo;
String label = applicationInfo.loadLabel(mPackageManager).toString();
item.label = label;
try {
item.date = mPackageManager.getPackageInfo(applicationInfo.packageName, 0).firstInstallTime;
} catch (PackageManager.NameNotFoundException e) {
item.date = 0L;
}
itemList.add(item);
getItemSize(item);
progress.label = label;
publishProgress(progress);
}
sortApplicationList(itemList, mSortBy);
return itemList;
}
private void getItemSize(final Item item) {
try {
Method getPackageSizeInfo = mPackageManager.getClass().getMethod(
"getPackageSizeInfo", String.class, IPackageStatsObserver.class);
getPackageSizeInfo.invoke(mPackageManager, item.applicationInfo.packageName, new IPackageStatsObserver.Stub() {
#Override
public void onGetStatsCompleted(final PackageStats pStats, boolean succeeded)
throws RemoteException {
if (succeeded)
item.size = pStats.codeSize + pStats.cacheSize + pStats.dataSize
+ pStats.externalCodeSize + pStats.externalCacheSize + pStats.externalDataSize
+ pStats.externalMediaSize + pStats.externalObbSize;
else
item.size = -1L;
onItemFinishedSizeProcess();
}
});
} catch (NoSuchMethodException e) {
e.printStackTrace();
onItemFinishedSizeProcess();
} catch (IllegalAccessException e) {
e.printStackTrace();
onItemFinishedSizeProcess();
} catch (InvocationTargetException e) {
e.printStackTrace();
onItemFinishedSizeProcess();
}
}
#Override
protected void onProgressUpdate(Progress... values) {
super.onProgressUpdate(values);
Progress progress = values[0];
mProgressDialog.setMessage(progress.label);
if (mProgressDialog.getMax() == 100)
mProgressDialog.setMax(progress.totalSize);
mProgressDialog.incrementProgressBy(1);
}
#Override
protected void onPostExecute(List<Item> list) {
super.onPostExecute(list);
mProgressDialog.hide();
onTaskEnded(list);
}
#Override
protected void onCancelled(List<Item> list) {
super.onCancelled(list);
mProgressDialog.hide();
}
}
}
In the xml that you have posted,replace the TAG <Fragment> with <LinearLayout> or <RelativeLayout> and inside this you simply show what you want to display in you UI
Make sure you extend Fragment class in you fragment activity
Could you post the code for your fragment? The problem could be with your import statements. You have 'import android.support.v4.app.FragmentActivity'. Do you have 'import android.support.v4.app.Fragment' in your fragment file?

android issues updating Listview due to filtering, with a custom base adapter

I'm facing issue by implementing a search mechanism on a ListView in Android.
I currently display a list of companies in a ListView
The ListView is linked to a custom BaseAdapter that ref a data model
The data model handle the data gathering thru HTTP requests.
I succeed partly filtering : the identified companies are identified in the listview, but the rest of the companies (the ones that not match the searching constraint are still there), even if I removed them
Here is the code :
package org.x.activites;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.x.R;
import org.x.activites.utils.Analytics;
import org.x.adapters.listview.AbstractDynamicModel;
import org.x.adapters.listview.AbstractExtendedDynamicViewAdapter;
import org.x.adapters.listview.ViewHolder;
import org.x.application.Application;
import org.x.http.HTTPRequest;
import org.x.list.adapters.PartnerViewHolder;
import org.x.model.Partner;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ListView;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.widget.SearchView;
public class GeoPartnerActivity extends SherlockActivity {
private ListView listView;
PartnersModel partnersModel;
PartnerListAdapter partnerAdpt;
private SearchManager searchManager;
private SearchView searchView;
public GeoPartnerActivity() {
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_partner);
listView = (ListView) findViewById(R.id.partnerList);
partnersModel = new PartnersModel();
partnerAdpt = new PartnerListAdapter(partnersModel);
listView.setAdapter(partnerAdpt);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.activity_partners, menu);
searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
if (null != searchView) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
}
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
public boolean onQueryTextChange(String newText) {
return false;
}
public boolean onQueryTextSubmit(String query) {
if (TextUtils.isEmpty(query)) {
listView.clearTextFilter();
}
else {
listView.setFilterText(query);
}
partnerAdpt.getFilter().filter(query);
return true;
}
};
searchView.setOnQueryTextListener(queryTextListener);
searchView.setQueryHint("Salut StackExchange");
return super.onCreateOptionsMenu(menu);
}
public class PartnersModel extends AbstractDynamicModel<Partner> {
public PartnersModel() {
}
private HTTPRequest createRequest() {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("currentIndex", getElements().size() + ""));
nameValuePairs.add(new BasicNameValuePair("partnersNumber", "5"));
return new HTTPRequest("http://xxxxxxxxxxxxxxxx/partners", nameValuePairs);
}
#Override
protected BackgroundTask createBackgroundTask() {
BackgroundTask backgroundTask = new BackgroundTask(GeoPartnerActivity.this, createRequest()) {
List<Partner> lastLoaded = new ArrayList<Partner>();
#Override
protected List<Partner> getLoadedElements() {
return lastLoaded;
}
#Override
protected void handleSuccess(Object object) {
lastLoaded.clear();
try {
JSONArray array = (JSONArray) object;
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = (JSONObject) array.get(i);
Partner partner = new Partner(jsonObject);
lastLoaded.add(partner);
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
};
return backgroundTask;
}
#Override
public List<Partner> getElements() {
return super.getElements();
}
#Override
protected Context getContext() {
return GeoPartnerActivity.this;
}
}
private class PartnerListAdapter extends AbstractExtendedDynamicViewAdapter<Partner> implements Filterable {
private PartnersModel partnerList, partnerFullList;
private PartnerFilter partnerFilter;
public PartnerListAdapter(PartnersModel model) {
super(GeoPartnerActivity.this, model);
partnerList = model;
partnerFullList = new PartnersModel();
}
#Override
public Filter getFilter() {
if (partnerFilter == null) {
partnerFilter = new PartnerFilter();
}
return partnerFilter;
}
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
#Override
protected int getResourceID() {
return PartnerViewHolder.ResourceId;
}
#Override
protected ViewHolder createViewHolder(View convertView) {
return new PartnerViewHolder(convertView);
}
public class PartnerFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
List<Partner> partnerFilteredList = new ArrayList<Partner>();
for (Iterator<Partner> iterator = partnerList.iterator(); iterator.hasNext();) {
Partner partner = iterator.next();
partnerFullList.getElements().add(partner);
if (false == partner.getName().toUpperCase().contains(constraint.toString().toUpperCase())) {
partnerFilteredList.add(partner);
}
}
results.values = partnerFilteredList;
results.count = partnerFilteredList.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.count == 0)
partnerAdpt.notifyDataSetInvalidated();
else {
for (Iterator<Partner> iterator = ((List<Partner>) results.values).iterator(); iterator.hasNext();) {
Partner p = (Partner) iterator.next();
if (partnerAdpt.partnerList.getElements().remove(p));
p.setName("del-> " + p.getName());
}
//listView.setAdapter(null);
//listView.setAdapter(new PartnerListAdapter(partnerList));
((PartnerListAdapter) listView.getAdapter()).notifyDataSetChanged();
listView.refreshDrawableState();
listView.invalidateViews();
}
}
}
}
}
Here is the menu layout
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/menu_search"
android:actionViewClass="com.actionbarsherlock.widget.SearchView"
android:icon="#drawable/toolbar_find"
android:showAsAction="always"
android:title="Search">
</item>
</menu>
And here is screenshot before filtering :
And after :
I have tagged the name of the items with a "del->", so all of them are identified, but not removed from the list !!!
Edit :
Here is the top adapter AbstractDynamicViewAdapter:
public abstract class AbstractDynamicViewAdapter extends BaseAdapter {
protected final Context _context;
protected final ArrayList<AdapterItem> _list;
private final LayoutInflater _inflater;
private final int _progressResourceId;
private final int _unavailableResourceId;
private final int _emptyResourceId;
protected boolean _isInitialization = false;
protected boolean _isRequestSubmited = false;
public AbstractDynamicViewAdapter(Context context, int progressResourceId, int unavailableResourceId,
int emptyResourceId) {
_context = context;
_inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
_list = new ArrayList<AdapterItem>();
_progressResourceId = progressResourceId;
_unavailableResourceId = unavailableResourceId;
_emptyResourceId = emptyResourceId;
}
protected abstract View onDataView(int position, AdapterItem item, View convertView, ViewGroup parent);
protected abstract void onDataLoad();
protected abstract boolean isMoreToLoad();
protected abstract void onSubmitDataRequest();
#Override
public int getCount() {
return _list.size();
}
#Override
public Object getItem(int position) {
Object result = null;
if (position < _list.size()) {
result = _list.get(position);
}
return result;
}
#Override
/* Override this method when implementing stable id */
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (_list.size() > position) {
AdapterItem item = _list.get(position);
if (item.viewType == ViewType.Data) {
convertView = onDataView(position, item, convertView, parent);
}
else {
int resourceid = getResourceByViewType(item.viewType);
convertView = tryInflateView(convertView, resourceid, parent);
tryCreateViewHolder(convertView, item, resourceid);
if (!_isRequestSubmited && item.viewType == ViewType.Progress) {
submitDataRequest();
}
}
}
return convertView;
}
protected int getResourceByViewType(ViewType expectedType) {
int result = 0;
switch (expectedType) {
case Progress:
result = _progressResourceId;
break;
case Unavailable:
result = _unavailableResourceId;
break;
case Empty:
result = _emptyResourceId;
break;
default:
break;
}
return result;
}
protected void tryCreateViewHolder(View viewSource, AdapterItem item, int resourceId) {
ViewHolder viewItem = (ViewHolder) viewSource.getTag();
if (viewItem == null) {
viewItem = new ViewHolder(viewSource, resourceId);
}
}
protected View tryInflateView(View viewSource, int resourceId, ViewGroup parent) {
View result = null;
if (viewSource != null && viewSource.getTag() != null) {
ViewHolder viewItem = (ViewHolder) viewSource.getTag();
// try to re-use view if it has the same type
if (viewItem != null && viewItem.resourceId == resourceId) {
result = viewSource;
}
}
if (result == null) {
// create new view
result = _inflater.inflate(resourceId, parent, false);
}
return result;
}
protected void addItem(Object value, Object tag) {
AdapterItem item = new AdapterItem(value, tag);
_list.add(item);
}
protected void removeItem(Object item) {
_list.remove(item);
}
protected void addUnavailableItem() {
AdapterItem item = new AdapterItem(ViewType.Unavailable);
_list.add(item);
}
protected void submitDataRequest() {
showProgress();
onSubmitDataRequest();
_isRequestSubmited = true;
}
protected void setDataCompleted() {
_list.clear();
onDataLoad();
if (isMoreToLoad()) {
showProgress();
}
notifyDataSetChanged();
_isRequestSubmited = false;
}
private void removeAnyBut(ViewType type) {
if (type != ViewType.Progress) {
tryEndProgress();
}
if (type != ViewType.Empty) {
tryEndEmpty();
}
if (type != ViewType.Unavailable) {
tryEndUnavailable();
}
}
private void tryShowItem(ViewType type) {
removeAnyBut(type);
if (_list.size() == 0 || _list.get(_list.size() - 1).viewType != type) {
_list.add(new AdapterItem(type));
}
notifyDataSetChanged();
}
protected void showUnavailable() {
tryShowItem(ViewType.Unavailable);
}
protected void showProgress() {
tryShowItem(ViewType.Progress);
}
protected void showEmpty() {
tryShowItem(ViewType.Empty);
}
private void tryRemoveItem(ViewType type) {
if (_list.size() > 0 && _list.get(_list.size() - 1).viewType == type) {
_list.remove(_list.size() - 1);
}
}
protected void tryEndProgress() {
tryRemoveItem(ViewType.Progress);
}
protected void tryEndUnavailable() {
tryRemoveItem(ViewType.Unavailable);
}
protected void tryEndEmpty() {
tryRemoveItem(ViewType.Empty);
}
}
And the middle adapter AbstractExtendedDynamicViewAdapter :
public abstract class AbstractExtendedDynamicViewAdapter<T> extends AbstractDynamicViewAdapter {
private final AbstractDynamicModel<T> _model;
private boolean offlineModedataLoaded = false;
private Handler handler = new Handler() {
#Override
public void dispatchMessage(Message msg) {
setDataCompleted();
}
};
public AbstractExtendedDynamicViewAdapter(Context context, AbstractDynamicModel<T> model) {
super(context, R.layout.progress_item, R.layout.unavailable_item, R.layout.empty_item);
_model = model;
_model.setLoadCompleted(handler);
submitDataRequest();
}
#Override
public View onDataView(int position, AdapterItem item, View convertView, ViewGroup parent) {
convertView = tryInflateView(convertView, getResourceID(), parent);
ViewHolder viewHolder = (ViewHolder) convertView.getTag();
if (viewHolder == null) {
viewHolder = createViewHolder(convertView);
}
viewHolder.render(item);
return convertView;
}
public boolean removeElement(Object obj) {
//return _list.remove(obj);
return _model.getElements().remove(obj);
}
protected abstract int getResourceID();
protected abstract ViewHolder createViewHolder(View convertView);
#Override
protected boolean isMoreToLoad() {
if (Utils.isConnected(_context)) {
offlineModedataLoaded = true;
return true;
}
else
if (false == offlineModedataLoaded) {
offlineModedataLoaded = true;
return true;
}
return false;
}
#Override
protected void onDataLoad() {
if (_model.getElements().isEmpty()) {
addUnavailableItem();
showUnavailable();
}
else {
for (int i = 0; i < _model.getElements().size(); i++) {
addItem(_model.getElements().get(i), null);
}
}
}
#Override
protected void onSubmitDataRequest() {
_model.loadMore();
}
}
if (partnerAdpt.partnerList.getElements().remove(p));
p.setName("del-> " + p.getName());
With this code you only update filtered result. You should remove this values from the list you put in adapter with this code:
super(GeoPartnerActivity.this, model);
Try to get "model" data from adapter (not from abstract) and remove "p".

Categories

Resources