not getting selected contacts to a listview - java

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

Related

capturing images from camera and setting into listview in android

What i am doing::
I am opening a camera onclick of item from actionbar menu
I am capturing the image and setting it in a listview
What is happening::
Say i have captured 10 images and set it in listview
next time i run my code, i am able to find the images i took last
time, and it dosen't start from groundup
What i am trying to do:
say i captured 10 images and set in listview
next time i start the app and start capturing the image it should add
freshly captured images to listview and not display the old images
i am not telling i have to delete these images but i the app i want
to show newly captured images everytime
MainActivity.java
public class MainActivity extends ListActivity {
private static final int CAMERA_CAPTURE = 20;
ArrayList<String> listOfImages;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayCapturedImagesFromCamera();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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.
int id = item.getItemId();
if (id == R.id.action_camera) {
startCameraCapture();
return true;
}
return super.onOptionsItemSelected(item);
}
private void startCameraCapture() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = CreateImageFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(photoFile != null)
{
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, CAMERA_CAPTURE);
}
}
}
private File CreateImageFile() throws IOException
{
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "Image_" + timeStamp + "_";
File storageDirectory = getExternalFilesDir("");
File image = File.createTempFile(imageFileName, ".jpg",storageDirectory);
return image;
}
#Override
public void onActivityResult(final int requestCode, int resultCode, Intent data) {
switch(requestCode)
{
case CAMERA_CAPTURE:
if(resultCode == RESULT_OK)
{
DisplayCapturedImagesFromCamera();
}
break;
}
}
private void DisplayCapturedImagesFromCamera() {
// TODO Auto-generated method stub
File myPath = getExternalFilesDir(null);
listOfImages = new ArrayList<String>();
try
{
for(File f: myPath.listFiles()) {
listOfImages.add(f.getAbsolutePath());
}
AdptAddjobsGallery adapter = new AdptAddjobsGallery(MainActivity.this,listOfImages);
setListAdapter(adapter);
}
catch(Exception ex)
{
Log.w("Error", ex.getMessage());
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
// custom dialog
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.cust_dialog);
dialog.setTitle("Image ");
Bitmap bitmap = BitmapFactory.decodeFile(listOfImages.get(position));
// set the custom dialog components - text, image and button
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageBitmap(bitmap);
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dialog.dismiss();
}
});
dialog.show();
}
}
AdptAddjobsGallery.java
public class AdptAddjobsGallery extends ArrayAdapter<String> {
private final Activity context;
private final ArrayList<String> listOfImages;
public AdptAddjobsGallery(Activity context, ArrayList<String> listOfImages) {
super(context, R.layout.adpt_addjobs_gallery, listOfImages);
// TODO Auto-generated constructor stub
this.context=context;
this.listOfImages = listOfImages;
}
public View getView(int position,View view,ViewGroup parent) {
ViewHolder holder;
if(view == null)
{
LayoutInflater inflater=context.getLayoutInflater();
view =inflater.inflate(R.layout.adpt_addjobs_gallery, null,true);
holder = new ViewHolder();
holder.imageView = (ImageView) view.findViewById(R.id.selfie);
holder.txtTitle = (TextView) view.findViewById(R.id.fileName);
view.setTag(holder);
}
else
{
holder = (ViewHolder) view.getTag();
}
Bitmap bitmap = BitmapFactory.decodeFile(listOfImages.get(position));
File f = new File(listOfImages.get(position));
holder.txtTitle.setText(f.getName());
holder.imageView.setImageBitmap(bitmap);
return view;
};
}
class ViewHolder {
TextView txtTitle;
ImageView imageView;
}
try this, using file.lastmodified() method.
private ArrayList<String> getRecentImages(long from, long to,
ArrayList<String> list) {
ArrayList<String> sortedList = new ArrayList<String>();
for (int i = 0; i < list.size(); i++) {
File file = new File(list.get(i));
long modified = file.lastModified();
if (modified > from && modified <= to) {
sortedList.add(list.get(i));
}
}
return sortedList;
}

