How to display data from hashmap in android? - android

I have a hashmap which i would like to display. The user will input a name into an editText and when they click the search button, it should go through the hashmap and show the entry that matches the text in edittext with the key.
HashMap<String, Staff> h = new HashMap<String, Staff>();
Staff staff = new Staff("Thomas", "133", "thomas133#email.com");
h.put("Thomsas", staff);
I have tried to adapt the notepad app
package android;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.project.R;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
public class SingleStaff extends ListActivity {
private DBAdapter mDbHelper;
private EditText staffName;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchstaff);
staffName = (EditText) findViewById(R.id.staffname);
mDbHelper = new DBAdapter(this);
mDbHelper.open();
registerForContextMenu(getListView());
Button search = (Button) findViewById(R.id.confirm);
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
String a = staffName.getText().toString();
fillData(a);
}
});
}
private void fillData(String staffName) {
Cursor notesCursor = mDbHelper.fetchSingleStaff(staffName);
startManagingCursor(notesCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{ DBAdapter.STAFF_NAME, DBAdapter.STAFF_ROOM, DBAdapter.STAFF_EMAIL};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text1, R.id.text2, R.id.text3};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.note_row_staff, notesCursor, from, to);
setListAdapter(notes);
}
}
When i run the application and have typed in for example "Thomas" in the edittext and clicked search i get an error message,
android.database.sqlite.SQLiteException: no such column: Thomas: , while compiling: SELECT
DISTINCT _id, name, room, email FROM staff WHERE name=Thomas

