android programming - android

I know what has to be done.. this is what i have to do..
create a custom listview (with checkboxes on the list row on the left) in your app, with the adapter getting data one be one to your app from contacts app using a service or thread, then inflate it on the view
But I am having trouble implementing it...
i knw the basics too..then pass that arraylist in the adapter...
If any body can help me out.. I am stuck for past week on this... I want to get it over with...
ArrayList<WhateverTypeYouWant> mArrayList = new ArrayList<WhateverTypeYouWant>();
for(mCursor.moveToFirst(); mCursor.moveToNext(); mCursor.isAfterLast()) {
// The Cursor is now set to the right position
mArrayList.add(mCursor.getWhateverTypeYouWant(WHATEVER_COLUMN_INDEX_YOU_WANT));
}
Here is the code...
package com.exiom.productcatalogue;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class WebexAttendeeList extends Activity {
ListView lstAttends;
ListView lstContacts;
private ArrayList<String> aAttendees = new ArrayList<String>();
private ArrayList<String> aContacts= new ArrayList<String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webexattendees);
// lstContacts = (ListView)findViewById(R.id.lstContacts);
lstAttends = (ListView)findViewById(R.id.lstAttendees);
Cursor cur = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> sContact = new HashMap<String, 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));
sContact = new HashMap<String, String>();
Cursor emailCur = getContentResolver().query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
// String emailType = emailCur.getString(
// emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
sContact.put("name", name);
sContact.put("email", email);
mylist.add(sContact);
aAttendees.add(name);
}
emailCur.close();
}
cur.close();
}
// SimpleAdapter mAttendees = new SimpleAdapter(this, mylist, R.layout.multicolumnlayout,
// new String[] {"name", "email"}, new int[] {R.id.NAME, R.id.EMAIL});
// lstContacts.setAdapter(mAttendees);
// lstContacts.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
ArrayAdapter<String> attendAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, aAttendees);
lstAttends.setAdapter(attendAdapter);
lstAttends.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button btnStart = (Button)this.findViewById(R.id.btnStartWebex);
btnStart.setOnClickListener(mStartButtonListener);
Button btnCancel = (Button)this.findViewById(R.id.btnWebexCancel);
btnCancel.setOnClickListener(mCancelButtonListener);
// lstContacts.setOnClickListener(mSelectAttendee);
}
public void StartWebEx()
{
// WebexClient webex = null ;
// String webExId = "";
// String backUrl = "";
//
// webex.getLoginUrl(webExId, backUrl);
int len = lstAttends.getCount();
SparseBooleanArray checked = lstAttends.getCheckedItemPositions();
for (int i = 0; i < len; i++)
if (checked.get(i)) {
String item = aAttendees.get(i).toString();
/* do whatever you want with the checked item */
}
}
private OnClickListener mStartButtonListener = new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
Toast.makeText(getBaseContext(), "Starting WebEx...",Toast.LENGTH_SHORT).show();
// String sSQLCmd = "update U_WEBEX_SETTING set webex_url = '"+edtWURL.getText()+"', "
// + "webex_id = '"+edtWID.getText()+"', "
// + "webex_pw = '"+edtWPW.getText()+"'";
//
// db.execSQL(sSQLCmd);
StartWebEx();
finish();
};
};
private OnClickListener mCancelButtonListener = new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
Toast.makeText(getBaseContext(), "Exiting WebEx...",Toast.LENGTH_LONG).show();
finish();
};
};
private OnClickListener mSelectAttendee = new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
// aAttendees.add(lstContacts);
Toast.makeText(getBaseContext(), "Selected...",Toast.LENGTH_LONG).show();
finish();
};
};
}

I think, this will be helpful to you.
Content Providers

Related

Passing data from one listview to another

