how to display contact numbers in MultiAutoCompleteTextView insted of displaying names - android

I am selecting multiple contacts using MultiAutoCompleteTextView it is displaying contact names like ramu,raju like that instead of displaying contact name how can i display contact number like 9999999999,8888888888 in MultiAutoCompleteTextView
my activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical">
<MultiAutoCompleteTextView
android:id="#+id/contacts"
android:textSize="18sp"
android:layout_margin="8px"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
and MainActivity.java
package com.example.multiplecontactselect;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Contacts;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.Filterable;
import android.widget.MultiAutoCompleteTextView;
import android.widget.TextView;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Cursor peopleCursor = getContentResolver().query(Contacts.People.CONTENT_URI, PEOPLE_PROJECTION, null, null, Contacts.People.DEFAULT_SORT_ORDER);
ContactListAdapter contactadapter = new ContactListAdapter(this,peopleCursor);
MultiAutoCompleteTextView textView = (MultiAutoCompleteTextView) findViewById(R.id.contacts);
textView.setAdapter(contactadapter);
textView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
}
public static class ContactListAdapter extends CursorAdapter implements Filterable {
public ContactListAdapter(Context context, Cursor c) {
super(context, c);
mContent = context.getContentResolver();
// System.out.println(mContent);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final LayoutInflater inflater = LayoutInflater.from(context);
final TextView view = (TextView) inflater.inflate(
android.R.layout.simple_dropdown_item_1line, parent, false);
view.setText(cursor.getString(5));
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
((TextView) view).setText(cursor.getString(5));
}
#Override
public String convertToString(Cursor cursor) {
return cursor.getString(5);
}
#Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
if (getFilterQueryProvider() != null) {
return getFilterQueryProvider().runQuery(constraint);
}
StringBuilder buffer = null;
String[] args = null;
if (constraint != null) {
buffer = new StringBuilder();
buffer.append("UPPER(");
buffer.append(Contacts.ContactMethods.NAME);
buffer.append(") GLOB ?");
args = new String[] { constraint.toString().toUpperCase() + "*" };
}
//System.out.println(constraint);
Log.d("hai", (String) constraint);
return mContent.query(Contacts.People.CONTENT_URI, PEOPLE_PROJECTION,
buffer == null ? null : buffer.toString(), args,
Contacts.People.DEFAULT_SORT_ORDER);
}
private ContentResolver mContent;
}
private static final String[] PEOPLE_PROJECTION = new String[] {
Contacts.People._ID,
Contacts.People.PRIMARY_PHONE_ID,
Contacts.People.TYPE,
Contacts.People.NUMBER,
Contacts.People.LABEL,
Contacts.People.NAME,
};
}
change in manifast.xml
<uses-permission android:name="android.permission.READ_CONTACTS" />

Related

get onclick for button in listview, in fragment