How to use custom adapter while adding and editing listview items?

I want to implement a to-do list application. I have three activities: one main activity, one adding activity and one editing activity. In my main activity there is a add button and a listview that shows the to-do items. When I click add button, adding activity is executed. In this activity,there is an edittext for the task, a datepicker and a spinner for priority level. When ok button is clicked, all these entred values are sent to main activity's listview as a line. And, when click an item on this list, editing activity is executed and user can change the values. However, in my code, when user enters the values, I can reach them in my custom adapter class but I could't display them in listview. Listview remains empty. How can i fix my code?
main activity:
public class MainActivity extends Activity {
protected static final String edits = "mainTask";
private ToDoItemAdapter listAdapter;
//private ToDoItemAdapter myCustomAdapter;
//private ArrayList<String> listString;
public ArrayList<ToDoItem> listItems;
public static final int ADD_TASKS = 1;
public static final int EDIT_TASKS = 2;
Button button;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
setListener();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void initUI() {
getViewReferences();
initializeToDoList();
}
private void setListener() {
// TODO Auto-generated method stub
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent addTaskIntent = new Intent(MainActivity.this, AddActivity.class);
startActivityForResult(addTaskIntent, ADD_TASKS);
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
System.out.println(arg2);
ToDoItemAdapter myAdapter = new ToDoItemAdapter(MainActivity.this,R.layout.editing_task,listItems);
listView.setAdapter(myAdapter);
Intent editTaskIntent = new Intent(MainActivity.this, EditingTask.class);
//editTaskIntent.putExtra("mainTask", arg2);
startActivityForResult(editTaskIntent, EDIT_TASKS);
}
});
}
private void getViewReferences() {
// TODO Auto-generated method stub
button = (Button) findViewById(R.id.addButton);
listView = (ListView) findViewById(R.id.listView);
}
private void initializeToDoList() {
// TODO Auto-generated method stub
listItems = new ArrayList<ToDoItem>();
//listString = new ArrayList<String>();
listAdapter = new ToDoItemAdapter(MainActivity.this, R.layout.activity_main, listItems);
listView.setAdapter(listAdapter);
View noTaskView = findViewById(R.id.emptyToDoList);
listView.setEmptyView(noTaskView);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case ADD_TASKS:
updateToDoList(data);
break;
case EDIT_TASKS:
break;
default:
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void updateToDoList(Intent data) {
// TODO Auto-generated method stub
String task = AddActivity.tasks;
ArrayList<String> list = data.getStringArrayListExtra(task);
String addedTask = list.get(0);
String addedDeadline = list.get(1);
String addedPriority = list.get(2);
ToDoItem item = new ToDoItem(addedTask, addedDeadline ,"0", addedPriority);
listItems.add(item);
//listString.add(addedTask + " " + addedDeadline + " " + addedPriority);
Log.w("Items:",listItems.get(0).getTask());
//Log.w("String:",listString.get(0));
listAdapter.notifyDataSetChanged();
}
}
ToDoItemAdapter class:
public class ToDoItemAdapter extends ArrayAdapter<ToDoItem> {
Context context;
private int resource;
ArrayList<ToDoItem> todoItem;
public ToDoItemAdapter(Context context, int resource, ArrayList<ToDoItem> objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
this.todoItem = objects;
}
#Override
public ToDoItem getItem(int position) {
return this.todoItem.get(position);
}
#Override
public int getCount() {
return this.todoItem.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
if (convertView == null)
{
/*todoView = new LinearLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li;
li = (LayoutInflater)getContext().getSystemService(inflater);
li.inflate(resource, todoView, true);
*/
LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(resource, parent, false);
}
//LinearLayout todoView;
ToDoItem todo = getItem(position);
String taskString = todo.getTask();
Log.w("task:", taskString);
String dateString = todo.getDeadline();
String priorityString = todo.getPriority();
String itemRow = taskString + " " + dateString + " " + priorityString;
return row;
}
}
Adding class:
public class AddActivity extends Activity{
private String[] states;
private Spinner spinner;
int position1;
String priority;
EditText etDate;
Button change_date;
final int Date_Dialog_ID=0;
int cDay,cMonth,cYear; // this is the instances of the current date
Calendar cDate;
int sDay,sMonth,sYear; // this is the instances of the entered date
protected static final String tasks = "addingTask";
private static final String LOG_TAG = "addingTaskActivity";
MainActivity main;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
initUI();
showDatePicker();
showPriorityLevel();
}
private void showPriorityLevel() {
// TODO Auto-generated method stub
states = getResources().getStringArray(R.array.priority_level);
spinner = (Spinner) findViewById(R.id.priority_spinner);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, states);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
position1 = spinner.getSelectedItemPosition();
switch(position1)
{
case 0: priority = "0";
break;
case 1: priority = "1";
break;
case 2: priority = "2";
break;
case 3: priority = "3";
break;
case 4: priority = "4";
break;
case 5: priority = "5";
break;
case 6: priority = "6";
break;
case 7: priority = "7";
break;
case 8: priority = "8";
break;
case 9: priority = "9";
break;
default: break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
private void showDatePicker() {
// TODO Auto-generated method stub
etDate=(EditText)findViewById(R.id.EditText01);
change_date=(Button)findViewById(R.id.Button01);
change_date.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//triggers the DatePickerDialog
showDialog(Date_Dialog_ID);
}
});
//getting current date
cDate=Calendar.getInstance();
cDay=cDate.get(Calendar.DAY_OF_MONTH);
cMonth=cDate.get(Calendar.MONTH);
cYear=cDate.get(Calendar.YEAR);
//assigning the edittext with the current date in the beginning
sDay=cDay;
sMonth=cMonth;
sYear=cYear;
updateDateDisplay(sYear,sMonth,sDay);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case Date_Dialog_ID:
return new DatePickerDialog(this, onDateSet, cYear, cMonth,
cDay);
}
return null;
}
private void updateDateDisplay(int year,int month,int date) {
// TODO Auto-generated method stub
etDate.setText(date+"-"+(month+1)+"-"+year);
}
private OnDateSetListener onDateSet=new OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
sYear=year;
sMonth=monthOfYear;
sDay=dayOfMonth;
updateDateDisplay(sYear,sMonth,sDay);
}
};
private void initUI() {
// TODO Auto-generated method stub
setContentView(R.layout.adding_task);
final EditText editTextTask = (EditText) findViewById(R.id.edit_text_task);
Button OKbutton = (Button) findViewById(R.id.ok_Button);
final EditText editTextDate = (EditText) findViewById(R.id.EditText01);
OKbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
ArrayList<String> addedDatas = new ArrayList<String>();
String addingTask = editTextTask.getText().toString();
String deadline = editTextDate.getText().toString();
//String concatenate = priority + " " + addingTask + " " + deadline;
Intent myIntent = new Intent();
addedDatas.add(addingTask);
addedDatas.add(deadline);
addedDatas.add(priority);
myIntent.putExtra("addingTask", addedDatas);
setResult(Activity.RESULT_OK, myIntent);
finish();
}
});
}
}
ToDoItem class
public class ToDoItem {
String task;
String deadline;
String status;
String priority;
public ToDoItem(String task, String deadline, String status, String priority) {
super();
this.task = task;
this.deadline = deadline;
this.status = status;
this.priority = priority;
}
public String getTask() {
return task;
}
public String getDeadline() {
return deadline;
}
public String getStatus() {
return status;
}
public String getPriority() {
return priority;
}
#Override
public String toString() {
return priority + " " + task + " " + deadline + " " + status;
}
What you should do, is make sure that the Adding Activity can access the ToDoItem Array that is used to populate the ListView in the Main Activity. Then it can just add to or modify this list directly. Then you can call a notifyAdapters() in onStart() of MainActivity to check for updates whenever it becomes visible.

Search option for contact names that extends base adapter

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
}
});