I have been trying to pass the contact data from my second activity's list view to my main activity's list view, upon clicking the checkbox.But the data doesn't get transferred. How do I fix this?
MainActivity.java
package com.example.artist.sender;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Parcelable;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
import static android.R.id.input;
import static android.app.AlertDialog.*;
public class MainActivity extends AppCompatActivity {
EditText itemText;
Button addButton;
Button sendText;
TextView text;
Button contact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemText = (EditText) findViewById(R.id.editText);
addButton = (Button) findViewById(R.id.button1);
text=(TextView) findViewById(R.id.textView);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TextUtils.isEmpty(itemText.getText())||(itemText.getText().length()<10)||(itemText.getText().length()>10)) {
itemText.setError("The number is not valid.");
return;
} else {
text.setText(itemText.getText().toString());
itemText.setText("");
return;
}
}
});
Button delete;
delete = (Button) findViewById(R.id.btn2);
delete.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View view) {
int con=text.getLineCount();
if(con==0)
Toast.makeText(MainActivity.this, "No number available to delete", Toast.LENGTH_SHORT).show();
else
text.setText("");
}
});
sendText=(Button) findViewById(R.id.btn3);
sendText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneno = text.getText().toString();
int count = text.getLineCount();
SmsManager smsMgrVar = SmsManager.getDefault();
if (count == 0) {
Toast.makeText(MainActivity.this, "No number available", Toast.LENGTH_SHORT).show();
}
else
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED)
{
try{
smsMgrVar.sendTextMessage(phoneno, null, "Hey There!", null, null);
Toast.makeText(MainActivity.this, "Message Sent",Toast.LENGTH_LONG).show();
}
catch (Exception ErrVar)
{
Toast.makeText(MainActivity.this, "Message Sending Failed", Toast.LENGTH_SHORT).show();
ErrVar.printStackTrace();
}
}
else
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
requestPermissions(new String[]{Manifest.permission.SEND_SMS}, 10);
}
}
}
});
contact =(Button) findViewById(R.id.btn4);
contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
{
startActivity(new Intent(MainActivity.this,contacts.class));
}
}
});
String tempholder=getIntent().getStringExtra("Listviewclickvalue");
text.setText(tempholder);
}
}
contacts.java
package com.example.artist.sender;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import static android.Manifest.permission.READ_CONTACTS;
public class contacts extends MainActivity {
private static final int REQUEST_READ_CONTACTS = 444;
private ListView mListView;
private ProgressDialog pDialog;
private Handler updateBarHandler;
ArrayList<String> contactList;
Cursor cursor;
int counter;
ListView list;
String temp;
TextView itemText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pDialog = new ProgressDialog(contacts.this);
pDialog.setMessage("Reading contacts...");
pDialog.setCancelable(false);
pDialog.show();
mListView = (ListView) findViewById(R.id.list);
updateBarHandler = new Handler();
// Since reading contacts takes more time, let's run it on a separate thread.
new Thread(new Runnable() {
#Override
public void run() {
getContacts();
}
}).start();
// Set onclicklistener to the list item.
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//TODO Do whatever you want with the list data
Toast.makeText(getApplicationContext(), "item clicked : \n" + contactList.get(position), Toast.LENGTH_SHORT).show();
}
});
}
private boolean mayRequestContacts() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
} else {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
return false;
}
/**
* Callback received when a permissions request has been completed.
*/
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getContacts();
}
}
}
public void getContacts() {
if (!mayRequestContacts()) {
return;
}
contactList = new ArrayList<String>();
String phoneNumber = null;
// String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
/* Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;*/
StringBuffer output;
ContentResolver contentResolver = getContentResolver();
cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
// Iterate every contact in the phone
if (cursor.getCount() > 0) {
counter = 0;
while (cursor.moveToNext()) {
output = new StringBuffer();
// Update the progress message
updateBarHandler.post(new Runnable() {
public void run() {
pDialog.setMessage("Reading contacts : " + counter++ + "/" + cursor.getCount());
}
});
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
output.append("\n First Name:" + name);
//This is to read multiple phone numbers associated with the same contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\n Phone number:" + phoneNumber);
}
phoneCursor.close();
/* // Read every email id associated with the contact
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID + " = ?", new String[]{contact_id}, null);
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(DATA));
output.append("\n Email:" + email);
}
emailCursor.close();
String columns[] = {
ContactsContract.CommonDataKinds.Event.START_DATE,
ContactsContract.CommonDataKinds.Event.TYPE,
ContactsContract.CommonDataKinds.Event.MIMETYPE,
};*/
String where = ContactsContract.CommonDataKinds.Event.TYPE + "=" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY +
" and " + ContactsContract.CommonDataKinds.Event.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE + "' and " + ContactsContract.Data.CONTACT_ID + " = " + contact_id;
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME;
/*Cursor birthdayCur = contentResolver.query(ContactsContract.Data.CONTENT_URI, columns, where, selectionArgs, sortOrder);
Log.d("BDAY", birthdayCur.getCount()+"");
if (birthdayCur.getCount() > 0) {
while (birthdayCur.moveToNext()) {
String birthday = birthdayCur.getString(birthdayCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
output.append("Birthday :" + birthday);
Log.d("BDAY", birthday);
}
}
birthdayCur.close();
}*/
// Add the contact to the ArrayList
contactList.add(output.toString());
}
// ListView has to be updated using a ui thread
runOnUiThread(new Runnable() {
#Override
public void run() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.contact_text, R.id.text1, contactList);
mListView.setAdapter(adapter);
}
});
// Dismiss the progressbar after 500 millisecondds
updateBarHandler.postDelayed(new Runnable() {
#Override
public void run() {
pDialog.cancel();
}
}, 500);
}
}
//passing the number to the mainactivity's textview through intent
list=(ListView) findViewById(R.id.list);
final String listview[] = new String[list.getCount()];
for (int j = 0; j < list.getCount(); j++) {
View v = list.getChildAt(j);
TextView tv = (TextView) v.findViewById(R.id.text1);
listview[j] = (String) tv.getText();
}
itemText = (TextView) findViewById(R.id.text1);
final String number = itemText.getText().toString();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, listview);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if ((number.matches("[0-9]+"))&&(number.length()==10))
temp = listview[position].toString();
Intent intent = new Intent(contacts.this, MainActivity.class);
intent.putExtra("Listviewclickvalue", temp);
startActivity(intent);
}
}
);
}
}
logcat
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.artist.sender/com.example.artist.sender.contacts}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
This is the logcat for the error. It keeps showing that the setitemOnClickListener keeps referring to a null object whereas, I've already assigned the listview to its respective id.
EDIT:**I've fixed part of the error, by renaming the setContentView(R.layout.activity_main); in the contacts class to setContentView(R.layout.contacts); But now after that, it shows this error, **java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
If the data in the database, or some other storage, only pass the _id or the location, respectively.
Instead of passing many extras, Android way is, actually, Parcable. Here a nice tutorial from Vogella
public class TestModel implements Parcelable {
String name;
String phoneNumber;
//.....
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.name);
dest.writeString(this.phoneNumber);
}
public static final Parcelable.Creator<TestModel> CREATOR = new Parcelable.Creator<TestModel>() {
#Override
public TestModel createFromParcel(Parcel source) {
return new TestModel(source);
}
#Override
public TestModel[] newArray(int size) {
return new TestModel[size];
}
};
}