I have a listview with several buttons in which the button.text property populated with several child names from a an sqlite database.
I need to retrieve tasks specificaly assigned to each child when the child's button is clicked (possibly using the text property of the button(which is populated with the child name) ).
I have 3 java files that i am working (ChildDatabase, ChildListAdapter, ChildList) with and 2 xml files(fragment_child_list_layout, fragment_child_list).
Where can I set an onClick event for the buttons in my list view. And how can i differentiate from each button if only ONE BUTTON is delcared?
This is my ChildDatabase file
package com.example.victor.kidsrewards;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Victor on 4/3/2016.
*/
public class ChildDataBase {
private SQLiteDatabase db;
private ChildSQLiteHelper childSQLiteHelper;
String _parentName = Globals._username;
public ChildDataBase(Context context) {
childSQLiteHelper = new ChildSQLiteHelper(context);
db = childSQLiteHelper.getWritableDatabase();
}
public void Close() {
db.close();
}
public void createChild(String childNameText, String nickNameText, String genderText, int ageText) {
String query = "select * from child";
Cursor cursor = db.rawQuery(query, null);
int count = cursor.getCount();
ContentValues contentValues = new ContentValues();
contentValues.put("id", count);
contentValues.put("childname", childNameText);
contentValues.put("nickname", nickNameText);
contentValues.put("age", ageText);
contentValues.put("gender", genderText);
contentValues.put("parent", _parentName);
//insert
db.insert("child", null, contentValues);
}
public List<ChildUser> getChildren() {
List<ChildUser> childList = new ArrayList<ChildUser>();
//select columns
String[] tableColumns = new String[]{"id", "childname", "nickname"};
Cursor cursor = db.query("child", tableColumns, "parent =? ", new String[]{_parentName}, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
ChildUser child = new ChildUser();
//take values from database
child.setId(cursor.getInt(0));
child.setChildName(cursor.getString(1));
child.setNickName(cursor.getString(2));
//add to db
childList.add(child);
cursor.moveToNext();
}
return childList;
}
public String[] getChildNames() {
String[] tableColumns = new String[]{"childname"};
Cursor cursor = db.query("child", tableColumns, "parent =?", new String[]{_parentName}, null, null, null);
String[] array = new String[cursor.getCount()];//sets the length of the array
int i = 0;
while (cursor.moveToNext()) {
String uname = cursor.getString(cursor.getColumnIndex("childname"));
array[i] = uname;
i++;
}
return array;
}
}
This is my ChildListAdapter
Displays same button over again with different text property
package com.example.victor.kidsrewards;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
/**
* Created by Victor on 4/3/2016.
*/
public class ChildListAdapter extends ArrayAdapter<ChildUser> {
private final Context context;
private final List<ChildUser> childList;
public ChildListAdapter(Context context, List<ChildUser> childList){
super(context, R.layout.fragment_child_list_layout, childList);//fragment_child_list
this.context = context;
this.childList= childList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.fragment_child_list_layout,parent,false);
Button childName = (Button)rowView.findViewById(R.id.childButton);
childName.setText(childList.get(position).getNickName());
return rowView;
}
ChildList class
package com.example.victor.kidsrewards;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class ChildList extends ListFragment {
private ChildDataBase cdb;
public ChildList() {
// Required empty public constructor
}
/* #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_child_list, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
cdb = new ChildDataBase(getContext());
setListAdapter(new ChildListAdapter(getContext(), cdb.getChildren()));
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
}
}
fragment_child_list_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/childButton"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginTop="15dp" />
</RelativeLayout>
fragment_child_list.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.victor.kidsrewards.ChildList">
<!-- TODO: Update blank fragment layout -->
<ListView
android:id="#id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:text="TODO TEXT GOES_HERE">
</ListView>
</FrameLayout>
You can set the OnClickListener for the Button inside the getView() method of the adapter. The position argument can be used to identify which button was clicked.
See the code,
#Override
public View getView(final int position, View convertView, ViewGroup parent){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.fragment_child_list_layout,parent,false);
Button childName = (Button)rowView.findViewById(R.id.childButton);
childName.setText(childList.get(position).getNickName());
childName.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String selectedChild = childList.get(position).getNickName();
// do something with selected item
}
});
return rowView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.fragment_child_list_layout,parent,false);
Button childName = (Button)rowView.findViewById(R.id.childButton);
childName.setText(childList.get(position).getNickName());
childName.setOncLickListener(new OnclickListener() {
public void onClick() {
// do something for click each row
}
return rowView;
}

Contact list with checkBox, to select for the group mesage [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to make the contact list with checkboxs. So I have to select the contacts to send a group message ; I tried this code but it doesn't work...
What can you suggest to me what to do further to get the contact list.
MainActivity.java
package com.example.cont1;
import java.util.ArrayList;
import com.example.cont.MainActivity;
import com.example.listo1.Demo;
import com.example.listo1.R;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
StringBuilder sb= new StringBuilder();
String str;
ListView tx;
private Contact selectedAdapter;
private ArrayList<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
class ast extends AsyncTask<String, Void, String> {
String name, phone;
ProgressDialog pd;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = ProgressDialog.show(MainActivity.this, "", "loading");
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.cancel();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, str);
setListAdapter(adapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//textDetail.setText(sb);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
String phone = null;
if (cur.getCount() > 0) {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext()) {
name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
sb.append("\n " + name + "\n" + phone);
sb.append("\n............................\n");
str=sb.toString();
}
phones.close();
}
return null;
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Toast.makeText(this, String.valueOf(getListView().getCheckedItemCount()), Toast.LENGTH_LONG).show();
return true;
}
}
Contact.java
package com.example.cont1;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Contact extends ArrayAdapter {
private MainActivity list;
// used to keep selected position in ListView
private int selectedPos = -1; // init value for not-selected
private Context context;
private String[] values;
public Contact(Context context, String[] values) {
super(context, R.layout.activity_main, values);
this.context = context;
this.values = values;
}
public void setSelectedPosition(int pos){
selectedPos = pos;
// inform the view of this change
notifyDataSetChanged();
}
public int getSelectedPosition(){
return selectedPos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
LayoutInflater vi = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.activity_main, null);
// get text view
TextView label = (TextView)v.findViewById(R.id.textView1);
ImageView btn=(ImageView)v.findViewById(R.id.icon);
if (convertView == null) {
v = vi.inflate(R.layout.activity_main, parent, false);
}
else
v = convertView;
TextView text1 = (TextView) v.findViewById(R.id.textView1);
text1.setText(values[position]);
LinearLayout layout_item = (LinearLayout) v.findViewById(R.id.linear);
//Set the background and text color
if (position % 2 == 0) {
layout_item.setBackgroundColor(context.getResources().getColor(R.color.black));
text1.setTextColor(context.getResources().getColor(R.color.white));
} else {
layout_item.setBackgroundColor(context.getResources().getColor(R.color.white));
text1.setTextColor(context.getResources().getColor(R.color.black));
}
return v;
}
}
Activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/linear"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_margin="10dp"/>
<ImageView
android:id="#+id/icon"
android:layout_width="22px"
android:layout_height="22px"
android:layout_marginLeft="4px"
android:layout_marginRight="10px"
android:layout_marginTop="4px">
</ImageView>
</LinearLayout>
</ScrollView>
</LinearLayout>
rowLayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ListView
android:id="#+id/list"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
</LinearLayout>
It appears that it's quite complicated to do it with an Async Task but here is a Snippet coming from https://stackoverflow.com/a/17878191/2545832 but a bit more complete (but still quite simple) which is working (I tested it):
Main Activity:
import java.util.ArrayList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
ListView lvCallList;
ProgressDialog pd;
ArrayList<String> aa = new ArrayList<String>();
ArrayList<String> num= new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvCallList = (ListView) findViewById(R.id.list);
new AsyncTask<Void, Void, Void>()
{
#Override
protected void onPreExecute()
{
pd = ProgressDialog.show(MainActivity.this,
"Loading..", "Please Wait", true, false);
}// End of onPreExecute method
#Override
protected Void doInBackground(Void... params)
{
getContacts();
return null;
}// End of doInBackground method
#Override
protected void onPostExecute(Void result)
{
pd.dismiss();
CustomAdapter cus = new CustomAdapter(MainActivity.this);
// ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,aa);
lvCallList.setAdapter(cus);
}//End of onPostExecute method
}.execute((Void[]) null);
}
private void getContacts()
{
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,null, null, null);
if (cur.getCount() > 0)
{
while (cur.moveToNext())
{
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
aa.add(name);
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = cr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id},
null);
while (pCur.moveToNext())
{
String phoneNumber = pCur.getString(pCur.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));
num.add(phoneNumber);
}
pCur.close();
}
}
}
}
public class CustomAdapter extends BaseAdapter
{
/*
* Variables Declaration section
*/
private Context mContext;
public CustomAdapter(Context context)
{
mContext = context;
}//End of CustomAdapter constructor
public int getCount()
{
return aa.size();
}//End of getCount method
public Object getItem(int position)
{
return position;
}//End of getItem method
public long getItemId(int position)
{
return position;
}//End of getItemId method
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
final int pos = position;
if (convertView == null)
{
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.display_contact, null);
holder.textviewName = (TextView) convertView.findViewById(R.id.textView1);
holder.textviewNumber = (TextView) convertView.findViewById(R.id.textView2);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}//End of if condition
else
{
holder = (ViewHolder) convertView.getTag();
}//End of else
holder.checkbox.setId(position);
holder.textviewName.setId(position);
holder.textviewNumber.setId(position);
holder.textviewName.setText(aa.get(position));
holder.textviewNumber.setText("No. "+num.get(position));
holder.id = position;
return convertView;
}//End of getView method
}//End of CustomAdapter instance inner class
static class ViewHolder
{
TextView textviewName;
TextView textviewNumber;
CheckBox checkbox;
int id;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/list">
</ListView>
display_contact.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView1"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView2"/>
<CheckBox android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/checkBox1"/>
</LinearLayout>
I saw in your code that you were able to select many items so it mustn't be a problem for you to select many contacts from this list. You've two options : listener on each checkboxes or a long click listener on the list.
Good luck :)