How to use search function in my custom listview(fetching data from website and display in listview)

I have listview,its getting data from website and displaying in an Listview,I want to use search function,in my listview i am having title and content.I want to search using content alone thats enough.How to use search function for my listview.
It shows problem in this line List newListTwo=new List(); the error is Cannot instantiate the type List
Myactivity.java
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
lv1 =(ListView)findViewById(R.id.list);
lv =(ListView)findViewById(R.id.list);
btnGetSelected = (Button) findViewById(R.id.btnget);
btnGetSelected.setOnClickListener(this);
myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
public void onTextChanged(CharSequence s,
int start, int before, int count)
{
String selection = myFilter.getText().toString().toLowerCase();
List<Application> newListTwo=new List<Application>();
int textlength = selection.trim().length();
System.err.println("selection" + textlength);
newListTwo.clear();
for (int i = 0; i < items.size(); i++)
{
// -------------- seach according to the content starts with -------------------------
if(items.get(i).getContent().toLowerCase().startsWith(selection))
{
System.err.println("Selection: " + selection);
newListTwo.add(items.get(i));
}
}
//---------------- Again Call your List View ------------------
adapter=new ApplicationAdapter(MainActivity.this, newListTwo);
setListAdapter(adapter);
}
private void setListAdapter(ApplicationAdapter adapter) {
// TODO Auto-generated method stub
}
});
//praycount.setOnClickListener(this);
initView();
}
private void initView(){
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://www.ginfy.com/api/v1/posts.json";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
For my code how to use the search function,i have my applicaton.java and applicationadapter.java also
Applicationadapter.java
#SuppressLint("NewApi")
public class ApplicationAdapter extends ArrayAdapter<Application> implements
TextToSpeech.OnInitListener{
private List<Application> items;
private LayoutInflater inflator;
private MainActivity activity;
private ProgressDialog dialog;
public TextToSpeech tts;
public ImageButton btnaudioprayer;
public TextView text1;
ArrayAdapter<String> adapter;
public ApplicationAdapter(MainActivity context, List<Application> items){
super(context, R.layout.activity_row, items);
this.items = items;
inflator = LayoutInflater.from(getContext());
activity=context;
}
#Override
public int getCount(){
return items.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder = null;
tts = new TextToSpeech(activity, ApplicationAdapter.this);
//View v = convertView;
if ( convertView == null ){
convertView = inflator.inflate(R.layout.activity_row, null);
holder = new ViewHolder();
holder.text2 = (TextView) convertView.findViewById(R.id.text2);
holder.text1 = (TextView) convertView.findViewById(R.id.text1);
holder.count = (TextView) convertView.findViewById(R.id.count);
holder.pray = (Button) convertView.findViewById(R.id.pray);
holder.chk = (CheckBox) convertView.findViewById(R.id.checkbox);
holder.btnaudioprayer = (ImageButton) convertView.findViewById(R.id.btnaudioprayer);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
holder.chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton view,
boolean isChecked) {
int getPosition = (Integer) view.getTag();
items.get(getPosition).setSelected(view.isChecked());
}
});
holder.pray.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int getPosition= (Integer)v.getTag();
StringBuffer sb1 = new StringBuffer();
sb1.append("ID :");
sb1.append(Html.fromHtml(""+items.get(getPosition).getId()));
sb1.append("\n");
activity.praydata(items.get(getPosition).getId());
//activity.showAlertView(sb1.toString().trim());
//activity.praydata(Integer.parseInt(sb1.toString().trim()));
}
});
holder.btnaudioprayer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View V) {
View parent = (View)V.getParent();
ViewHolder vh = (ViewHolder)parent.getTag();
TextView tv = vh.text1;
speakOut(tv.getText().toString());
}
});
Application app = items.get(position);
holder.chk.setTag(position);
holder.pray.setTag(position);
holder.text2.setText(Html.fromHtml(app.getTitle()));
holder.text1.setText(Html.fromHtml(app.getContent()));
holder.count.setText(app.getCount()+"");
holder.chk.setChecked(app.isSelected());
return convertView;
}
static class ViewHolder {
public TextView text2;
public TextView text1;
public TextView count;
public CheckBox chk;
public Button pray;
public ImageButton btnaudioprayer;
private TextToSpeech tts;
}
//return convertView;
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speakOut(String text) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
Use addTextChangeListener to show list according to the content:-
searchContentEditText.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
public void onTextChanged(CharSequence s,
int start, int before, int count)
{
selection= searchContentEditText.getText().toString().toLowerCase();
List newListTwo=new ArrayList();
textlength = selection.trim().length();
System.err.println("selection" + textlength);
newListTwo.clear();
for (int i = 0; i < contactList.size(); i++)
{
// -------------- seach according to the content starts with -------------------------
if(firstList.get(i).getContent().toLowerCase().startsWith(selection))
{
System.err.println("Selection: " + selection);
newListTwo.add(firstList.get(i));
}
}
//---------------- Again Call your List View ------------------
adapter=new ContactListAdapter(MyActivity.this, newListTwo);
setListAdapter(adapter);
}
});
You need to implement your MyActivity.java class with TextWatcher.
public class MyActivity extends Activity implements TextWatcher {
myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(this);
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Group[] group_array = null;
this.array_sort = new ArrayList<Group>();
try {
if(user != null) {
group_array = this.user.getUser_groups().getData();
}
int textlength = this.search_bar.getText().length();
for(int i=0; i<group_array.length; i++) {
if(textlength <= group_array[i].getGroup_name().length()) {
if(((String) group_array[i].getGroup_name().subSequence(0, textlength))
.equalsIgnoreCase(this.search_bar.getText().toString()))
{
this.array_sort.add(group_array[i]);
}
}
}
if(this.array_sort.size() > 0) {
Group[] groups = new Group[this.array_sort.size()];
FetchGroups.this.group_adapter = new GroupAdapter(FetchGroups.this,R.layout.row_fetch_groups,
android.R.layout.simple_list_item_1, this.array_sort.toArray(groups));
FetchGroups.this.groups_list.setAdapter(group_adapter);
}
} catch(Exception e) {
e.printStackTrace();
}
}