Passing data from one listview to another textview

I have been trying to pass the contact data from my second activity's list view to my main activity's list view, upon clicking the data.But the app crashes just on clicking the contacts button. How do I fix this?
MainActivity.java
package com.example.artist.sender;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Parcelable;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
import static android.R.id.input;
import static android.app.AlertDialog.*;
public class MainActivity extends AppCompatActivity {
EditText itemText;
Button addButton;
Button sendText;
TextView text;
Button contact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemText = (EditText) findViewById(R.id.editText);
addButton = (Button) findViewById(R.id.button1);
text=(TextView) findViewById(R.id.textView);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TextUtils.isEmpty(itemText.getText())||(itemText.getText().length()<10)||(itemText.getText().length()>10)) {
itemText.setError("The number is not valid.");
return;
} else {
text.setText(itemText.getText().toString());
itemText.setText("");
return;
}
}
});
Button delete;
delete = (Button) findViewById(R.id.btn2);
delete.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View view) {
int con=text.getLineCount();
if(con==0)
Toast.makeText(MainActivity.this, "No number available to delete", Toast.LENGTH_SHORT).show();
else
text.setText("");
}
});
sendText=(Button) findViewById(R.id.btn3);
sendText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneno = text.getText().toString();
int count = text.getLineCount();
SmsManager smsMgrVar = SmsManager.getDefault();
if (count == 0) {
Toast.makeText(MainActivity.this, "No number available", Toast.LENGTH_SHORT).show();
}
else
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED)
{
try{
smsMgrVar.sendTextMessage(phoneno, null, "Hey There!", null, null);
Toast.makeText(MainActivity.this, "Message Sent",Toast.LENGTH_LONG).show();
}
catch (Exception ErrVar)
{
Toast.makeText(MainActivity.this, "Message Sending Failed", Toast.LENGTH_SHORT).show();
ErrVar.printStackTrace();
}
}
else
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
requestPermissions(new String[]{Manifest.permission.SEND_SMS}, 10);
}
}
}
});
contact =(Button) findViewById(R.id.btn4);
contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
{
startActivity(new Intent(MainActivity.this,contacts.class));
}
}
});
String tempholder=getIntent().getStringExtra("Listviewclickvalue");
text.setText(tempholder);
}
contacts.java
package com.example.artist.sender;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import static android.Manifest.permission.READ_CONTACTS;
public class contacts extends MainActivity {
private static final int REQUEST_READ_CONTACTS = 444;
private ListView mListView;
private ProgressDialog pDialog;
private Handler updateBarHandler;
ArrayList<String> contactList;
Cursor cursor;
int counter;
ListView list;
String temp;
TextView itemText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts);
pDialog = new ProgressDialog(contacts.this);
pDialog.setMessage("Reading contacts...");
pDialog.setCancelable(false);
pDialog.show();
mListView = (ListView) findViewById(R.id.list);
updateBarHandler = new Handler();
// Since reading contacts takes more time, let's run it on a separate thread.
new Thread(new Runnable() {
#Override
public void run() {
getContacts();
}
}).start();
// Set onclicklistener to the list item.
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//TODO Do whatever you want with the list data
Toast.makeText(getApplicationContext(), "item clicked : \n" + contactList.get(position), Toast.LENGTH_SHORT).show();
}
});
}
private boolean mayRequestContacts() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED)
{
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
} else {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
return false;
}
/**
* Callback received when a permissions request has been completed.
*/
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getContacts();
}
}
}
public void getContacts() {
if (!mayRequestContacts()) {
return;
}
contactList = new ArrayList<String>();
String phoneNumber = null;
// String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
/* Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;*/
StringBuffer output;
ContentResolver contentResolver = getContentResolver();
cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
// Iterate every contact in the phone
if (cursor.getCount() > 0) {
counter = 0;
while (cursor.moveToNext()) {
output = new StringBuffer();
// Update the progress message
updateBarHandler.post(new Runnable() {
public void run() {
pDialog.setMessage("Reading contacts : " + counter++ + "/" + cursor.getCount());
}
});
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
output.append("\n First Name:" + name);
//This is to read multiple phone numbers associated with the same contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\n Phone number:" + phoneNumber);
}
phoneCursor.close();
/* // Read every email id associated with the contact
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID + " = ?", new String[]{contact_id}, null);
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(DATA));
output.append("\n Email:" + email);
}
emailCursor.close();
String columns[] = {
ContactsContract.CommonDataKinds.Event.START_DATE,
ContactsContract.CommonDataKinds.Event.TYPE,
ContactsContract.CommonDataKinds.Event.MIMETYPE,
};*/
String where = ContactsContract.CommonDataKinds.Event.TYPE + "=" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY +
" and " + ContactsContract.CommonDataKinds.Event.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE + "' and " + ContactsContract.Data.CONTACT_ID + " = " + contact_id;
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME;
/*Cursor birthdayCur = contentResolver.query(ContactsContract.Data.CONTENT_URI, columns, where, selectionArgs, sortOrder);
Log.d("BDAY", birthdayCur.getCount()+"");
if (birthdayCur.getCount() > 0) {
while (birthdayCur.moveToNext()) {
String birthday = birthdayCur.getString(birthdayCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
output.append("Birthday :" + birthday);
Log.d("BDAY", birthday);
}
}
birthdayCur.close();
}*/
// Add the contact to the ArrayList
contactList.add(output.toString());
}
// ListView has to be updated using a ui thread
runOnUiThread(new Runnable() {
#Override
public void run() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.contact_text, R.id.text1, contactList);
mListView.setAdapter(adapter);
}
});
// Dismiss the progressbar after 500 millisecondds
updateBarHandler.postDelayed(new Runnable() {
#Override
public void run() {
pDialog.cancel();
}
}, 500);
}
}
//passing the number to the mainactivity's textview through intent
list=(ListView) findViewById(R.id.list);
final String listview[] = new String[list.getCount()];
for (int j = 0; j < list.getCount(); j++) {
View v = list.getChildAt(j);
TextView tv = (TextView) v.findViewById(R.id.text1);
listview[j] = (String) tv.getText();
}
itemText = (TextView) findViewById(R.id.text1);
final String number = itemText.getText().toString();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, listview);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if ((number.matches("[0-9]+"))&&(number.length()==10))
temp = listview[position].toString();
Intent intent = new Intent(contacts.this, MainActivity.class);
intent.putExtra("Listviewclickvalue", temp);
startActivity(intent);
}
}
);
}
logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.example.artist.sender.contacts.getContacts(contacts.java:236)
at com.example.artist.sender.contacts$1.run(contacts.java:57)
at java.lang.Thread.run(Thread.java:818)
This is the logcat for the error. It keeps showing that the findViewById keeps referring to a null object whereas, I've already assigned all the variables to their respective ids.

