Displaying wrong contact photo while scrolling listview - android

I am developing one Loaders & list view simple app. It is exactly like whatsapp's CONTACTS tab list. This app get the contacts from mobile and displays the name and image in list item. You can find the fragment code here.
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;
import java.io.InputStream;
public class TabThreeFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
MyCursorAdapter mAdapter;
SimpleCursorAdapter s;
public static final String TAG = "TabThreeFragment";
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setEmptyText("No phone numbers");
mAdapter = new MyCursorAdapter(getActivity(), R.layout.contact_list_item, null, 0 );
setListAdapter(mAdapter);
getLoaderManager().initLoader(0, null, this);
}
static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.CONTACT_STATUS,
ContactsContract.Contacts.CONTACT_PRESENCE,
ContactsContract.Contacts.PHOTO_ID,
ContactsContract.Contacts.LOOKUP_KEY,
};
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Log.d(TAG, "onCreateLoader");
Uri baseUri = ContactsContract.Contacts.CONTENT_URI;
String select = "((" + ContactsContract.Contacts.DISPLAY_NAME + " NOTNULL) AND ("
+ ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1) AND ("
+ ContactsContract.Contacts.DISPLAY_NAME + " != '' ))";
return new CursorLoader(getActivity(), baseUri,
CONTACTS_SUMMARY_PROJECTION, select, null,
ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Log.d(TAG, "onLoadFinished");
mAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
class MyCursorAdapter extends ResourceCursorAdapter{
public MyCursorAdapter(Context context, int layout, Cursor c, int flags) {
super(context, layout, c, flags);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView contactName = (TextView) view.findViewById(R.id.textView1);
contactName.setText(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
ImageView imageView = (ImageView) view.findViewById(R.id.profileImage);
Bitmap profileImage = getPhoto(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)));
//TextView ID = (TextView) view.findViewById(R.id.textView2);
if(profileImage !=null)
{
imageView.setImageBitmap(profileImage);
}
}
private Bitmap getPhoto(String id){
Log.d(TAG, id + "-----");
Bitmap photo = null;
try{
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(
getActivity().getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI , new Long(id).longValue()));
if(inputStream != null)
photo= BitmapFactory.decodeStream(inputStream);
}catch (Exception e){
}
return photo;
}
}
}
List Item Layout file:- contact_list_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="match_parent"
android:layout_height="wrap_content" android:gravity="center_vertical" android:layout_marginLeft="8dp"
android:layout_marginRight="8dp" android:layout_marginTop="6dp" android:layout_marginBottom="6dp">
<ImageView android:id="#+id/profileImage"
android:src="#drawable/ic_launcher"
android:layout_weight="0" android:layout_width="50dp"
android:layout_height="50dp"/>
<LinearLayout android:orientation="vertical"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="6dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/textView1" />
<TextView
android:id="#+id/textView2"
android:paddingLeft="6dp"
android:textSize="16dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dummy Content fro subtile"
/>
</LinearLayout>>
</LinearLayout>
My problem, app is displayed the contact details and photos but photos are changing every time when I scroll up and down. It means one contact information displaying with other contact's photo.
Did I miss anything?

use
if(profileImage !=null){
imageView.setImageBitmap(profileImage);
}else{
imageView.setImageDrawable(null);
}
inside your getview()

Related

ListView not populating with FragmentActivity

I'm building my first AndroidApp and can't get the ListView to populate with data from my database. The data is definitely there because I can loop through it and Toast() it and the data shows up - I just can't get it into the ListView for some reason. Below is the code:
ListSmsRecipients.java
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class ListSmsRecipients extends Base_Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.smslist);
Button addSmsRecipient = (Button) findViewById(R.id.btn_listSms_addSms);
DbHelper dbhelper = new DbHelper(getApplicationContext());
SQLiteDatabase db = dbhelper.getWritableDatabase();
String[] from = new String[] { DbHelper.SMS_NAME, DbHelper.SMS_PHONE, DbHelper.SMS_MESSAGE };
String[] column = new String[] {DbHelper.SMS_ID, DbHelper.SMS_NAME, DbHelper.SMS_PHONE, DbHelper.SMS_MESSAGE };
int[] toViewIDs = new int[] { R.id.temp_smslist_item_name, R.id.temp_smslist_item_phone, R.id.temp_smslist_item_message };
Cursor cursor = db.query(DbHelper.SMS_TABLE_NAME, column, null, null, null, null, null);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.smslist_item, cursor, from, toViewIDs);
ListView list = (ListView)findViewById(R.id.listview_smsList);
list.setAdapter(adapter);
// This works
cursor.moveToFirst();
while (cursor.moveToNext())
{
String name = cursor.getString(cursor.getColumnIndex(DbHelper.SMS_NAME));
String phone = cursor.getString(cursor.getColumnIndex(DbHelper.SMS_PHONE));
String message = cursor.getString(cursor.getColumnIndex(DbHelper.SMS_MESSAGE));
Toast.makeText(getApplicationContext(), "Name = " + name + "\nPhone = " + phone + "\nMessage = " + message, Toast.LENGTH_SHORT).show();
}
cursor.close();
}
}
BaseActivity.java
import android.support.v4.app.FragmentActivity;
public class Base_Activity extends FragmentActivity
{
}
smslist.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ListView
android:id="#+id/listview_smsList"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
smslist_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/temp_smslist_item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text" />
<TextView
android:id="#+id/temp_smslist_item_phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text" />
<TextView
android:id="#+id/temp_smslist_item_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
The problem is at adapter declaration. Change the getApplicationContext() to getActivity() as following
SimpleCursorAdapter adapter = new SimpleCursorAdapter(getActivity(), R.layout.smslist_item, cursor, from, toViewIDs);
Hope this will help you.
After the help from Anu and Ramesh_D, I simply changed my code to Extend Activity cursor.close(), and then changed the adapter call to the following: SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.smslist_item, cursor, from, toViewIDs);