You can change your query line to (notice the single quote around staffName:
Cursor mCursor = mDb.query(true, STAFF_TABLE, new String[] {STAFF_ROWID, STAFF_NAME, STAFF_ROOM, STAFF_EMAIL}, STAFF_NAME + "='" + staffName + "'", null, null, null, null, null);
It is better to use ? placeholders to avoid that kind of problem (untested)
public Cursor fetchSingleStaff(String staffName) throws SQLException {
String[] arg = new String[] { staffName };
Cursor mCursor = mDb.query(true, STAFF_TABLE, new String[] {STAFF_ROWID, STAFF_NAME, STAFF_ROOM, STAFF_EMAIL}, STAFF_NAME + "=?", arg , null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
If you want to use a map, you can overload the above method and set the staffName with the corresponding value in your map
public Cursor fetchSingleStaff(Map<String, Staff> m) throws SQLException {
return fetchSingleStaff(m.getFirstName); // m.getFirstName() should be mapped the `Thomas` in `Staff` - Update according to your implementation
}

Related

Displaying the phone number of a contact in Android Contact Content Provider

i am trying to write a program that would display the id, name and phone number of a contact in android. So far the Id and Names of the contact are displayed but the number of the contact doesn't. Can someone help me, below is the code for my program:
package com.example.oghenekaroedoh.provider;
import android.app.ListActivity;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.widget.CursorAdapter;
import android.widget.SimpleCursorAdapter;
public class Provider2Activity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_provider);
Uri allContacts = ContactsContract.Contacts.CONTENT_URI;
//query string for our contacts
//Uri allContacts = Uri.parse("content://contacts/people");
//declare our cursor
Cursor c;
String[] projection = new String[]
{ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER};
//---detect the android version
//---Projection, Filtering, and sorting
/* >>The second parameter of the managedQuery() method (third parameter for the CursorLoader class)
controls how many columns are returned by the query; this parameter is known as the projection
>>The third parameter of the managedQuery() method (fourth parameter for the CursorLoader class)
enable you to specify a SQL WHERE clause to filter the result of the query
>>The fourth parameter of the managedQuery() method (the fifth parameter for the CursorLoader class)
enables you to specify a SQL ORDER BY clause to sort the result of the query, either in ascending or descending order
* */
if (android.os.Build.VERSION.SDK_INT <11) {
//---if the device ids running on OS before Honeycomb
//use the managedQuery() of the Activity class to retrieve a managed cursor
c = managedQuery(allContacts, projection, null, null, null);
}
else {
//---Honeycomb and later use the cursor loader class to retrieve managed cursor---
CursorLoader cursorLoader = new CursorLoader(
this,
allContacts,
projection,
null,
null ,
null);
c = cursorLoader.loadInBackground();
}
//create columns for the contacts display name and the column
String[] columns = new String[] {
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts._ID};
int[] views = new int[] {R.id.contactName, R.id.contactID};
SimpleCursorAdapter adapter;
//detect the android version again..s
if (android.os.Build.VERSION.SDK_INT <11) {
//---if it is before Honeycomb---
//use the SimpleCursorAdapter class to map the cursor to a view (like textViews imageViews e.t.c)
adapter = new SimpleCursorAdapter(
this, R.layout.activity_provider, c, columns, views);
}
else {
//---Honeycomb and later---
////use the SimpleCursorAdapter class to map the cursor to a view (like textViews imageViews e.t.c)
//with an extra parameter known as CursorAdapter.FLAG_REGISTER_CURRENT_OBSERVER
adapter = new SimpleCursorAdapter(
this, R.layout.activity_provider, c, columns, views,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
}
this.setListAdapter(adapter);
PrintContacts(c);
}
private void PrintContacts(Cursor c)
{
//---display the contact id and name and phone number----
if (c.moveToFirst()) {
do{
//---get the contact id and name
String contactID = c.getString(c.getColumnIndex(
ContactsContract.Contacts._ID));
String contactDisplayName =
c.getString(c.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
Log.v("Content Providers", contactID + ", " +
contactDisplayName);
//---get phone number---
int hasPhone =
c.getInt(c.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone == 1) {
Cursor phoneCursor =
getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " +
contactID, null, null);
while (phoneCursor.moveToNext()) {
Log.v("Content Providers",
phoneCursor.getString(
phoneCursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
phoneCursor.close();
}
} while (c.moveToNext());
}
}
}
I got your example working by adding a CustomAdapter MyClassAdapter which extends ArrayAdapter, and populating an ArrayList of Contact objects.
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class Provider2Activity extends ListActivity {
ArrayList<Contact> contacts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_provider2);
contacts = new ArrayList<Contact>();
Uri allContacts = ContactsContract.Contacts.CONTENT_URI;
//declare our cursor
Cursor c;
String[] projection = new String[]
{ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER};
/* >>The second parameter of the managedQuery() method (third parameter for the CursorLoader class)
controls how many columns are returned by the query; this parameter is known as the projection
>>The third parameter of the managedQuery() method (fourth parameter for the CursorLoader class)
enable you to specify a SQL WHERE clause to filter the result of the query
>>The fourth parameter of the managedQuery() method (the fifth parameter for the CursorLoader class)
enables you to specify a SQL ORDER BY clause to sort the result of the query, either in ascending or descending order
* */
if (android.os.Build.VERSION.SDK_INT <11) {
//---if the device ids running on OS before Honeycomb
//use the managedQuery() of the Activity class to retrieve a managed cursor
c = managedQuery(allContacts, projection, null, null, null);
}
else {
//---Honeycomb and later use the cursor loader class to retrieve managed cursor---
CursorLoader cursorLoader = new CursorLoader(
this,
allContacts,
projection,
null,
null ,
null);
c = cursorLoader.loadInBackground();
}
PrintContacts(c);
MyClassAdapter adapter;
//detect the android version again..
if (android.os.Build.VERSION.SDK_INT <11) {
//---if it is before Honeycomb---
adapter = new MyClassAdapter(
this, R.layout.row_line, contacts);
}
else {
//---Honeycomb and later---
adapter = new MyClassAdapter(
this, R.layout.row_line, contacts);
}
this.setListAdapter(adapter);
}
private void PrintContacts(Cursor c)
{
ContentResolver cr = getContentResolver();
//---display the contact id and name and phone number----
if (c.moveToFirst()) {
do{
//---get the contact id and name
String contactID = c.getString(c.getColumnIndex(
ContactsContract.Contacts._ID));
String contactDisplayName =
c.getString(c.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
Log.v("Content Providers", contactID + ", " +
contactDisplayName);
String contactDisplayPhone = "";
//---get phone number---
int hasPhone =
c.getInt(c.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone == 1) {
Cursor phoneCursor =
getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " +
contactID, null, null);
while (phoneCursor.moveToNext()) {
Log.v("Content Providers",
contactDisplayPhone = phoneCursor.getString(
phoneCursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
phoneCursor.close();
}
contacts.add(new Contact(contactDisplayName, contactID, contactDisplayPhone));
} while (c.moveToNext());
}
}
public class Contact{
public String contactName = "";
public String contactID = "";
public String contactNumber = "";
public Contact(String name, String id, String number){
contactName = name;
contactID = id;
contactNumber = number;
}
}
public class MyClassAdapter extends ArrayAdapter<Contact> {
private class ViewHolder {
private TextView name;
private TextView id;
private TextView number;
}
public MyClassAdapter(Context context, int textViewResourceId, ArrayList<Contact> items) {
super(context, textViewResourceId, items);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(this.getContext())
.inflate(R.layout.row_line, parent, false);
viewHolder = new ViewHolder();
viewHolder.name = (TextView) convertView.findViewById(R.id.contactName);
viewHolder.id = (TextView) convertView.findViewById(R.id.contactID);
viewHolder.number = (TextView) convertView.findViewById(R.id.contactNumber);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Contact item = getItem(position);
if (item!= null) {
viewHolder.name.setText(item.contactName);
viewHolder.id.setText(item.contactID);
viewHolder.number.setText(item.contactNumber);
}
return convertView;
}
}
}
row_line.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="wrap_content"
android:orientation="vertical">
<TextView android:id="#+id/contactName"
android:textSize="16sp"
android:textStyle="bold"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/contactID"
android:textSize="16sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/contactNumber"
android:textSize="16sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
activity_provider2.xml:
<RelativeLayout 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" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".Provider2Activity">
<ListView
android:id="#android:id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</ListView>
</RelativeLayout>

Passing cursor values to ArrayList

This is my problem: I have an SQLite DB set up to store some values. In this case, its pretty simple. Two columns (_id, name). I know data is getting stored in the database and I know the cursor I am using to pass that information is also populating. However, when I try to add a cursor value to an ArrayList, I get an error. This is the code for my problem method:
public void sqltest(LDatabase LConnector){
cursor = LConnector.getAllRecords(); //gets the cursor from my db
try{
cursor.moveToFirst();}
catch (Exception e){
log.i("Failed", "Couldn't moveToFirst"); //I get a successful moveToFirst
}
while(cursor.moveToNext()){
try{
getWork.add(cursor.getString(cursor.getColumnIndex("name")));
} catch (Exception h){
Log.i("FAILED", cursor.getString(cursor.getColumnIndex("name")));
}
}
I set up that last log to tell me the value of the cursor at that position. The values entered for the DB always print out so I know the cursor is being populated. Anyone have any idea what I am doing wrong here?
EDIT: LogCat shows these two lines after this is called when an activity starts:
04-12 23:26:26.606: I/MOVED(9478): MOVED TO FIRST
04-12 23:26:26.606: I/FAILED(9478): test1
There are no more verbose errors that describe it better, that is why I am so confused. It just doesn't get stored to the AssetList at all.
This is the code for the getAllRecords() mehod:
public Cursor getAllLifts() throws SQLiteException
{
open();
return database.rawQuery("SELECT * FROM contacts"+";", null);
}
Additionally, here is the create code + the code used for inserting:
Create:
String createQuery = "CREATE TABLE contacts" +
"(_id auto_increment integer primary key," +
"name text);";
db.execSQL(createQuery); // execute the query
Insert:
open(); // open the database
try{
//add more later to get data to insert from usr, just for testing
database.execSQL("INSERT INTO contacts(name) VALUES('test1')");
database.execSQL("INSERT INTO contacts(name) VALUES('test2')");}
catch (Exception insert){
Log.i("INSERT", "INSERT FAILED");
}
close(); // close the database
EDIT: rest of the activity w/ imports
package com.jydev.llogger2;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.content.Context;
import android.database.Cursor;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Create extends Activity implements OnClickListener {
Button buttonNext; //continue button
Button buttonBack; //back button
EditText nameEditText; //editText w/ workout name
EditText commentEditText; //editText w/ comments
Intent info; //intent used to pass extras
String wName = null;
String wComments = null;
ArrayList<String> getWork;
Cursor cursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
commentEditText = (EditText)findViewById(R.id.commentEditText);
buttonBack = (Button)findViewById(R.id.create_back);
buttonNext = (Button)findViewById(R.id.create_continue);
nameEditText = (EditText)findViewById(R.id.nameEditText);
LtDatabase LConnector = new LDatabase(this);
LConnector.insert();
sqltest(LConnector);
}
There are several wrong things. First moveToFirst() returns a boolean so you will never get an exception thrown. Second the while statement will skip one row since you call moveToNext(), thus the first row is skipped. Finally, you get an exception because you did not initialize getwork.
public void sqltest(LDatabase LConnector)
{
cursor = LConnector.getAllRecords(); //gets the cursor from my db
if (cursor.moveToFirst())
{
do
{
try{
getWork.add(cursor.getString(cursor.getColumnIndex("name")));
} catch (Exception h){
Log.i("FAILED", cursor.getString(cursor.getColumnIndex("name")));
}
while (cursor.moveToNext());
}
}
}
In your declaration of getWork
ArrayList<String> getWork = new ArrayList<String>();
for my queries i'm using the following
public ArrayList<T> findAllBy(String selection) {
final SQLiteDatabase db = HELPER.getReadableDatabase();
final ArrayList<T> result = new ArrayList<T>();
final Cursor cursor = db.query(TABLE_NAME, SELECTED_COLS, WHERE, null, null, null, null);
try {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
T model = CREATEOBJECT(cursor);
result.add(model);
cursor.moveToNext();
}
return result;
} finally {
cursor.close();
db.close();
}
}
Where:
HELPER is a instance extendes from SQLiteOpenHelper
TABLE_NAME is a string with the name of the table
SELECTED_COLS is a String[] array with the columns names i want get
WHERE is a string like "COL_NAME = 'value'" or null
CREATEOBJECT is a method for create Object of type T want in my ArrayList<T>
Example CREATEOBJECT
public T CREATEOBJECT(Cursor cursor) {
new T(
cursor.getInt(0), cursor.getString(1)
);
}
public class T {
private long id;
private String name;
T(int id, String name) {
this.id = id;
this.name = name;
}
//...
}

Multiple Contact Picker List

I have a contact picker list with chckboxes of the contacts that have a phone number.
Now, my problem is that can't seem to get the checked contact's name and phone number.
Here is my code:
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class Create_Group extends ListActivity implements OnClickListener{
// List variables
public String[] Contacts = {};
public int[] to = {};
public ListView myListView;
Button save_button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_group);
// Initializing the buttons according to their ID
save_button = (Button)findViewById(R.id.save_group_button);
// Defines listeners for the buttons
save_button.setOnClickListener(this);
Cursor mCursor = getContacts();
startManagingCursor(mCursor);
ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, mCursor,
Contacts = new String[] {ContactsContract.Contacts.DISPLAY_NAME },
to = new int[] { android.R.id.text1 });
setListAdapter(adapter);
myListView = getListView();
myListView.setItemsCanFocus(false);
myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
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.HAS_PHONE_NUMBER + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs,
sortOrder);
}
public void onClick(View src) {
Intent i;
switch (src.getId())
{
case R.id.save_group_button:
int checked_Names_Counter = 0;
// Goes over the list of contacts and checks which were checked
for (int j = 0; j < myListView.getCount(); j++)
{
if (myListView.isItemChecked(j) == true)
{
Cursor cur = getContacts();
ContentResolver contect_resolver = getContentResolver();
cur.moveToFirst();
/**
* Here I tried to compare the IDs but each list has different IDs so it didn't really help me...
// Converts the current checked name ID into a String
String Checked_ID = String.valueOf(myListView.getCheckedItemIds()[checked_Names_Counter]);
// Checks if the current checked ID matches the cursors ID, if not move the cursor to the next name
while (Checked_ID != cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID)))
{
cur.moveToNext();
}
*/
/**
* Here I tried to compare the names, even though it's not a good pratice, and it didn't work either...
String Checked_Name = myListView.getAdapter().getItem(checked_Names_Counter).toString();
// Checks if the current checked ID matches the cursors ID, if not move the cursor to the next name
while (Checked_Name != cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)))
{
cur.moveToNext();
}
*/
String id = cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String name = "";
String no = "";
Cursor phoneCur = contect_resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
name = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
no = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
id = null;
name = null;
no = null;
phoneCur = null;
checked_Names_Counter++;
}
}
// Goes back to the Manage Groups screen
i = new Intent(this, Manage_Groups.class);
startActivity(i);
break;
}
}
}
Any ideas?
Thanks!!
It looks like you are so close, I used ListView.getCheckedItemIds() to return unique ids of the selected contacts:
public void onClick(View view) {
long[] ids = myListView.getCheckedItemIds();
for(long id : ids) {
Cursor contact = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id + "" }, null);
// Do whatever you want with the data
}
}
Addition
I have a quick question about this code:
// Goes back to the Manage Groups screen
i = new Intent(this, Manage_Groups.class);
startActivity(i);
Does this bring the user back to a previous Activity? If so you should use finish(); instead. finish() ends the current Activity, taking it off the stack and freeing up any memory (less memory wasted means a faster app.) It also allows the previous Activity to restore the saved state when it left (filled in EditTexts, previous Spinner selections, toggle button and checkmarks, etc.) The Activity resumes where the user left off.