How to save Array of phone number into SharedPreference

I want to save phone number using SharedPreference . As it has been fetched from phone book and set in textView i am unable to save every one of them in SharedPreference. Please help me towards how to save and retrive set of phone number(array or set) via SharedPreference and send it to another fragment for messaging the number.
Contact.java
package com.kamal.sos10;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.nfc.Tag;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.content.Intent;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.reflect.Array;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class Contact extends AppCompatActivity {
EditText msg,editText2,editText3,editText4;
Button con1,con2,con3;
TextView textView3,textView5,textView6,textView7,textView8,textView9;
TextView text1;
// static final int PICK_CONTACT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact);
msg=(EditText)findViewById(R.id.msg);
// editText2=(EditText)findViewById(R.id.editText2);
textView3=(TextView)findViewById(R.id.textView3);
// text1=(TextView)findViewById(R.id.first);
textView5=(TextView)findViewById(R.id.textView5);
textView6=(TextView)findViewById(R.id.textView6);
textView7=(TextView)findViewById(R.id.textView7);
textView8=(TextView)findViewById(R.id.textView8);
textView9=(TextView)findViewById(R.id.textView9);
con1=(Button)findViewById(R.id.con1);
con2=(Button)findViewById(R.id.con2);
con3=(Button)findViewById(R.id.con3);
con1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.putExtra("extra_text1", "1");
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
if (intent.resolveActivity(Contact.this.getPackageManager()) != null) {
startActivityForResult(intent, 1);
}
}
});
con2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.putExtra("extra_text2", "2");
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
if (intent.resolveActivity(Contact.this.getPackageManager()) != null) {
startActivityForResult(intent,2);
}
}
});
con3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.putExtra("extra_text3", "3");
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
if (intent.resolveActivity(Contact.this.getPackageManager()) != null) {
startActivityForResult(intent, 3);
}
}
});
int num = Integer.valueOf(textView3.getText().toString());
int num2 = Integer.valueOf(textView6.getText().toString());
int num3 = Integer.valueOf(textView7.getText().toString());
Integer[] array=new Integer[3];
array[0]=num;
array[1]=num;
array[2]=num;
for (int j=0;j<3;j++)
{
Log.i("key", String.valueOf(array[j]));
}
/*
SharedPreferences sharedPreferences=this.getSharedPreferences("com.kamal.sos10", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putInt("array_size", strings.length);
for(int i=0;i<strings.length; i++)
edit.putString("array_" + i, strings[i]);
edit.commit();
int size = sharedPreferences.getInt("array_size", 0);
strings = new String[size];
for(int i=0; i<size; i++) {
strings[i]= sharedPreferences.getString("array_" + i, null);
Log.i("sdert",strings[i]);
}
*/
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 || requestCode == 2 || requestCode == 3) {
if (resultCode == this.RESULT_OK) {
contactPicked(data,requestCode);
}
}
}
private void contactPicked(Intent data,int req) {
ContentResolver cr = this.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
cur.moveToFirst();
try {
// getData() method will have the Content Uri of the selected contact
Uri uri = data.getData();
//Query the content uri
cur = this.getContentResolver().query(uri, null, null, null, null);
cur.moveToFirst();
// column index of the contact ID
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
// column index of the contact name
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// column index of the phone number
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll(" ", "");
String text1 = getIntent().getStringExtra("extra_text1");
Toast.makeText(Contact.this, text1, Toast.LENGTH_SHORT).show();
if (req==1)
{
textView3.setText(phone);
Toast.makeText(Contact.this, textView3.getText(), Toast.LENGTH_SHORT).show();
int num = Integer.valueOf(textView3.getText().toString());
Log.i("yut", String.valueOf(num));
textView5.setText(name);
}
if (req==2)
{
textView6.setText(phone);
textView8.setText(name);
}
if (req==3)
{
textView7.setText(phone);
textView9.setText(name);
}
pCur.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
You can save ArrayList/Array/List to SharedPrefernces Here is How you can do it
//Retrieve the values
Set<String> set = myScores.getStringSet("key", null);
//Set the values
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
scoreEditor.putStringSet("key", set);
scoreEditor.commit();
but You an refer this link for details and this link . these Are useful and easy to understand.
For your second part To Send the Data to Fragment
Well I would suggest to save the data in the current Activity/Fragment what ever you have and then get the data from shared preferences in the fragment you wish to open but in case if you really want to get the data and to send the data to the fragment consider this link please.
Note:
By Looking at your code I think there could be large amount of contacts, so it means that you will have a large array. I will suggest you to store them in database as you can easily retrieve/update/delete any data and record.
Update : (after getting clear in comments )
You have written the code to get the contacts from the Textview in On create where as I think the contacts in textviews gets update later where as that code in the onCreate run before it.
make this change
con3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Just check it here
int num = Integer.valueOf(textView3.getText().toString());
int num2 = Integer.valueOf(textView6.getText().toString());
int num3 = Integer.valueOf(textView7.getText().toString());
Integer[] array=new Integer[3];
array[0]=num;
array[1]=num;
array[2]=num;
for (int j=0;j<3;j++)
{
Log.i("key", String.valueOf(array[j]));
}
}
});
after api level 11 Set will be stored in preferences so convert your Array or List to set and stored in preferences
Set<String> setNameYouWantToStore = new HashSet<String>();
setNameYouWantToStore.addAll(listOfDetails);
scoreEditor.putStringSet("keyForSet", setNameYouWantToStore);
scoreEditor.commit();
For Retriving using Iterator
Set<String> setNameYouWantToStore = new HashSet<String>();
Iterator iterator = setNameYouWantToStore.iterator();
while(iterator.hasNext()) {
System.out.println("Value: " + iterator.next() + " ");
}