Custom ListView is not updated when items are inserted

I have a custom listview with custom adapter extending BaseAdapter if i add items to this list view in OnCreate method they show up in list, but if i add them from other methods like a packet listener method then items do not show up , on the screen below this listview there is a textbox if i select textbox to entertext using virtual keyboard immediately the listview gets populated with previousely inserted items which didnt show up. This activity is a chat window basically
I have tried calling notifyDataSetChanged, invalidate on Layout or on listview but nothing helped.
What i think is i need to have a way to refresh activity , as same thing must be happening when the virtual keyboard pops up .
Help will be highly appreciated
Thanks
Code:
package com.arounds;
public class ChatActivity extends Activity implements OnClickListener,PacketListener{
private ListView chatView;
private ChatListViewCustomAdapter adapter;
private String user;
private XMPPConnection connection;
private Conversation conv;
private ChatActivity selfRef = this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_win);
AroundApplication app = (AroundApplication) this.getApplicationContext();
connection = app.getConnection();
chatView = (ListView) findViewById(R.id.conversationList);
adapter = new ChatListViewCustomAdapter(this);
chatView.setAdapter(adapter);
// set send btn listener
ImageButton send = (ImageButton)findViewById(R.id.imgBtnSend);
send.setOnClickListener(this);
ImageButton smiley = (ImageButton)findViewById(R.id.imgBtnSmiley);
smiley.setOnClickListener(this);
// get the parameter passed by previouse activity
Bundle b = this.getIntent().getExtras();
String temp = b.getString("user");
user = temp;
TextView v = (TextView)this.findViewById(R.id.txtViewTitle_chat);
v.setText(temp);
v = (TextView)this.findViewById(R.id.txtViewDescription_chat);
temp = b.getString("status");
v.setText(temp);
//chatView.setOnItemClickListener(this);
HashMap convs = app.getConversations();
if(convs.containsKey(user) == true)
conv = (Conversation) convs.get(user);
else {
conv = new Conversation();
convs.put(user,conv);
}
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
connection.addPacketListener(this,filter);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == R.id.imgBtnSend)
{
EditText msg = (EditText)this.findViewById(R.id.editChat);
String s = msg.getText().toString();
Message message = new Message(user, Message.Type.chat);
message.setBody(s);
connection.sendPacket(message);
ArrayList<ChatMessage> m = conv.messages;
String currentDate = DateFormat.getDateInstance().format(new Date());
m.add(new ChatMessage(s,currentDate));
adapter.addItem("I said",s,currentDate,Constants.SEND_LIST_TYPE);
//adapter.notifyDataSetChanged();
}
else
{
//View view = this.findViewById(R.id.linerLayoutChat);
chatView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
#Override
public void processPacket(Packet packet) {
// TODO Auto-generated method stub
System.out.println("in");
Message message = (Message) packet;
if (message.getBody() != null) {
System.out.println("in1");
String fromName = StringUtils.parseBareAddress(message.getFrom());
ArrayList<ChatMessage> m = conv.messages;
String currentDate = DateFormat.getDateInstance().format(new Date());
m.add(new ChatMessage(message.getBody(),currentDate));
adapter.addItem(fromName+" said",message.getBody(),currentDate,Constants.REC_LIST_TYPE);
//chatView.postInvalidate();
}
}
}
Adapter class:
public class ChatListViewCustomAdapter extends BaseAdapter
{
public ArrayList<ChatListItem> items;
public Activity context;
public LayoutInflater inflater;
public Boolean temp=false;
public ChatListViewCustomAdapter(Activity context) {
super();
this.context = context;
this.items = new ArrayList<ChatListItem>();
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
TextView txtViewTitle;
TextView txtViewDescription;
TextView txtViewDate;
}
public void addItem(String title,String desc,String d,int type)
{
ChatListItem item = new ChatListItem(title,desc,d,type);
items.add(item);
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ChatListItem item = items.get(position);
ViewHolder holder;
System.out.println("Title:"+item.title+" type:"+item.type);
if(convertView==null)
{
holder = new ViewHolder();
int type = this.getItemViewType(position);
if(type == 0)
{
convertView = inflater.inflate(R.layout.list_item_even, null);
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.txtViewTitleEven);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.txtViewDescriptionEven);
holder.txtViewDate = (TextView) convertView.findViewById(R.id.txtViewDateEven);
}
else
{
convertView = inflater.inflate(R.layout.list_item_odd, null);
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.txtViewTitleOdd);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.txtViewDescriptionOdd);
holder.txtViewDate = (TextView) convertView.findViewById(R.id.txtViewDateOdd);
}
convertView.setTag(holder);
}
else
holder=(ViewHolder)convertView.getTag();
holder.txtViewTitle.setText(item.title);
holder.txtViewDescription.setText(item.desc);
holder.txtViewDate.setText(item.date);
return convertView;
}
#Override
public int getItemViewType(int position) {
ChatListItem item = items.get(position);
return item.type;
}
#Override
public int getViewTypeCount() {
return 2;
}
}
Handle all the updates within your Adapter and ensure you invoke notifyDataSetChanged() after you update it (within your Adapter)?
In cases where notifyDataSetChanged() does not work, re-set the adapter on the ListView by calling ListView.setAdapter() with the same Adapter again. This should refresh the view.
the only thing I can see not right are these methods:
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
These methods should return proper values.
items.get(position) and position respectively.

Categories

Resources