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];
}
};
}
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 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 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();
}
}
all..i have made a demo in android in that i have opened intent of addressbook and in my "onActivityResult" i am binding Contact name to List,All is going well but problem is i want ,if 1 contact name isalready added it shouldnt be added again ,my code is as below:
main.java
package com.example.mycontactpicker;
import java.util.zip.Inflater;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
public Button add;
public TextView contact;
public LinearLayout list;
private static final int CONTACT_PICKER_RESULT = 1200;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add = (Button) findViewById(R.id.add);
list = (LinearLayout) findViewById(R.id.list);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, CONTACT_PICKER_RESULT);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
String orgName = "";
String title = "";
String emailId = "";
String cNumber = "";
String zipCode = "";
if (c.moveToFirst()) {
// Fetch Contact Name
String DisplayName = c
.getString(c
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
System.out.println("==============Display name:::::::::;; "
+ DisplayName);
View inflateView;
inflateView = LayoutInflater.from(MainActivity.this)
.inflate(R.layout.contact_row, null, true);
contact = (TextView) inflateView.findViewById(R.id.contact);
contact.setText(DisplayName);
list.addView(inflateView);
Toast.makeText(getApplicationContext(), DisplayName,
Toast.LENGTH_LONG).show();
String hasPhone = c
.getString(c
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
String contactId = c.getString(c
.getColumnIndex(ContactsContract.Contacts._ID));
// long id = c.getLong(Integer.parseInt(contactId));
if (DisplayName.equals("") || DisplayName.equals(" ")) {
DisplayName = c
.getString(c
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_ALTERNATIVE));
System.out
.println("=============Display name:::::::::::outer side "
+ DisplayName);
}
}
}
}
}
}
pls help frends
To check if a contact name already exists in the address book you could add...
public boolean contactExists(String contact) {
if (contact != null) {
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()) {
if (contact.equalsIgnoreCase(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)))) {
return true;
}
}
}
return false;
}
**im trying to do n sms app and im using this code to pick some data from contact my
probleam is when im closing my app the contact list is still opend.. how can i close it?
is there any way to pick the data and force close the contact list activity?
**
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity implements OnTouchListener{
TextView a1,a2;
EditText contact,message;
Button send;
String name,phoneNumber;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initilaize();
}
public void initilaize(){
a1 = (TextView)findViewById(R.id.tVContact);
a2 = (TextView)findViewById(R.id.tVMessage);
contact = (EditText)findViewById(R.id.eTContact);
message = (EditText)findViewById(R.id.eTMessage);
send = (Button)findViewById(R.id.button1);
name ="";
phoneNumber="";
contact.setOnTouchListener(this);
}
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
Uri contactData = data.getData();
try {
String id = contactData.getLastPathSegment();
Cursor phoneCur = getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id },
null);
final ArrayList<String> phonesList = new ArrayList<String>();
while (phoneCur.moveToNext()) {
// This would allow you get several phone addresses
// if the phone addresses were stored in an array
String phone = phoneCur
.getString(phoneCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
phonesList.add(phone);
}
phoneCur.close();
//
String name="";
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
}
c.close();
//
if (phonesList.size() == 0) {
} else{
phoneNumber = phonesList.get(0);
this.name = name;
contact.setText(name);
} } catch (Exception e) {
Log.e("FILES", "Failed to get phone data", e);
}
}
}
}
public boolean onTouch1(View v, MotionEvent arg1) {
switch(v.getId()){
case R.id.eTContact:{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent,0);
break;
}
case R.id.button1:{
}
}
return true;
}
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
return false;
}
}
After some research and coding, I am able to get into my callLog. after i added more codes so that I am able to retrieve the numbers from callLog to my edittext, there seem to be errors. I have googled on this but so far to no avail. Any advise? -Simon-
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CallLog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SimonCallLogActivity extends Activity {
/** Called when the activity is first created. */
EditText display;
Button log;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//to go to Call Log//
log=(Button)findViewById(R.id.button1);
log.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
Intent myIntent=new Intent();
myIntent.setAction(Intent.ACTION_CALL_BUTTON);
startActivity(myIntent);
}
});
}
//Call Log//
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
final EditText number = (EditText) findViewById(R.id.editText1);
Cursor cursor = null;
String phoneNo = " ";
List<String> logNumbers = new ArrayList<String>();
String[] projection = new String[] {CallLog.Calls.NUMBER, CallLog.Calls.DATE, CallLog.Calls.CACHED_NAME};
Uri contacts = CallLog.Calls.CONTENT_URI;
Cursor managedCursor = managedQuery(contacts, projection, null, null, CallLog.Calls.DATE + " ASC");
getColumnData(managedCursor);
}
private void getColumnData(Cursor cur){
try{
if (cur.moveToFirst()) {
String name;
String number;
long date;
int nameColumn = cur.getColumnIndex(CallLog.Calls.CACHED_NAME);
int numberColumn = cur.getColumnIndex(CallLog.Calls.NUMBER);
int dateColumn = cur.getColumnIndex(CallLog.Calls.DATE);
System.out.println("Reading Call Details: ");
do {
name = cur.getString(nameColumn);
number = cur.getString(numberColumn);
date = cur.getLong(dateColumn);
System.out.println(number + ":"+ new Date(date) +":"+name);
// number.setText(numberColumn);
} while (cur.moveToNext());
}
}
finally
{
cur.close();
}
final String [] items = logNumbers.toArray(new String[logNumbers.size() ]) ;
AlertDialog.Builder builder = new AlertDialog.Builder(SimonCallLogActivity.this);
builder.setTitle("Choose a number: ");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
// TODO Auto-generated method stub
String selectedNumber = items[item].toString();
selectedNumber= selectedNumber.replace("-","");
selectedNumber= selectedNumber.replace("Home:", "");
selectedNumber= selectedNumber.replace("Mobile:", "");
selectedNumber= selectedNumber.replace("Work:", "");
selectedNumber= selectedNumber.replace("Other:", "");
//selectedNumber = selectedNumber.replace("+","");
number.setText(selectedNumber);
}
});
AlertDialog alert = builder.create();
if(logNumbers.size()>1){
alert.show();
}else{
String selectedNumber= phoneNo.toString();
selectedNumber=selectedNumber.replace("-", "");
number.setText(selectedNumber);
}
if(phoneNo.length()==0){
Log.d("SIMON", "No contact");
}
}
break;
}
}else
{
//gracefully handle failure
Log.w("SIMON","Warning activity not okay");
}
}
}
Declare logNumbers and number as members of your SimonCallLogActivity class.
public class SimonCallLogActivity extends Activity {
/** Member variables */
EditText display;
Button log;
List<String> logNumbers = new ArrayList<String>();
EditText number;
...
...
}
Remove their local declarations..