How to use a layout as empty view for a listview when the adapter has zero elements

list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ListView
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tab on icon to start a Campaign" />
</LinearLayout>
Activity+list_demonstration.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Active Campaign"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#4AE56B" />
<TextView
android:id="#+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Closed Campaign"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ScrollView
android:layout_width="wrap_content"
android:layout_height="130dp" >
<ListView
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
I m trying to make an listview that is empty in the starting of the application.in which a textview will give information to tab on icon..,and when user tab and create an app.the data shown in the listview..bt listview is giving an error ,how to solve it..
Demo.java // custom adapter
package com.example.smscampaign;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Demo extends ArrayAdapter{
private Campaign_Details list;
// used to keep selected position in ListView
private int selectedPos = -1; // init value for not-selected
private Context context;
private String[] values;
public Demo(Context context, String[] values) {
super(context, R.layout.activity_list_demostration);
this.context = context;
this.values = values;
}
public void setSelectedPosition(int pos){
selectedPos = pos;
// inform the view of this change
notifyDataSetChanged();
}
public int getSelectedPosition(){
return selectedPos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
LayoutInflater vi = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list, null);
// get text view
TextView label = (TextView)v.findViewById(R.id.text1);
ImageView btn=(ImageView)v.findViewById(R.id.imageView1);
if (convertView == null) {
v = vi.inflate(R.layout.list, parent, false);
}
else
v = convertView;
TextView text1 = (TextView) v.findViewById(R.id.text1);
return v;
}
}
Campaign_Details.java
package com.example.smscampaign;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class Campaign_Details extends Activity {
private Demo selectedAdapter;
private ArrayList<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
DataBaseHandler info= new DataBaseHandler(this);
info.open();
String data=info.getData();
info.close();
String[] values= new String[]{ data };
//txt.setText(data);
// Button next=(Button) findViewById(R.id.next);
// Map<String, String[]> storage = new HashMap<String, String[]>();
// String[] tableItems = storage.get("ContactTable");
// next.setOnClickListener(this);
// final ListView listview = (ListView) findViewById(R.id.listview);
ListView listview = (ListView) findViewById(R.id.listView1);
TextView emptyText = (TextView)findViewById(android.R.id.empty);
listview .setEmptyView(emptyText);
// listview.setEmptyView((LinearLayout) findViewById(R.id.emptyText));
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < data.length(); ++i) {
selectedAdapter = new Demo(this,values);
selectedAdapter.setNotifyOnChange(true);
listview.setAdapter(selectedAdapter);
list.add(data);
}
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
Intent n = new Intent(getApplicationContext(), SmsSend.class);
startActivity(n);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.main2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.nextPage:
Intent i = new Intent(this,SmsSend.class);
startActivity(i);
break;
}
return super.onOptionsItemSelected(item);
}
}
UPDATE:
You have done everything wrong. you need to change as follows.
public Demo(Context context, String[] values) {
super(context, R.layout.activity_list_demostration);
this.context = context;
this.values = values;
}
to
public Demo(Context context, String[] values) {
super(context, values);
this.context = context;
this.values = values;
}
In Campaign_Details Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_demostration);
ListView listview = (ListView) findViewById(R.id.listView1);
TextView emptyText = (TextView)findViewById(android.R.id.empty);
According to your question finally you need to change here from
ListView listview = (ListView) findViewById(R.id.listView1);
to
ListView listview = (ListView) findViewById(R.id.listView);