Contact list isn't in Alphabetical order in Listview

I am using the Android Eclair 2.1 platform.
The working behind this code is, it will access all the contacts from the Emulator and will display in the list view for each contact like this
Contact Name, Contact Number, Email
There are 2 issues for this code is
I did run the program, after that I created a new contact it won't be in alphabetical order
[ eg : when I create a name starting from B it wouldn't go after A, instead it go to the last place ]
2.If a contact has no Email or Number it will receive the previous contact's Email or Number
Here is the code
public class GetAllDatas extends Activity {
ListView lvItem;
private Button btnAdd;
String displayName="", emailAddress="", phoneNumber="";
ArrayList<String> contactlist=new ArrayList<String>();
ArrayAdapter<String> itemAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lvItem = (ListView)this.findViewById(R.id.lvitems);
btnAdd = (Button)this.findViewById(R.id.btnAddItem);
itemAdapter = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1,contactlist);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
readContacts();
}
});
}
private void readContacts()
{
ContentResolver cr =getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext())
{
displayName =Cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME) );
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor emails = cr.query(Email.CONTENT_URI,null,Email.CONTACT_ID + " = " + id, null, null);
while (emails.moveToNext())
{
emailAddress = emails.getString(emails.getColumnIndex(Email.DATA));
break;
}
emails.close();
if(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PH ONE_NUMBER))) > 0)
{
Cursor pCur =cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDat aKinds.Phone.CONTACT_ID +" = ?",new String[]{id}, null);
while (pCur.moveToNext())
{
phoneNumber =pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
break;
}
pCur.close();
}
// To display the Details
contactlist.add(displayName+", "+phoneNumber+", "+ emailAddress+"\n");
itemAdapter.notifyDataSetChanged();
}
cursor.close();
}
}
Any link or site to refer and study to solve this problems if so send me the link ?
Check the tested code below
package stack.examples;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class GetAllDatas extends Activity {
ListView lvItem;
private Button btnAdd;
String displayName="", emailAddress="", phoneNumber="";
ArrayList<String> contactlist=new ArrayList<String>();
ArrayAdapter<String> itemAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lvItem = (ListView)this.findViewById(R.id.listView_items);
btnAdd = (Button)this.findViewById(R.id.btnAddItem);
itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,contactlist);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
readContacts();
}
});
}
private void readContacts()
{
ContentResolver cr =getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext())
{
displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor emails = cr.query(Email.CONTENT_URI,null,Email.CONTACT_ID + " = " + id, null, null);
while (emails.moveToNext())
{
emailAddress = emails.getString(emails.getColumnIndex(Email.DATA));
break;
}
emails.close();
if(Integer.parseInt(cursor.getString(cursor.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())
{
phoneNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
break;
}
pCur.close();
}
contactlist.add(displayName+","+phoneNumber+","+ emailAddress);
}
cursor.close();
sortList(contactlist);
itemAdapter.notifyDataSetChanged();
}
private static void sortList(List<String> aItems){
Collections.sort(aItems, String.CASE_INSENSITIVE_ORDER);
}
}
To sort the ArrayList in Alphabetical order, you can use
Collections.sort(aItems, String.CASE_INSENSITIVE_ORDER);
Happy Coding !!!
When you query the database you are missing the orderBy:
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
replace the last null with the column to sort by:
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
The last parameter of the query method expects the sorting order.
Please check the documentation query (Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder).
sortOrder How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.

How to save checked listview items to array in android?

I have an app that lists the users contacts in a listview with a checkbox using a simple cursor adapter. Upon pressing a button i would like to save the checked items to an array with a name the user has chosen using edittext so that i can display it later. Also, i was wondering how to create an array or array names or something similar allowing me to select the arrays that have been created.
Specific code is much appreciated.
Thanks in advance for your help.
here is my code:
package com.contacts5;
import android.app.ListActivity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class contacts5 extends ListActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Cursor mCursor = getContacts();
startManagingCursor(mCursor);
ListAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_multiple_choice,
mCursor,
new String[] { ContactsContract.Contacts.DISPLAY_NAME ,
ContactsContract.Contacts._ID},
new int[] { android.R.id.text1, android.R.id.text2 });
setListAdapter(adapter);
final ListView listView = getListView();
listView.setItemsCanFocus(false);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
private Cursor getContacts()
{
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);
}
}

Categories

Resources