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
Related
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];
}
};
}
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.
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() + " ");
}
I want to do the following.
Pick up three to five contacts out of a special group of contacts or all contacts.
In the list it would be nice to show the contact image.
The selected contacts should have the following information (contact-id, first name, the small version of the contact image to save it as a blob in the database)
I found solutions for the different aspects.
-select multiple contacts:
How to obtain the checked rows in a custom view list
-show contacts from one group
getting contacts from a specified group in android
- photo problem
Getting a Photo from a Contact
But I dont know how to put those together. It would be great if someone could help me putting it together.
Thank you very much!
Frank J.
Solved it, but cant post the answer for some hours.
Solution (not prettyfied yet)
package com.pinkpony.frankj.contactpicker2;
import android.app.Activity;
import android.content.ClipData;
import android.content.ContentResolver;
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.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
/**
* Created by Frank on 28.07.2014.
*/
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
List<String> name1 = new ArrayList<String>();
List<String> name2 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
List<String> img1 = new ArrayList<String>();
MyAdapter ma ;
Button select;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadGroups();
//Toast.makeText(MainActivity.this, toString(), Toast.LENGTH_LONG).show();
Log.d("LongValue", toString());
getAllCallLogs(this.getContentResolver());
ListView lv= (ListView) findViewById(R.id.lv);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
// adding
select = (Button) findViewById(R.id.button1);
select.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
StringBuilder checkedcontacts= new StringBuilder();
System.out.println(".............."+ma.mCheckStates.size());
for(int i = 0; i < name1.size(); i++)
{
if(ma.mCheckStates.get(i)==true)
{
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
}
else
{
System.out.println("..Not Checked......"+name1.get(i).toString());
}
}
//Toast.makeText(getApplicationContext(), checkedcontacts, 1000).show();
Toast.makeText(MainActivity.this, checkedcontacts, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
public void getAllCallLogs(ContentResolver cr) {
/* 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";
Cursor phones = cr.query(uri, projection, selection, selectionArgs,
sortOrder);
*/
// long groupId = id;
String[] cProjection = { ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID };
Cursor groupCursor = getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
cProjection,
ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + "= ?" + " AND "
+ ContactsContract.CommonDataKinds.GroupMembership.MIMETYPE + "='"
+ ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE + "'",
new String[] { String.valueOf(6) }, null);
if (groupCursor != null && groupCursor.moveToFirst())
{
do
{
int nameCoumnIndex = groupCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
String name = groupCursor.getString(nameCoumnIndex);
String szFullname=name;
//long contactId = groupCursor.getLong(groupCursor.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID));
long contactId = groupCursor.getLong(groupCursor.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID));
// Log.d("your tag", "contact " + name + ":"+String.valueOf(contactId));
name1.add(name);
phno1.add(String.valueOf(contactId));
boolean foundToken = false;
// IDENTIFY Contact based on name and token
String szLookupKey = "";
Uri lkup = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI, szFullname);
ContentResolver cr2 = getContentResolver();
Cursor idCursor = getContentResolver().query(lkup, null, null, null, null);
// get all the names
while (idCursor.moveToNext()) {
// get current row/contact ID = ID's are unreliable, so we will go for the lookup key
String szId = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts._ID));
String szName = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
szLookupKey = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
// for this contact ID, search the custom field
Log.d("", "Searching token:" + szId + " Name:" + szName + " LookupKey:" + szLookupKey);
//Log.d(LOG_TAG, "search: "+lid + " key: "+key + " name: "+name);
}
String whereName = ContactsContract.Data.MIMETYPE + " = ? AND " + ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID + " = ?";
String[] whereNameParams = new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE, String.valueOf(contactId) };
Cursor nameCur = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, whereName, whereNameParams, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
while (nameCur.moveToNext()) {
String given = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
String family = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
String display = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
Log.d("your tag", "Vorname " + ":" + given);
name2.add(given);
}
nameCur.close();
} while (groupCursor.moveToNext());
groupCursor.close();
}
}
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
ImageView im1;
CheckBox cb;
MyAdapter()
{
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
private void retrieveContactPhoto(Long contactID) {
Bitmap photo = null;
try {
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(contactID)));
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageBitmap(photo);
}
assert inputStream != null;
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public Bitmap openPhoto(long contactId) {
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = getContentResolver().query(photoUri,
new String[] {ContactsContract.Contacts.Photo.PHOTO}, null, null, null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return BitmapFactory.decodeStream(new ByteArrayInputStream(data));
}
}
} finally {
cursor.close();
}
return null;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.row, null);
TextView tv= (TextView) vi.findViewById(R.id.textView1);
// tv1= (TextView) vi.findViewById(R.id.textView2);
im1= (ImageView) vi.findViewById(R.id.imageView1);
Bitmap photo = null;
Long contactID=Long.valueOf(phno1.get(position));
im1.setImageBitmap(openPhoto(contactID));
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText(""+ name1.get(position));
// tv1.setText(""+phno1.get(position));//
// retrieveContactPhoto(Long.valueOf(phno1.get(position)));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
System.out.println("hello...........");
notifyDataSetChanged();
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
private class GroupInfo {
String id;
String title;
#Override
public String toString() {
return title+ " ("+id+")";
}
public String getId() {
return id;
}
}
List<GroupInfo> groups = new ArrayList<GroupInfo>();
public void loadGroups() {
final String[] GROUP_PROJECTION = new String[] {
ContactsContract.Groups._ID,
ContactsContract.Groups.TITLE,
ContactsContract.Groups.SUMMARY_WITH_PHONES
};
Cursor c = getContentResolver().query(
ContactsContract.Groups.CONTENT_SUMMARY_URI,
GROUP_PROJECTION,
ContactsContract.Groups.DELETED+"!='1' AND "+
ContactsContract.Groups.GROUP_VISIBLE+"!='0' "
,
null,
null);
final int IDX_ID = c.getColumnIndex(ContactsContract.Groups._ID);
final int IDX_TITLE = c.getColumnIndex(ContactsContract.Groups.TITLE);
Map<String,GroupInfo> m = new HashMap<String, GroupInfo>();
while (c.moveToNext()) {
GroupInfo g = new GroupInfo();
g.id = c.getString(IDX_ID);
g.title = c.getString(IDX_TITLE);
int users = c.getInt(c.getColumnIndex(ContactsContract.Groups.SUMMARY_WITH_PHONES));
if (users>0) {
// group with duplicate name?
GroupInfo g2 = m.get(g.title);
if (g2==null) {
m.put(g.title, g);
groups.add(g);
} else {
g2.id+=","+g.id;
}
}
Log.d("LongValue", g.id+g.title);
}
c.close();
}
}
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