Contact List with Multiple Selection using CheckBoxes

I am trying to create a List in which I take the Contacts I have in my android phone, with CheckBoxes and Images. For now I am just trying to get the contacts on the list with the checkbox.
Code is as Follows :
Problems I am facing :
1) Unable to create ViewHolder Properly
2) Unable to populate contacts into a adapter
3) Unable to retrive images from contacts
main.java
package com.example.curs;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.provider.ContactsContract;
import android.view.Menu;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState );
setContentView(R.layout.activity_main);
Cursor mCursor = getContacts();
startManagingCursor(mCursor);
my_custom_adapter adapter = new my_custom_adapter(this, // Context.
android.R.layout.simple_list_item_multiple_choice, // Specify the row template
// to use (here, two
// columns bound to the
// two retrieved cursor
// rows).
mCursor, // Pass in the cursor to bind to.
// Array of cursor columns to bind to.
new String []{ ContactsContract.Contacts._ID,ContactsContract.Contacts.DISPLAY_NAME },
// Parallel array of which template objects to bind to those
// columns.
new int[] { android.R.id.text1,android.R.id.text2});
setListAdapter(adapter);
}
private Cursor getContacts() {
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs,
sortOrder);
}
}
my_custom_adapter.java
package com.example.curs;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class my_custom_adapter extends SimpleCursorAdapter{
private Context context ;
//ArrayList<String> elements ;
private ArrayList<Boolean> itemChecked ;
Cursor c;
String contact_id;
String contact_name[];
String []from;
int to1;
int to2;
String elements;
public my_custom_adapter(Context context, int layout, Cursor c, String []from, int[] to) {
super(context, layout, c, from, to);
// set_checked(false);
}
/*
// AS EVERY TIME LISTVIEW INFLATE YOUR VIEWS WHEN YOU MOVE THEM SO YOU NEED TO SAVE ALL OF YOUR CHECKBOX STATES IN SOME ARRAYLIST OTHERWISE IT WILL SET ANY DEFAULT VALUE.
private void set_checked(boolean is_checked)
{
for (int i=0; i < c.getCount(); i++) {
itemChecked.add(i, is_checked);
}
}
*/
//THIS IS SIMPLY A CLASS VIEW WILL HOLD DIFFERENT VIEWS OF YOUR ROW.
static class ViewHolder
{
public TextView tv;
public CheckBox cb;
public ImageView iv;
}
public View getView (final int position, View convertView, ViewGroup parent)
{
View rowView = convertView;
View view = null;
if (rowView == null) {
LayoutInflater inflator = (LayoutInflater)context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
rowView = inflator.inflate(R.layout.inflated_layout, null);
final ViewHolder holder = new ViewHolder();
holder.cb = (CheckBox) rowView.findViewById(R.id.checkBox1);
holder.tv = (TextView) rowView.findViewById(R.id.textView1);
holder.iv = (ImageView) rowView.findViewById(R.id.imageView1);
rowView.setTag(holder);
holder.cb
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
/* Model element = (Model) viewHolder.checkbox
.getTag();
element.setSelected(buttonView.isChecked());
*/
}
});
view.setTag(holder);
holder.cb.setTag(c.getPosition());
} else {
view = convertView;
((ViewHolder) view.getTag()).cb.setTag(c.getPosition());
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.tv.setText(c.getString(c.getPosition()));
holder.iv.setImageBitmap(BitmapFactory.decodeResource(Resources.getSystem(),c.getPosition()));
//holder.cb.setChecked(c.getPosition().isSelected());
return view;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
inflated_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="17dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/checkBox1"
android:layout_toRightOf="#+id/imageView1"
android:singleLine="true"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:padding="15dp"/>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:src="#drawable/ic_launcher" />
</RelativeLayout>

Android autocompletetextview won't populate contacts with custom adapter

I've created a custom adapter and custom list item. I was originally using a simple list item and just populated either the name or the number. However, now I'd like to show both the name and phone number in each list item. When I type something now into the autocomplete text it won't populate any anything. I did some error testing and it seems that it isn't even calling the overridden getView() method. I can't seem to figure out why this isn't working.
Also, yes I've added the READ_CONTACTS permission in the manifest.
MainActivity.java
package com.sncrmck.autocompletetest;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.widget.AutoCompleteTextView;
import com.sncrmck.adapter.ContactAdapter;
import com.sncrmck.obj.SimpleContact.SimpleContact;
public class MainActivity extends Activity {
AutoCompleteTextView acTextField;
private ContactAdapter adapter;
public ArrayList<SimpleContact> contactList = new ArrayList<SimpleContact>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ContentResolver resolver = getContentResolver();
acTextField = (AutoCompleteTextView) findViewById(R.id.autoComplete);
Uri contacts = Uri.parse("content://icc/adn");
Cursor cursor = resolver.query(contacts, null, null, null, null);
if (cursor.moveToFirst()) {
String contactName;
String phoneNumber;
int nameColumn = cursor.getColumnIndex("name");
int phoneColumn = cursor.getColumnIndex("number");
do {
contactName = cursor.getString(nameColumn);
phoneNumber = cursor.getString(phoneColumn);
if((contactName != " " || contactName != null) && (phoneNumber!= " " ||phoneNumber!= null))
{
SimpleContact sc = new SimpleContact(contactName, phoneNumber);
contactList.add(sc);
}
} while (cursor.moveToNext());
}
adapter = new ContactAdapter(this, R.layout.grid_item, contactList);
acTextField.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
CustomAdapter.java
package com.sncrmck.adapter;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.sncrmck.autocompletetest.R;
import com.sncrmck.obj.SimpleContact.SimpleContact;
public class ContactAdapter extends ArrayAdapter<SimpleContact> {
private ArrayList<SimpleContact> entries;
private Activity activity;
public ContactAdapter(Activity a, int textViewResourceId, ArrayList<SimpleContact> entries){
super(a, textViewResourceId, entries);
this.entries = entries;
this.activity = a;
Toast.makeText(getContext(), "Constructor", Toast.LENGTH_SHORT).show();
}
public static class ViewHolder{
public TextView item1;
public TextView item2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Toast.makeText(getContext(), "Get View", Toast.LENGTH_SHORT).show();
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi =
(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.grid_item, null);
holder = new ViewHolder();
holder.item1 = (TextView) v.findViewById(R.id.big);
holder.item2 = (TextView) v.findViewById(R.id.small);;
}
else
holder=(ViewHolder)v.getTag();
final SimpleContact contactInfo = entries.get(position);
if (contactInfo != null) {
holder.item1.setText(contactInfo.getContactName());
holder.item2.setText(contactInfo.getContactNumber());
}
return v;
}
}
This is the SimpleContact object I'm passing to the ContactAdapter
package com.sncrmck.obj.SimpleContact;
public class SimpleContact {
private String contactName;
private String contactNumber;
public SimpleContact(String string, String string2) {
this.contactName = string;
this.contactNumber = string2;
}
public String getContactName() { return contactName; }
public void set(String contactName) { this.contactName= contactName; }
public String getContactNumber() { return contactNumber; }
public void setcustomSmall(String contactNumber) { this.contactNumber = contactNumber; }
}
Lastly, this is my custom list item - grid_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:textSize="24dp"
android:id="#+id/big"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:textSize="24dip"
android:id="#+id/small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
You need to override the getFilter() Method of your custom adapter
Also implement a custom filter and override the methods in that.
See this similar question.
I don't have my code available at work so but if I get a chance tonight I'll edit the answer.

Categories

Resources