I am trying to implement search option for my contact list that is being displayed with Contact images and contact name.
I have created a text box to input the search text.
contactnameadpater.java: extends base adapter.
which has the following code:
public class ContactNamesAdapter extends BaseAdapter implements Filterable
{
private Activity activity;
private ArrayList<HashMap<String, String>> originalData;
private ArrayList<HashMap<String, String>> filteredData;
private static LayoutInflater inflater=null;
public ContactNamesAdapter(Activity a, ArrayList<HashMap<String, String>> d)
{
activity = a;
originalData=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount()
{
return originalData.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.contacts_row, null);
ImageView profile = (ImageView)vi.findViewById(R.id.ContactImage);
Uri my_contact_Uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(originalData.get(position).get("id")));
InputStream photo_stream = ContactsContract.Contacts.openContactPhotoInputStream(ContactNamesAdapter.inflater.getContext().getContentResolver(),my_contact_Uri);
if(photo_stream != null)
{
BufferedInputStream buf =new BufferedInputStream(photo_stream);
Bitmap my_btmp = BitmapFactory.decodeStream(buf);
profile.setImageBitmap(my_btmp);
}
else
{
profile.setImageResource(R.drawable.no_pic);
}
TextView name = (TextView)vi.findViewById(R.id.name);
name.setText(originalData.get(position).get("name"));
return vi;
}
#Override
public Filter getFilter()
{
return new Filter()
{
private ArrayList<HashMap<String, String>> filteredResultsData;
#Override
protected FilterResults performFiltering(CharSequence charSequence)
{
FilterResults results = new FilterResults();
//If there's nothing to filter on, return the original data for your list
if(charSequence == null || charSequence.length() == 0)
{
results.values = originalData;
results.count = originalData.size();
}
else
{
ArrayList<HashMap<String,String>> filterResultsData = new ArrayList<HashMap<String,String>>();
for(HashMap<String,String> data : originalData)
{
if(originalData == filterResultsData )
{
filterResultsData.add(data);
}
}
results.values = filterResultsData;
results.count = filteredResultsData.size();
}
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults)
{
filteredData = (ArrayList<HashMap<String,String>>)filterResults.values;
notifyDataSetChanged();
}
};
}
contactname.java: extends an activity.
OnCreate:
DetailsList = new ArrayList<HashMap<String, String>>();
contactList = (ListView) findViewById(R.id.ContactNamelist);
profileImage = (ImageView) findViewById(R.id.ContactImage);
inputSearch = (EditText) findViewById(R.id.inputSearch);
getContactName();
contactList.setTextFilterEnabled(true);
inputSearch.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
adapter.getFilter().filter(cs.toString());
//adapter.getFilter().filter(cs);
Log.e("getfilter","getfilter");
contactList.setAdapter(adapter);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
}
});
}
and under getContactName():
public void getContactName()
{
final Uri uri = ContactsContract.Contacts.CONTENT_URI;
final String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.PHOTO_ID
};
String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '1'";
final String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
Cursor cur = getContentResolver().query(uri, projection, selection, null, sortOrder);
if (cur.getCount() > 0)
{
while (cur.moveToNext())
{
String Sid = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", name);
map.put("id", Sid);
DetailsList.add( map);
}
}
cur.close();
adapter = new ContactNamesAdapter(this, DetailsList);
// updating listview
contactList.setAdapter(adapter);
}
The problem is that I am not getting results after typing the text in search box. I am not sure where I am going wrong?
Let me know how to fix this?
Thanks!
You might want to look at this link.
Click Here to see Searchview
It is a good SearchView or use my SearchView below
Here is my search method on a listview
search.addTextChangedListener(new TextWatcher() { //search is a edittext object
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
textlength = search.getText().length(); //textlength is a global variable
filtered_text = new ArrayList<RowItem>(); //global array list
for (int i = 0; i < employee.length(); i++)
{
if(rowItems.get(i).getTitle().toString().toUpperCase().contains(search.getText().toString().toUpperCase())) //rowItem is an object of my holder class for Custom Adapter
{
//Adding image and names which match the search criteria
in filtered_text array list
String mDrawableName;
try {
mDrawableName = employee.getJSONObject(i).getString("image");
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
RowItem item = new RowItem(resID, rowItems.get(i).getTitle());
filtered_text.add(item);
} catch (JSONException e) {e.printStackTrace();}
}
}
adapter = new CustomBaseAdapter(YourClass.this, filtered_text);
listView.setAdapter(adapter);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
Related
I googled other solutions but coudn't find any whic is similar to my condition and at first i tried to get the contents of the text view and filter but was not successful please help. so here I have Created a listview which is inflated by three textviews which form like a table each textview is a column and data is added dynamically from the server. How Can filter contents based on the user search.
Here is the code Below.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private void showJSON2(String response){
String id="";
String name="";
String date_from="";
String date_to="";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(JSON_ARRAY2);
ListView listView = (ListView) findViewById(R.id.list_view);
list = new ArrayList<HashMap<String, String>>();
for (int i=0; i<result.length(); i++) {
JSONObject notice = result.getJSONObject(i);
id = notice.getString(KEY_ID);
name = notice.getString(KEY_NAME);
date_from = notice.getString(KEY_DATE_FROM);
date_to = notice.getString(KEY_DATE_TO);
HashMap<String, String> temp= new HashMap<String, String>();
temp.put(FIRST_COLUMN, id);
temp.put(SECOND_COLUMN, name);
temp.put(THIRD_COLUMN, date_from);
temp.put(FOURTH_COLUMN, date_to);
list.add(temp);
}
ListViewAdapters adapter = new ListViewAdapters(this, list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id)
{
int pos=position+1;
Toast.makeText(MainActivity.this, Integer.toString(pos)+" Clicked", Toast.LENGTH_SHORT).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
ListViewAdapters.java -
public class ListViewAdapters extends BaseAdapter{
public ListViewAdapters(Activity activity,ArrayList<HashMap<String, String>> list){
super();
this.activity=activity;
this.list=list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater=activity.getLayoutInflater();
if(convertView == null){
convertView=inflater.inflate(R.layout.colmn_row, null);
txtFirst=(TextView) convertView.findViewById(R.id.name);
txtSecond=(TextView) convertView.findViewById(R.id.gender);
txtThird=(TextView) convertView.findViewById(R.id.age);
txtFourth=(TextView) convertView.findViewById(R.id.status);
}
HashMap<String, String> map=list.get(position);
txtFirst.setText(map.get(FIRST_COLUMN));
txtSecond.setText(map.get(SECOND_COLUMN));
txtThird.setText(map.get(THIRD_COLUMN));
txtFourth.setText(map.get(FOURTH_COLUMN));
return convertView;
}
}
In MainActivity.java,
public class MainActivity extends AppCompatActivity {
ArrayList<HashMap<String, String>> list = new ArrayList<>();
ListViewAdapters adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_default);
adapter = new ListViewAdapters(this, list);
listView.setAdapter(adapter);
}
private void showJSON2(String response) {
...
list.clear();
...
list.add(temp);
...
// ListViewAdapters adapter = new ListViewAdapters(this, list);
// listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
...
}
}
In adapter class,
public class ListViewAdapters extends BaseAdapter {
ArrayList<HashMap<String, String>> origList = new ArrayList<>();
public ListViewAdapters(Activity activity,ArrayList<HashMap<String, String>> list) {
super();
this.activity=activity;
this.list=list;
this.origList=list;
}
...
void filter(String filterString) {
list = new ArrayList<>();
for (HashMap<String, String> item: origList) {
// use your own logic to filter
if (itemShouldBeAdded)
list.add(item); // add if item is inside filter
}
notifyDataSetChanged();
}
void cancelFilter() {
list = origList;
notifyDataSetChanged();
}
}
Now, to filter, call the function filter.
adapter.filter("some_string");
To cancel filter,
adapter.cancelFilter();
I am using this way to filter my list according to user's input.
private void setFilter(EditText et_search_bar, ArrayList<String> list, OnListUpdated onListUpdated) {
if (et_search_bar != null) {
TextWatcher textWatcher;
textWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// filter your list from your input
if (!previousValue.equalsIgnoreCase(s.toString())) {
if (!TextUtils.isEmpty(s.toString())) {
previousValue = s.toString();
ArrayList<String> temp = new ArrayList<>();
for (String bookmarkBean : list) {
//or use .contains(text)
if (bookmarkBean.toLowerCase().contains(s.toString())) {
temp.add(bookmarkBean);
}
}
//update recyclerview
if (onListUpdated != null) {
onListUpdated.onListFiltered(temp);
}
} else onListUpdated.onListFiltered(filterBean);
}
}
};
et_search_bar.addTextChangedListener(textWatcher);
}
}
and
public interface OnListUpdated {
void onListFiltered(ArrayList<String> list);}
setFilter(et_search_bar, filterBean, new OnListUpdated() {
#Override
public void onListFiltered(ArrayList<String> list) {
// notify your adapter
}
});
I am trying to implement something similar to facebook's search system, where if a user starts typing in a name it brings autocomplete suggestions based on the letters typed, and with an additional option to search for more results. Each result is an object and not a string, and I have tried adding an extra result for search but every time I click on search or one of the objects a replace text occurs with the object as oppose to the name and I know it is a method of the autocomplete widget. Is there another way to go about it?
Here is my code:
private AutoCompleteTextView sx;
sx = (AutoCompleteTextView) findViewById(R.id.sx);
if(sadapter == null) {
sadapter = new Sadapter(PostActivity.this, usersFound);
sx.setAdapter(sadapter);
}
sx.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (sx.getText().toString().length() <= 3 && sadapter != null) {
usersFound.clear();
sadapter.notifyDataSetChanged();
}
if (sx.getText().toString().length() > 3) {
usersFound.clear();
sadapter.notifyDataSetChanged();
Log.d(Constants.DEBUG, "Changing text " + s);
sxname = s.toString();
testCreate();
sadapter.notifyDataSetChanged();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
sx.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DatabaseUser newAdd = usersFound.get(position);
if(position == searchServerIndex) {
sx.setText(sxname);
usersFound.clear();
sadapter.notifyDataSetChanged();
apiGetPossibleCandidates();
} else {
sx.setText("");
}
}
});
private void testCreate() {
DatabaseUser nuser1 = new DatabaseUser("userid", "pictureid", "Jon");
DatabaseUser nuser2 = new DatabaseUser("userid", "pictureid", "Jonny");
DatabaseUser nuser3 = new DatabaseUser("userid", "pictureid", "Jong");
DatabaseUser nuser4 = new DatabaseUser("userid", "pictureid", "Joan");
DatabaseUser searchServer = new DatabaseUser("SearchId", "pictureid", "Search " + sxname);
usersFound.add(nuser1);
usersFound.add(nuser2);
usersFound.add(nuser3);
usersFound.add(nuser4);
searchServerIndex = usersFound.size();
usersFound.add(searchServer);
if(sadapter != null) {
sadapter.notifyDataSetChanged();
}
}
This is the adapter:
public class Sadapter extends ArrayAdapter<DatabaseUser> {
private Context mContext;
private List<DatabaseUser> usersSearch;
private List<DatabaseUser> usersFiltered;
public Sadapter(Context context, List<DatabaseUser> usersAdded) {
super(context, 0, usersAdded);
mContext = context;
usersSearch = usersAdded;
}
#Override
public int getCount() {
return usersSearch.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.user_autosearch_item, null);
}
//helps for recycling
final ViewHolder holder = new ViewHolder();
holder.userTxt = (TextView) v.findViewById(R.id.userTxt);
v.setTag(holder);
String name = usersSearch.get(position).getName();
holder.userTxt.setText(name);
return v;
}
static class ViewHolder {
TextView userTxt;
}
}
you can override getItem() method in your adapater and return the object of DataBaseUser of particular position from the searchlist.. like
#Override public DatabaseUser getItem(int position) {
return usersSearch.get(position);
}
So from your onClick method you can call this method and it will give you DatabaseUser object from which you can retrive your text. I hope it helps you ..
I am using this project and edited it in my way. I used a common layout for every page. There is a ListView in that layout. I am checking the position of the page and setting different view to it depending on that position.
There is an editText in my actionbar. I want to filter the listview of the current page according to the onTextChanged of the editText. Everything is working fine but the filtering is not happening.
Here is my full code:
public class MainActivity extends ActionBarActivity {
public static TextView actionbarTitle;
public static EditText listViewEditText;
public static ImageButton listViewSearch;
public static Context context;
public static ListView songslist;
public static final int MAX_PAGES = 1;
private int num_pages = 5;
public ArrayList<String> title;
public ArrayList<Long> albumId;
public ArrayList albumName;
public ArrayList songs;
public ArrayList artist;
public ArrayList songsPath;
public ArrayList songsDuration;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this;
populate();
ActionBar actionBar = getSupportActionBar();
LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.customactionbar, null);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setIcon(R.drawable.ic_launcher);
actionBar.setCustomView(v);
listViewSearch = (ImageButton) findViewById(R.id.listViewSearch);
listViewEditText = (EditText) findViewById(R.id.editText);
actionbarTitle = (TextView) findViewById(R.id.text_left);
listViewSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
actionbarTitle.setVisibility(View.GONE);
listViewEditText.setVisibility(View.VISIBLE);
}
});
final ViewPagerParallax pager = (ViewPagerParallax) findViewById(R.id.pager);
pager.set_max_pages(MAX_PAGES);
pager.setBackgroundAsset(R.drawable.picture);
pager.setAdapter(new my_adapter());
pager.getAdapter().notifyDataSetChanged();
if (savedInstanceState != null) {
num_pages = savedInstanceState.getInt("num_pages");
pager.setCurrentItem(savedInstanceState.getInt("current_page"), false);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("num_pages", num_pages);
final ViewPagerParallax pager = (ViewPagerParallax) findViewById(R.id.pager);
outState.putInt("current_page", pager.getCurrentItem());
}
private class my_adapter extends PagerAdapter {
#Override
public int getCount() {
return num_pages;
}
#Override
public boolean isViewFromObject(View view, Object o) {
return view == o;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
View new_view = null;
LayoutInflater inflater = getLayoutInflater();
new_view = inflater.inflate(R.layout.page, null);
songslist = (ListView) new_view.findViewById(R.id.listView);
if (position == 0) {
songslist.setAdapter(new CustomListViewSongs(context, title, artist, songsDuration));
} else if (position == 1) {
songslist.setAdapter(new CustomListViewSongs(context, songsDuration, artist, songsDuration));
} else if (position == 2) {
songslist.setAdapter(new CustomListViewSongs(context, songsPath, artist, songsDuration));
}
listViewEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
ArrayList<String> temp = new ArrayList<String>();
int length = listViewEditText.getText().length();
temp.clear();
for (int t = 0; t < title.size(); t++) {
if (length <= title.get(t).length()) {
if (listViewEditText.getText().toString().equalsIgnoreCase((String) title.get(t).substring(0, length))) {
temp.add(title.get(t));
}
}
}
songslist.setAdapter(new CustomListViewSongs(context, temp, artist, songsDuration));
}
#Override
public void afterTextChanged(Editable s) {
}
});
container.addView(new_view);
Log.e("TAG", "" + position);
return new_view;
}
}
private void populate() {
ArrayList<Long> albumId = new ArrayList<Long>();
ArrayList artist = new ArrayList();
ArrayList title = new ArrayList();
ArrayList album = new ArrayList();
ArrayList songs = new ArrayList();
ArrayList songsPath = new ArrayList();
ArrayList songsDuration = new ArrayList();
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
Cursor cursor;
String[] projection = {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.ALBUM_ID,
MediaStore.Audio.Media.TITLE
};
cursor = this.getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
null,
null);
while (cursor.moveToNext()) {
artist.add(cursor.getString(1));
songsPath.add(cursor.getString(3));
songs.add(cursor.getString(4));
songsDuration.add(cursor.getString(5));
album.add(cursor.getString(6));
albumId.add(cursor.getLong(7));
title.add(cursor.getString(2));
//songUri.add(cursor.getString(3));
}
cursor.close();
this.title = title;
this.albumId = albumId;
this.albumName = album;
this.songs = songs;
//this.songs = title;
this.artist = artist;
this.songsPath = songsPath;
this.songsDuration = songsDuration;
//Collections.sort(this.songs, String.CASE_INSENSITIVE_ORDER);
//Collections.sort(this.albumName, String.CASE_INSENSITIVE_ORDER);
}
}
It would be easier to use Autocomplete textView.
I need to get the selected contacts from the SelectContactsActivity and display those selected contacts in ContactListActivity. But i am not getting the contacts which i selected.
my SelectContactsActivity.java
public class SelectContactsActivity extends Activity{
private ListView select_listView;
private EditText search_edt;
private List<ContactBean> list = new ArrayList<ContactBean>();
private ContanctAdapter objAdapter;
//private boolean UpdateAB;
private String groupName;
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_selectcontacts);
select_listView = (ListView) findViewById(R.id.select_contacts_listView);
search_edt = (EditText) findViewById(R.id.inputSearch);
Intent intent = getIntent();
groupName = intent.getStringExtra("group_name");
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,null, null);
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
ContactBean objContact = new ContactBean();
objContact.setName(name);
objContact.setPhoneNo(phoneNumber);
list.add(objContact);
}
phones.close();
objAdapter = new ContanctAdapter(SelectContactsActivity.this, R.layout.select_contacts_list_item, list, updateAB);
select_listView.setAdapter(objAdapter);
objAdapter.setEditMode(true);
if (null != list && list.size() != 0) {
Collections.sort(list, new Comparator<ContactBean>() {
#Override
public int compare(ContactBean lhs, ContactBean rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
} else {
showToast("No Contact Found!!!");
}
select_listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listview, View v,
int position, long id) {
// TODO Auto-generated method stub
objAdapter.setChecked(position, v);
objAdapter.notifyDataSetChanged();
invalidateOptionsMenu();
}
});
/**
* Enabling Search Filter
* */
// Capture Text in EditText
search_edt.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = search_edt.getText().toString().toLowerCase(Locale.getDefault());
objAdapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
}
private void showToast(String msg) {
// TODO Auto-generated method stub
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
objAdapter.setEditMode(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.actions_select_contacts_list, menu);
MenuItem item = null;
if (select_listView.getCount() > 0) {
if(objAdapter.isCheckItem()){
menu.findItem(R.id.action_done).setEnabled(true).setVisible(true);
item = menu.add(Menu.NONE, R.id.action_done, Menu.NONE,R.string.done);
}else{
menu.findItem(R.id.action_done).setEnabled(false).setVisible(false);
}
}else{
menu.findItem(R.id.action_done).setEnabled(false).setVisible(false);
}
Log.v(this.getClass().getName(), "Check update..."+objAdapter.isCheckItem());
return true;
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_done:
StringBuilder _itemBuilder = new StringBuilder();
objAdapter.saveSelected(groupName);
invalidateOptionsMenu();
finish();
break;
}
return true;
}
Handler updateAB = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
invalidateOptionsMenu();
Log.v(SelectContactsActivity.this.getClass().getName(), "Check invalidate cal;l");
}
};
}
My ContanctAdapter.java
public class ContanctAdapter extends ArrayAdapter<ContactBean> {
public Context mcontext;
private List<ContactBean> items;
private ContactBean objBean;
private boolean isEdit;
private ArrayList<ContactBean> arraylist;
public boolean[] contactCheckArray;
private LayoutInflater inflater;
public ContanctAdapter(Activity act, int row, List<ContactBean> items, Handler handler) {
super(act, row, items);
this.mcontext = act;
inflater = LayoutInflater.from(act);
this.items = items;
this.arraylist = new ArrayList<ContactBean>();
this.arraylist.addAll(items);
contactCheckArray = new boolean[items.size()];
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final View view = null==convertView?inflater.inflate(R.layout.select_contacts_list_item, null):convertView;
ViewHolder holder = null;
if (null == view.getTag()) {
holder = new ViewHolder();
holder.tvname = (TextView) view.findViewById(R.id.tvname);
holder.tvPhoneNo = (TextView) view.findViewById(R.id.tvphone);
holder.iv = (ImageView)view.findViewById(R.id.contacts_imageview);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
objBean = items.get(position);
if (holder.tvname != null && null != objBean.getName() && objBean.getName().trim().length() > 0) {
holder.tvname.setText(Html.fromHtml(objBean.getName()));
}
if (holder.tvPhoneNo != null && null != objBean.getPhoneNo()
&& objBean.getPhoneNo().trim().length() > 0) {
holder.tvPhoneNo.setText(Html.fromHtml(objBean.getPhoneNo()));
}
if (isEdit) {
holder.iv.setVisibility(View.VISIBLE);
} else {
holder.iv.setVisibility(View.GONE);
}
return view;
}
public void setEditMode(boolean isEdit) {
this.isEdit = isEdit;
}
public boolean isCheckItem () {
for (boolean value : contactCheckArray) {
if (value)
return true;
}
return false;
}
public void setChecked(final int pos, final View row) {
if (!contactCheckArray[pos]) {
((ViewHolder) row.getTag()).iv.setImageResource(R.drawable.setting_check);
contactCheckArray[pos] = true;
notifyDataSetChanged();
} else {
contactCheckArray[pos] = false;
((ViewHolder) row.getTag()).iv.setImageResource(R.drawable.setting_check_box_bg);
notifyDataSetChanged();
}
}
public class ViewHolder {
public ImageView iv;
public TextView tvname, tvPhoneNo;
}
public void saveSelected(String groupName){
StringBuilder _itemBuilder = new StringBuilder();
ProfilesDatabaseHelper DbHelper = new ProfilesDatabaseHelper(mcontext);
for (int i = 0; i < arraylist.size(); i++) {
if (contactCheckArray[i]) {
_itemBuilder.append("'"+ arraylist.get(i).getPhoneNo() + "'" + ",");
//Toast.makeText(mcontext, "Selected Contacts : "+_itemBuilder.toString(), Toast.LENGTH_LONG).show();
DbHelper.executeSQL("INSERT INTO GroupsTable (GroupName, ContactName, PhoneNumber) VALUES ('"+groupName+"', '"+arraylist.get(i).getName()+"','"+ arraylist.get(i).getPhoneNo()+ "')");
}
}
if (_itemBuilder.length() > 0) {
_itemBuilder.deleteCharAt(_itemBuilder.length() - 1);
Log.v(getClass().getName(), "Check..selected contactss :"+ _itemBuilder.toString());
//Toast.makeText(getApplicationContext(), "Selected Contacts : "+_itemBuilder.toString(), Toast.LENGTH_LONG).show();
// This will clear the buffer
_itemBuilder.delete(0, _itemBuilder.length());
}
}
public void filter(String charText ) {
// TODO Auto-generated method stub
charText = charText.toLowerCase(Locale.getDefault());
items.clear();
if (charText.length() == 0) {
items.addAll(arraylist);
}else {
for (ContactBean ob : arraylist) {
if (ob.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
items.add(ob);
}
}
}
notifyDataSetChanged();
}
}
And if i click on the first item in SelectContactsList activity automatically my 9th and 17th and 25th, 33.... contacts also selected and its returning one contact which i didn't select to the Contactslist activity. And i am not getting any errors. Any one help me to solve this issue.
Your issue is with this line in the first snippet, in your listener.
objAdapter.setChecked(position, v);
POSITION is different from ID. A ListView only renders the number of items that it needs to show. The position is the position in the rendered list.
Change it to id.
See this post as well for a better explanation of this with in-depth examples: Create a ListView with selectable rows/change background color of ListView rows when clicked
I want to retrieve the data from particular website( "http://api.eventful.com/rest/events/search?app_key=42t54cX7RbrDFczc&location=singapore ),
however, I couldn't managed to retrieve it.
I think there is something wrong with my code but I not sure which part gone wrong.
Could anyone help me out?
This is my coding.
It contains of the spinner date filtering as well.
public class AndroidXMLParsingActivity extends ListActivity implements OnItemSelectedListener {
List<String> browseby = new ArrayList<String>();
Date d = new Date();
String[] dates = { "Today", "Tomorrow", "This Week",
};
ArrayList<String> browse = new ArrayList<String>();
ArrayList<String> mPostingData = new ArrayList<String>();
Spinner s1;
ListView listview;
CustomAdapter cus;
// All static variables
static final String URL = "http://api.eventful.com/rest/events/search?app_key=42t54cX7RbrDFczc&location=singapore";
// XML node keys
static final String KEY_EVENT = "event"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_START_TIME = "start_time";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_EVENT);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_START_TIME, parser.getValue(e, KEY_START_TIME));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item, new String[] { KEY_TITLE,KEY_START_TIME }, new int[] {
R.id.title,
R.id.startTime });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.title))
.getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SingleMenuItemActivity.class);
in.putExtra(KEY_TITLE, title);
startActivity(in);
}
});
listview = (ListView) findViewById(R.id.listView1);
s1 = (Spinner) findViewById(R.id.spinner1);
for (int i = 0; i < browseby.size(); i++) {
browse.add(browseby.get(i));
}
// aa = new
// ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,Category);
s1.setOnItemSelectedListener(this);
mPostingData = browse;
for (int i = 0; i < mPostingData.size(); i++) {
if (mPostingData.size() > 0)
Log.i("Datas", mPostingData.get(i));
}
cus = new CustomAdapter(this, 0);
setListAdapter(cus);
ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, dates);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(aa);
}
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
// listview.setFilterText(Category[position]);
String Text = s1.getSelectedItem().toString();
cus.getFilter().filter(Text);
cus.notifyDataSetChanged();
}
public void onNothingSelected(AdapterView<?> parent) {
// listview.setFilterText("");
}
public void onListItemClick(ListView parent, View v, int position, long id) {
Toast.makeText(this, "You have selected " + mPostingData.get(position),
Toast.LENGTH_SHORT).show();
}
class CustomAdapter extends ArrayAdapter<String> {
public void setData(ArrayList<String> mPpst) {
mPostingData = mPpst;// contains class items data.
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected void publishResults(CharSequence constraint,
FilterResults start_time) {
if (start_time != null && start_time.count >= 0) {
setData((ArrayList<String>) start_time.values);
} else {
setData(browse);// set original values
}
notifyDataSetInvalidated();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
if(constraint=="Today") {
constraint = constraint.toString();
CharSequence s = DateFormat.format("yyyy-MM-dd ", d.getTime());
ArrayList<String> foundItems = new ArrayList<String>();
if (browse != null) {
for (int i = 0; i < browse.size(); i++) {
if (browse.get(i).contains(s)){
System.out.println("My datas" + browse.get(i));
foundItems.add(browse.get(i));
} else {
}
}
}
result.count = foundItems.size();// search results found
// return count
result.values = foundItems;// return values
} else {
result.count = -1;// no search results found
}
return result;
}
};
}
LayoutInflater mInflater;
public CustomAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mPostingData.size();
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder vh;
if (convertView == null) {
vh = new ViewHolder();
convertView = mInflater.inflate(R.layout.row, null);
vh.t1 = (TextView) convertView.findViewById(R.id.textView1);
convertView.setTag(vh);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
vh = (ViewHolder) convertView.getTag();
}
if (mPostingData.size() > 0)
vh.t1.setText(mPostingData.get(position));
return convertView;
}
}
static class ViewHolder {
TextView t1;
}
}
have you added this permission in your manifest file
<uses-permission
android:name="android.permission.INTERNET"
></uses-permission>