How to Search the name from a list in android?

Hi i have made an android app in that i load all the addressbook contacts in a list and above it i placed a edittext,if i enter any alphabet then it should give me all values related to that alphabet from the list,I have tried as below,But its not working
My Code is Below:
AutocompliteMain.java
package com.example.autocomplite;
import java.util.ArrayList;
import android.app.Activity;
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.Contacts;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
public class AutocompleteMain extends Activity implements OnItemClickListener,
OnItemSelectedListener {
// Initialize variables
int PICK_CONTACT = 1200;
AutoCompleteTextView textView = null;
private ArrayAdapter<String> adapter;
// Store contacts values in these arraylist
public static ArrayList<String> phoneValueArr = new ArrayList<String>();
public static ArrayList<String> nameValueArr = new ArrayList<String>();
EditText toNumber = null;
String toNumberValue = "";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.autocomplete_main);
final Button Send = (Button) findViewById(R.id.Send);
// Initialize AutoCompleteTextView values
textView = (AutoCompleteTextView) findViewById(R.id.toNumber);
// Create adapter
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line,
new ArrayList<String>());
textView.setThreshold(1);
// Set adapter to AutoCompleteTextView
textView.setAdapter(adapter);
textView.setOnItemClickListener(this);
// Read contact data and add data to ArrayAdapter
// ArrayAdapter used by AutoCompleteTextView
readContactData();
/********** Button Click pass textView object ***********/
Send.setOnClickListener(BtnAction(textView));
}
private OnClickListener BtnAction(final AutoCompleteTextView toNumber) {
return new OnClickListener() {
public void onClick(View v) {
String NameSel = "";
NameSel = toNumber.getText().toString();
final String ToNumber = toNumberValue;
if (ToNumber.length() == 0) {
Toast.makeText(getBaseContext(),
"Please fill phone number", Toast.LENGTH_SHORT)
.show();
} else {
/*
* Toast.makeText(getBaseContext(),
* NameSel+" : "+toNumberValue, Toast.LENGTH_LONG).show();
*/
}
}
};
}
// Read phone contact name and phone numbers
private void readContactData() {
try {
/*********** Reading Contacts Name And Number **********/
String phoneNumber = "";
ContentResolver cr = getBaseContext().getContentResolver();
// Query to get contact name
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
// If data data found in contacts
if (cur.getCount() > 0) {
Log.i("AutocompleteContacts", "Reading contacts........");
int k = 0;
String name = "";
while (cur.moveToNext()) {
String id = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// Check contact have phone number
if (Integer
.parseInt(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// Create query to get phone number by contact id
Cursor pCur = cr
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id },
null);
int j = 0;
while (pCur.moveToNext()) {
// Sometimes get multiple data
if (j == 0) {
// Get Phone number
phoneNumber = ""
+ pCur.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// Add contacts names to adapter
adapter.add(name);
// Add ArrayList names to adapter
phoneValueArr.add(phoneNumber.toString());
nameValueArr.add(name.toString());
j++;
k++;
}
} // End while loop
pCur.close();
} // End if
} // End while loop
} // End Cursor value check
cur.close();
} catch (Exception e) {
Log.i("AutocompleteContacts", "Exception : " + e);
}
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
Log.d("AutocompleteContacts", "onItemSelected() position " + position);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
// Get Array index value for selected name
int i = nameValueArr.indexOf("" + arg0.getItemAtPosition(arg2));
// If name exist in name ArrayList
if (i >= 0) {
// Get Phone Number
toNumberValue = phoneValueArr.get(i);
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
// Show Alert
Intent it = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(it, PICK_CONTACT);
/*
* Toast.makeText(getBaseContext(),
* "Position:"+arg2+" Name:"+arg0.getItemAtPosition
* (arg2)+" Number:"+toNumberValue, Toast.LENGTH_LONG).show();
*/
Log.d("AutocompleteContacts",
"Position:" + arg2 + " Name:"
+ arg0.getItemAtPosition(arg2) + " Number:"
+ toNumberValue);
}
}
protected void onResume() {
super.onResume();
}
protected void onDestroy() {
super.onDestroy();
}
}
autocomplitemain.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20px"
android:text="Write character"
android:layout_marginLeft="10dip"></TextView>
</TableRow>
<TableRow>
<AutoCompleteTextView
android:id="#+id/toNumber"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:textColorHighlight="#000000"
android:textColorLink="#000000"
android:textStyle="bold"
android:width="250dip" />
</TableRow>
<TableRow android:layout_marginTop="2dip">
<Button android:id="#+id/Send"
android:clickable="true"
android:width="86dip"
android:text="Show Selected Value"
android:layout_gravity="center_vertical|center_horizontal"/>
</TableRow>
</TableLayout>
use AutoCompleteTextView instead of EditText. so once u enter any string into it, then it automatically provides list of data with matched entry.
Or else you can try with TextChangeListener for EditText

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.

Categories

Resources