how to display contact numbers in MultiAutoCompleteTextView insted of displaying names

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" />

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>

Displaying the button at the end of the ListView with Linear Layout

I am a newbie in android application development. I faced a problem regarding the displaying a button at the end of the List View. I am using Linear Layout. The application can show all the list but cannot show the Button. I have also pasted my XML code here. Any help in this regard, will be highly appreciated.
Mohan
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:id="#+id/contact_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btn_New"
android:width="170dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="20dp"
android:text="Click"
/>
<TextView
android:id="#+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/btn_New"
android:text="#string/hello"
/>
<ListView
android:id="#+id/contactList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/textView"
/>
</RelativeLayout>
contactlistitem.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="horizontal" android:weightSum="1">
<TextView
android:id="#+id/txtDisplayName"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceMedium" >
</TextView>
<ImageView android:id="#+id/contact_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textView1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"></TextView>
</LinearLayout>
ContactListActivity.java
package com.contactlist;
import android.app.Activity;
import android.graphics.BitmapFactory;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.provider.ContactsContract.Data;
public class ContactListActivity extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ContactList contactList=this.getContacts();
ArrayAdapter<Contact> adapter=new ContactAdapter(this,contactList.getContacts());
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
Object o=this.getListAdapter().getItem(position);
Contact c=(Contact)o;
Toast.makeText(this, c.getDisplayName(), Toast.LENGTH_SHORT).show();
Toast.makeText(this, c.getId(), Toast.LENGTH_SHORT).show();
}
private ContactList getContacts()
{
ContactList contactList=new ContactList();
Uri uri=ContactsContract.Contacts.CONTENT_URI;
ContentResolver cr=getContentResolver();
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
Cursor cur=cr.query(uri, null, null, null, sortOrder);
if(cur.getCount() >0)
{
String id;
String img;
String name;
while(cur.moveToNext())
{
Contact c =new Contact();
id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
img= cur.getString(cur.getColumnIndex(ContactsContract.Contacts.PHOTO_ID));
name=cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
final Bitmap photo;
if(img != null) {
photo = queryContactBitmap(img);
} else {
photo = null;
}
c.setId(id);
c.setImage(photo);
c.setDisplayName(name);
contactList.addContact(c);
}
}
// cur.close();
return contactList;
}
private Bitmap queryContactBitmap(String photoId) {
final Cursor photo = managedQuery(
Data.CONTENT_URI,
new String[] {Photo.PHOTO}, // column where the blob is stored
Data._ID + "=?", // select row by id
new String[]{photoId}, // filter by the given photoId
null);
final Bitmap photoBitmap;
if(photo.moveToFirst()) {
byte[] photoBlob = photo.getBlob(
photo.getColumnIndex(Photo.PHOTO));
photoBitmap = BitmapFactory.decodeByteArray(
photoBlob, 0, photoBlob.length);
} else {
photoBitmap = null;
}
photo.close();
return photoBitmap;
}
}
ContactList.java
package com.contactlist;
import java.util.ArrayList;
import java.util.List;
public class ContactList {
private List<Contact> _contacts=new ArrayList<Contact>();
public List<Contact> getContacts(){return _contacts;}
public void addContact(Contact contact){ this._contacts.add(contact);}
}
ContactAdapter.java
package com.contactlist;
import java.util.List;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ContactAdapter extends ArrayAdapter<Contact> {
private final List<Contact> _contacts;
private final Activity _context;
public ContactAdapter(Activity context, List<Contact> contacts)
{
super(context,R.layout.main,contacts);
this._contacts=contacts;
this._context=context;
}
static class ViewHolder {
protected TextView text;
private Contact _contact;
public ImageView imageview;
protected void setContact(Contact contact)
{
text.setText(contact.getDisplayName());
imageview.setImageBitmap(contact.getImage());
_contact=contact;
}
protected Contact getContact() {return _contact;}
}
#Override
public Contact getItem(int position)
{
return _contacts.get(position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View view=null;
if(convertView==null)
{
LayoutInflater inflater=_context.getLayoutInflater();
view=inflater.inflate(R.layout.contactlistitem, null);
final ViewHolder viewHolder=new ViewHolder();
viewHolder.text=(TextView)view.findViewById(R.id.txtDisplayName);
viewHolder.imageview =(ImageView)view.findViewById(R.id.contact_image);
viewHolder.setContact(_contacts.get(position));
view.setTag(viewHolder);
}
else
{
view = convertView;
}
return view;
}
}
Contact.java
package com.contactlist;
import java.util.ArrayList;
import android.R.string;
import android.graphics.Bitmap;
public class Contact {
private String _id;
private String _displayName;
private Bitmap _img;
public String getId(){return _id;}
public String getDisplayName(){return _displayName;}
public Bitmap getImage(){return _img;}
public void setId(String id){_id=id;}
public void setDisplayName(String displayName){_displayName=displayName;}
public void setImage(Bitmap img){_img=img;}
}
Try this and see if it works:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:id="#+id/contact_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btn_New"
android:width="170dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="20dp"
android:text="Click"
/>
<TextView
android:id="#+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/btn_New"
android:text="#string/hello"
/>
<ListView
android:id="#+id/contactList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/textView"
/>
</RelativeLayout>
MainActivity class:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listView = (ListView) findViewById(R.id.contactList);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
}
Now when you put things inside the listView it should not "push" the button or the textView down.
Firstly you have to set a linear layout in a main relative layout and set its gravity bottom
<RelativeLayout
android:width = "fill..."
android....>
<LinearLayout
android:gravity="bottom"
android:id="#+id/linear1"
android:layout_alignParentBottom="true">
<Button/>
</LinearLayout>
<ListView
android:layout_above="#id/linear"/>
android:layout_weight="1"
delete it.
if you are not express 'android:layout_weightSum' on over level that cotains some components are express 'android:layout_weight' but also component that contain 'android:layout_weight="1"' code is exactly change size to fullscreen.
(i'm sorry, i can't speak english very well....)
android:layout_weight="1" is wrong
android:layout_weight="1" delete it
Or use android:layout_weightSum first.

Android contact list (adapter)

(noob question)
Hello,
I am using this code to make a list of all contacts and display the phone number.
Currently I just want to display the name, but I am facing difficulties and I get a force close error.
ActivityManager: Starting: Intent { act=android.intent.action.MAIN
cat=[android.intent.category.LAUNCHER]
cmp=com.beta.cphonebook/.CPhonebook }
The code I am using is this:
PhoneList.java:
package com.beta.cphonebook;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.ListActivity;
import android.os.Bundle;
import android.content.ContentResolver;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.content.ContentUris;
import android.net.Uri;
import android.database.Cursor;
public class PhoneList extends ListActivity {
private SimpleCursorAdapter myAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
ArrayList<String> nlist = new ArrayList<String>();
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));
nlist.add(name);
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
//Query phone here. Covered next
}
}
}
String[] nlistString = new String[nlist.size()];
nlist.toArray(nlistString);
Arrays.sort(nlistString);
int[] mapto = new int[] {R.id.contact_name};
//------------------------------------------------------------------
//This is where I get the error. While trying to use the list adapter
ListAdapter mAdapter = new SimpleCursorAdapter(this,R.layout.phonelist,cur,test,mapto);
this.setListAdapter(mAdapter);
//------------------------------------------------------------------
}
}
phonelist.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">
<ImageView
android:src="#drawable/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name: "
/>
<TextView android:id="#+id/contact_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number: "
/>
<TextView android:id="#+id/contact_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
I know it should be something very simple, but for the past 3 hours, I just can't find it!!
instead of using the SimpleCursorAdapter class you can use ArrayAdapter....because u need to sort the name...and it is after iterating cursor....
so your code can be like the following
private ArrayAdapter<String> myAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
ArrayList<String> nlist = new ArrayList<String>();
if (cur.getCount() > 0) {
if(cur.moveToFirst()) {
do {
Log.i("Test", "---------------------count-------------------" + cur.getCount());
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
nlist.add(name);
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
//Query phone here. Covered next
//String num = cur.getString(cur.getColumnIndex(ContactsContract.PhoneLookup.NUMBER));
}
}while (cur.moveToNext()) ;
}
}
String[] nlistString = new String[nlist.size()];
nlist.toArray(nlistString);
Arrays.sort(nlistString);
myAdapter = new ArrayAdapter<String>(this, R.layout.phonelist, R.id.contact_name, nlistString);
this.setListAdapter(myAdapter);
}
}

Categories

Resources