So.. my listview items are disappearing after they're scrolled off the screen. They're there, you scoll down, back up, and they're gone. After rotation they reappear, but I have no idea why this is happening.
package com.teslaprime.prirt;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.content.Context;
import android.content.ContentValues;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.CheckBox;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ListView;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.Cursor;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
public class TaskList extends Activity {
List<Task> tasks = new ArrayList<Task>();
TaskAdapter adapter = null;
SQLiteDatabase db = null;
public void populateList(){
adapter = new TaskAdapter();
adapter.clear();
Cursor cur = db.query("tasks",null,null,null,null,null,"timestamp");
cur.moveToFirst();
int anchor = 0;
while (cur.isAfterLast() == false) {
if (cur.getInt(cur.getColumnIndex("completed")) == 1) {
Task task = new Task(cur.getString(cur.getColumnIndex("name")),cur.getString(cur.getColumnIndex("type")));
task.id = cur.getInt(cur.getColumnIndex("id"));
task.completed = 1;
adapter.add(task);
anchor = anchor+1;
}
cur.moveToNext();
}
cur.moveToFirst();
while (cur.isAfterLast() == false) {
if (cur.getInt(cur.getColumnIndex("completed")) == 0) {
Task task = new Task(cur.getString(cur.getColumnIndex("name")),cur.getString(cur.getColumnIndex("type")));
task.id = cur.getInt(cur.getColumnIndex("id"));
adapter.add(task);
}
cur.moveToNext();
}
cur.close();
for (int i = tasks.size(); i <= 8; i++) {
adapter.add(new Task());
}
ListView list = (ListView) findViewById(R.id.tasks);
list.setAdapter(adapter);
list.setSelection(anchor);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent setupProcess = new Intent (TaskList.this, SetupWelcome.class);
boolean first = checkDatabase() ? true : false;
db = openOrCreateDatabase("priRT.db",
SQLiteDatabase.CREATE_IF_NECESSARY,null);
db.setVersion(1);
db.setLockingEnabled(true);
db.execSQL("create table if not exists tasks ("
+ "id integer primary key autoincrement,"
+ "name text,"
+ "time integer,"
+ "completed integer,"
+ "timestamp integer,"
+ "spacer integer,"
+ "type text);");
db.execSQL("create table if not exists schedule ("
+ "id integer primary key autoincrement,"
+ "hours_free integer);");
if (first) { startActivityForResult(setupProcess,0); }
populateList();
Button add = (Button) findViewById(R.id.addTask);
add.setOnClickListener(onAdd);
}
public View.OnClickListener closeTaskListener = new View.OnClickListener(){
public void onClick(View v){
int pos = (Integer) (v.getTag());
Task task = adapter.getItem(pos);
ContentValues values = new ContentValues();
if (task.completed == 1){
values.put("completed", 0);
task.completed = 0;
} else {
values.put("completed", 1);
task.completed = 1;
}
Long time = new Date().getTime();
values.put("timestamp", time);
db.update("tasks", values, "id='"+task.id+"'", null);
populateList();
}
};
private boolean checkDatabase() {
SQLiteDatabase checkDB = null;
try {
checkDB = SQLiteDatabase.openDatabase(
"/data/data/com.teslaprime.prirt/databases/priRT.db", null,
SQLiteDatabase.OPEN_READONLY);
checkDB.close();
} catch (SQLiteException e) {}
return checkDB == null ? true : false;
}
private View.OnClickListener onAdd = new View.OnClickListener() {
public void onClick(View view) {
Intent addTask = new Intent (view.getContext(), TaskEntry.class);
startActivityForResult(addTask, 2);
}
};
protected void onActivityResult(int req, int res, Intent data) {
if (req == 0 && res == RESULT_OK) {
Intent setup = new Intent (TaskList.this, SetupWizard.class);
startActivityForResult(setup, 1);
}
if (req == 2 && res == RESULT_OK) {
Task task = new Task(data.getStringExtra("name"),data.getStringExtra("type"));
adapter.add(task);
ContentValues values = new ContentValues();
values.put("name", data.getStringExtra("name"));
values.put("type", data.getStringExtra("type"));
values.put("completed", 0);
values.put("spacer", 0);
db.insert("tasks", null, values);
Cursor cur = db.query("tasks", null, null, null, null, null, null);
cur.moveToLast();
task.id = cur.getInt(cur.getColumnIndex("id"));
cur.close();
populateList();
}
}
class TaskAdapter extends ArrayAdapter<Task> {
TaskAdapter() {super(TaskList.this,R.layout.task,tasks);}
private List<Task> taskList;
private Context context;
public View getView(int pos, View convertView, ViewGroup parent) {
View task = convertView;
if (convertView == null) {
LayoutInflater inflater = getLayoutInflater();
task = inflater.inflate(R.layout.task,null);
}
if (tasks.get(pos).spacer == 0) {
TextView taskName = (TextView) task.findViewById(R.id.name);
TextView taskType = (TextView) task.findViewById(R.id.type);
taskName.setText(tasks.get(pos).name);
taskType.setText(tasks.get(pos).type);
Task taskList = adapter.getItem(pos);
CheckBox closeTask = (CheckBox) task.findViewById(R.id.closeTask);
if (taskList.completed == 0) {
closeTask.setChecked(false);
} else {
closeTask.setChecked(true);
}
closeTask.setTag(pos);
closeTask.setOnClickListener(closeTaskListener);
} else {
CheckBox closeTask = (CheckBox) task.findViewById(R.id.closeTask);
task.setVisibility(View.GONE);
task.setFocusable(false);
task.setClickable(false);
}
return task;
}
}
}
It may be happening because of the background color of surface in which list appears. Try setting the background color to white in linerlayout and text view coolr black then scroll the through the list view again.
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 have build an app that can insert and retrieve data into listview. i used database that placed on assets folder. When i run my app on device (xiaomi redmi note4) via usb debug but I can not sign up user when I click sign up button. this also happens to the emulator if I delete the database file in "/data/data/com.example.ibtb.bmkg/databases/" with logcat like this
04-12 12:09:27.789 16299-16299/? E/SQLiteLog: (1) no such table: tb_user
04-12 12:09:27.794 16299-16299/? E/SQLiteDatabase: Error inserting email=t password=t nip=t username=t nama=t
android.database.sqlite.SQLiteException: no such table: tb_user (code 1): , while compiling: INSERT INTO tb_user(email,password,nip,username,nama) VALUES (?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1470)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1343)
at com.example.ibtb.bmkg.database.DatabaseHelper.insertUser(DatabaseHelper.java:73)
at com.example.ibtb.bmkg.SignUp$1.onClick(SignUp.java:68)
at android.view.View.performClick(View.java:5619)
at android.view.View$PerformClick.run(View.java:22295)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6342)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:880)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770)
here is my database code
package com.example.ibtb.bmkg.database;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.ibtb.bmkg.model.Instrumen;
import com.example.ibtb.bmkg.model.User;
import com.example.ibtb.bmkg.model.Pengecekan;
import java.util.ArrayList;
import java.util.List;
/**
* Created by IBTB on 08/02/2018.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public static String DB_PATH = "/data/data/com.example.ibtb.bmkg/databases/";
public static String DB_NAME = "bmkgdb.db";
SQLiteDatabase myDataBase;
private final Context myContext;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void openDataBase() {
String dbPath = myContext.getDatabasePath(DB_NAME).getPath();
if (myDataBase != null && myDataBase.isOpen()) {
return;
}
myDataBase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabase() {
if (myDataBase != null) {
myDataBase.close();
}
}
public long insertUser(User c){
myDataBase = this.getWritableDatabase();
ContentValues values = new ContentValues();
/*String query = "select * from tb_user";
Cursor cursor = myDataBase.rawQuery(query,null);
int count = cursor.getCount();
values.put("id_user", count); */
values.put("nama", c.getName());
values.put("nip", c.getNip());
values.put("email", c.getEmail());
values.put("username", c.getUname());
values.put("password", c.getPass());
openDataBase();
long returnValue = myDataBase.insert("tb_user", null, values);
closeDatabase();
return returnValue;}
public String searchPass(String uname) {
myDataBase = this.getReadableDatabase();
String query = "select username, password from tb_user";
Cursor cursor = myDataBase.rawQuery(query, null);
String a, b;
b = "not found";
if (cursor.moveToFirst()) {
do {
a = cursor.getString(0);
//b= cursor.getString(1);
if (a.equals(uname)) {
b = cursor.getString(1);
break;
}
}
while (cursor.moveToNext());
}
return b;
}
public List<Pengecekan> getListPengecekan() {
// String[] whereargs = new String[]{String.valueOf(id)};
Pengecekan pengecekan = null;
List<Pengecekan> PengecekanList = new ArrayList<>();
openDataBase();
Cursor cursor = myDataBase.rawQuery("SELECT A.id_pengecekan, A.pengecekan, A.normal, B.nama_alat FROM tb_pengecekan A, tb_alat B, tb_instrumen C " +
"WHERE C.id_instrumen = B.id_instrumen AND A.id_alat = B.id_alat AND C.id_instrumen = '9' ", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
pengecekan = new Pengecekan(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
PengecekanList.add(pengecekan);
/* if (cursor.moveToFirst()) {
pengecekan = new Pengecekan(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
PengecekanList.add(pengecekan);*/
cursor.moveToNext();}
cursor.close();
close();
return PengecekanList;
}
public Pengecekan getPengecekanId(int id) {
Pengecekan pengecekan = null;
openDataBase();
Cursor cursor = myDataBase.rawQuery("SELECT A.id_pengecekan, A.pengecekan, A.normal, B.nama_alat FROM tb_pengecekan A, tb_alat B, tb_instrumen C " +
"WHERE A.id_pengecekan = ?", new String[]{String.valueOf(id)});
cursor.moveToFirst();
pengecekan = new Pengecekan(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
//Only 1 resul
cursor.close();
closeDatabase();
return pengecekan;
}
public long updatePengecekan(Pengecekan pengecekan) {
ContentValues contentValues = new ContentValues();
contentValues.put("pengecekan", pengecekan.getPengecekan());
contentValues.put("normal", pengecekan.getNormal());
contentValues.put("nama_alat", pengecekan.getNama_alat());
String[] whereArgs = {Integer.toString(pengecekan.getId_pengecekan())};
openDataBase();
long returnValue = myDataBase.update("tb_pengecekan",contentValues, "id_pengecekan=?", whereArgs);
closeDatabase();
return returnValue;
}
public long addPengecekan(Pengecekan pengecekan) {
ContentValues contentValues = new ContentValues();
contentValues.put("ID", pengecekan.getId_pengecekan());
contentValues.put("pengecekan", pengecekan.getPengecekan());
contentValues.put("normal", pengecekan.getNormal());
contentValues.put("nama_alat", pengecekan.getNama_alat());
openDataBase();
long returnValue = myDataBase.insert("tb_pengecekan", null, contentValues);
closeDatabase();
return returnValue;
}
public boolean deletePengecekanById(int id) {
openDataBase();
int result = myDataBase.delete("tb_pengecekan", "id_pengecekan =?", new String[]{String.valueOf(id)});
closeDatabase();
return result !=0;
}
public List<Instrumen> getListInstrumen() {
Instrumen instrumen = null;
List<Instrumen> InstrumenList = new ArrayList<>();
openDataBase();
Cursor cursor = myDataBase.rawQuery("SELECT * FROM tb_instrumen ", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
instrumen = new Instrumen(cursor.getInt(0), cursor.getString(1));
InstrumenList.add(instrumen);
cursor.moveToNext();
}
cursor.close();
close();
return InstrumenList;
}
public Instrumen geInstrumenId(int id) {
Instrumen instrumen = null;
openDataBase();
Cursor cursor = myDataBase.rawQuery("SELECT * FROM tb_instrumen WHERE id_instrumen = ?", new String[]{String.valueOf(id)});
cursor.moveToFirst();
instrumen = new Instrumen(cursor.getInt(0), cursor.getString(1));
//Only 1 resul
cursor.close();
closeDatabase();
return instrumen;
}
}
copy database
File database = getApplicationContext().getDatabasePath(DatabaseHelper.DB_NAME);
if(false == database.exists()) {
myDbHelper.getReadableDatabase();
//Copy db
if(copyDatabase(this)) {
Toast.makeText(this, "Copy database succes", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Copy data error", Toast.LENGTH_SHORT).show();
return;
}
}
SignUp.Java
package com.example.ibtb.bmkg;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.ibtb.bmkg.database.DatabaseHelper;
import com.example.ibtb.bmkg.model.User;
/**
* Created by IBTB on 08/02/2018.
*/
public class SignUp extends Activity {
private Button reg;
private DatabaseHelper dbHelper;
private EditText name, nip, email, uname, pass1, pass2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
dbHelper = new DatabaseHelper(getApplicationContext());
reg = (Button)findViewById(R.id.Bsignupbutton);
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = (EditText) findViewById(R.id.Tfname);
nip = (EditText) findViewById(R.id.Tfnip);
email = (EditText) findViewById(R.id.Tfemail);
uname = (EditText) findViewById(R.id.Tfuname);
pass1 = (EditText) findViewById(R.id.Tfpass1);
pass2 = (EditText) findViewById(R.id.Tfpass2);
String namestr = name.getText().toString();
String nipstr = nip.getText().toString();
String emailstr = email.getText().toString();
String unamestr = uname.getText().toString();
String pass1str = pass1.getText().toString();
String pass2str = pass2.getText().toString();
User c = new User(namestr, nipstr, emailstr, unamestr, pass1str);
if (namestr.isEmpty() || nipstr.isEmpty() || emailstr.isEmpty() || unamestr.isEmpty() || pass1str.isEmpty() || pass2str.isEmpty()) {
Toast full = Toast.makeText(SignUp.this, "Please fill all the coloumn", Toast.LENGTH_SHORT);
full.show();
} else if (!pass1str.equals(pass2str)) {
Toast pass = Toast.makeText(SignUp.this, "Password dont match", Toast.LENGTH_SHORT);
pass.show();
} else {
/*c.setName(namestr);
c.setNip(nipstr);
c.setEmail(emailstr);
c.setUname(unamestr);
c.setPass(pass1str);*/
long result = dbHelper.insertUser(c);
Intent j = new Intent(SignUp.this, MainActivity.class);
startActivity(j);
if (result > 0) {
Toast.makeText(getApplicationContext(), "Added", Toast.LENGTH_SHORT).show();
//back to main activity
finish();
} else {
Toast.makeText(getApplicationContext(), "Add failed", Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
MainActivity.Java
package com.example.ibtb.bmkg;
import android.content.Intent;
import android.app.Activity;
//import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.ibtb.bmkg.database.DatabaseHelper;
public class MainActivity extends Activity {
private Session session;
//private Button button;
DatabaseHelper myDbHelper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
session = new Session(this);
// button = (Button)findViewById(R.id.button);
if(session.loggedin()){
startActivity(new Intent(MainActivity.this,Home.class));
finish();
}
}
public void onButtonClick(View v)
{
if(v.getId()==R.id.Blogin)
{
EditText a = (EditText)findViewById(R.id.Tfusername);
String str = a.getText().toString();
EditText b = (EditText)findViewById(R.id.Tfpassword);
String pass = b.getText().toString();
String password = myDbHelper.searchPass(str);
if (pass.isEmpty() || str.isEmpty()) {
Toast full = Toast.makeText(MainActivity.this, "Please enter username and password", Toast.LENGTH_SHORT);
full.show();
}
else if(pass.equals(password))
{
session.setLoggedin(true);
Intent i = new Intent (MainActivity.this, Home.class);
i.putExtra("Username",str);
startActivity(i);
finish();
}
else
{
Toast temp = Toast.makeText(MainActivity.this, "Username and Password dont match", Toast.LENGTH_SHORT);
temp.show();
}
}
if (v.getId()==R.id.Bsignup)
{
Intent i = new Intent (MainActivity.this, SignUp.class);
startActivity(i);
}
}
/*
public void press (View v){
Intent i = new Intent (MainActivity.this, ListPengecekan2.class);
startActivity(i);
}*/
}
Session.java
package com.example.ibtb.bmkg;
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by IBTB on 06/04/2018.
*/
public class Session {
SharedPreferences prefs;
SharedPreferences.Editor editor;
Context ctx;
public Session(Context ctx){
this.ctx = ctx;
prefs = ctx.getSharedPreferences("myapp", Context.MODE_PRIVATE);
editor = prefs.edit();
}
public void setLoggedin(boolean logggedin){
editor.putBoolean("loggedInmode",logggedin);
editor.commit();
}
public boolean loggedin(){
return prefs.getBoolean("loggedInmode", false);
}
}
ListPengecekan.java
package com.example.ibtb.bmkg;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.ibtb.bmkg.adapter.ListPengecekanAdapter;
import com.example.ibtb.bmkg.database.DatabaseHelper;
import com.example.ibtb.bmkg.model.Pengecekan;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
public class ListPengecekan extends AppCompatActivity {
private ListView lvPengecekan;
private TextView instrumen;
private ListPengecekanAdapter adapter;
private List<Pengecekan> mPengecekanList;
private Button btnAdd;
private DatabaseHelper myDbHelper;
//Cursor c = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pengecekan);
lvPengecekan = (ListView) findViewById(R.id.listview_pengecekan);
btnAdd = (Button)findViewById(R.id.Badd);
myDbHelper = new DatabaseHelper(this);
String instrumen = getIntent().getStringExtra("ins");
TextView tv = (TextView) findViewById(R.id.tv_instrumen);
tv.setText(instrumen);
File database = getApplicationContext().getDatabasePath(DatabaseHelper.DB_NAME);
if(false == database.exists()) {
myDbHelper.getReadableDatabase();
//Copy db
if(copyDatabase(this)) {
Toast.makeText(this, "Copy database succes", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Copy data error", Toast.LENGTH_SHORT).show();
return;
}
}
//String id = getIntent().getStringExtra("id");
mPengecekanList = myDbHelper.getListPengecekan();
adapter = new ListPengecekanAdapter (this, mPengecekanList);
lvPengecekan.setAdapter(adapter);
}
#Override
protected void onResume() {
super.onResume();
mPengecekanList = myDbHelper.getListPengecekan();
//Init adapter
adapter.updateList(mPengecekanList);
}
private boolean copyDatabase(Context context) {
try {
InputStream inputStream = context.getAssets().open(DatabaseHelper.DB_NAME);
String outFileName = DatabaseHelper.DB_PATH + DatabaseHelper.DB_NAME;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[] buff = new byte[1024];
int length = 0;
while ((length = inputStream.read(buff)) > 0) {
outputStream.write(buff, 0, length);
}
outputStream.flush();
outputStream.close();
Log.v("ListPengecekan", "DB copied");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
// });
}
public void onRadioButtonClicked(View view) {
String kondisi="";
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId()) {
case R.id.B:
if (checked)
kondisi = "Baik";
break;
case R.id.RR:
if (checked)
kondisi = "Rusak ringan";
AlertDialog.Builder mBuilder = new AlertDialog.Builder(ListPengecekan.this);
View mView = getLayoutInflater().inflate(R.layout.dialogrusak, null);
mBuilder.setTitle("Keterangan kerusakan");
final Spinner mSpinner = (Spinner) mView.findViewById(R.id.Spenanganan);
final Spinner mSpinner1 = (Spinner) mView.findViewById(R.id.Shasil);
final EditText kronologi = (EditText) mView.findViewById(R.id.ekro);
final EditText lapor = (EditText) mView.findViewById(R.id.elapor);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListPengecekan.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.penaganan));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(ListPengecekan.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.hasil));
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner1.setAdapter(adapter1);
mBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String Kronologi = kronologi.getText().toString();
Toast.makeText(ListPengecekan.this, Kronologi, Toast.LENGTH_SHORT).show();
if (!mSpinner.getSelectedItem().toString().equalsIgnoreCase("Pilih penanganan…")) {
Toast.makeText(ListPengecekan.this, mSpinner.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
dialogInterface.dismiss();
}
if (!mSpinner.getSelectedItem().toString().equalsIgnoreCase("Pilih hasil…")) {
Toast.makeText(ListPengecekan.this, mSpinner1.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
dialogInterface.dismiss();
}
String Lapor = lapor.getText().toString();
Toast.makeText(ListPengecekan.this, Lapor, Toast.LENGTH_SHORT).show();
}
});
mBuilder.setNegativeButton("Batal", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
break;
case R.id.RB:
if (checked)
kondisi = "Rusak berat";
AlertDialog.Builder mBuilder1 = new AlertDialog.Builder(ListPengecekan.this);
View mView1 = getLayoutInflater().inflate(R.layout.dialogrusak, null);
mBuilder1.setTitle("Keterangan kerusakan");
final Spinner mSpinner2 = (Spinner) mView1.findViewById(R.id.Spenanganan);
final Spinner mSpinner3 = (Spinner) mView1.findViewById(R.id.Shasil);
final EditText kronologi1 = (EditText) mView1.findViewById(R.id.ekro);
final EditText lapor1 = (EditText) mView1.findViewById(R.id.elapor);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(ListPengecekan.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.penaganan));
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner2.setAdapter(adapter2);
ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(ListPengecekan.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.hasil));
adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner3.setAdapter(adapter3);
mBuilder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String Kronologi = kronologi1.getText().toString();
Toast.makeText(ListPengecekan.this, Kronologi, Toast.LENGTH_SHORT).show();
if (!mSpinner2.getSelectedItem().toString().equalsIgnoreCase("Pilih penanganan…")) {
Toast.makeText(ListPengecekan.this, mSpinner2.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
dialogInterface.dismiss();
}
if (!mSpinner3.getSelectedItem().toString().equalsIgnoreCase("Pilih hasil…")) {
Toast.makeText(ListPengecekan.this, mSpinner3.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
dialogInterface.dismiss();
}
String Lapor = lapor1.getText().toString();
Toast.makeText(ListPengecekan.this, Lapor, Toast.LENGTH_SHORT).show();
}
});
mBuilder1.setNegativeButton("Batal", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
mBuilder1.setView(mView1);
AlertDialog dialog1 = mBuilder1.create();
dialog1.show();
break;
}
//myDbHelper.execSQl
}
}
Ok your issue could be that the onCreate method does nothing. if you delete an existing/useable database then there are no tables created.
You need to use db.execSql(a_string_with_the_sql_to_create_your_tables); in the onCreate method.
Something like :-
#Override
public void onCreate(SQLiteDatabase db) {
crtsql = "CREATE TABLE IF NOT EXISTS tb_user (id INTEGER PRIMARY KEY,nama TEXT,nip TEXT, email TEXT, password TEXT)";
db.execSQL(crtsql);
}
Note you'd need to do the same for all the other tables. Noting that you need a db.execSQL for each as you can only run 1 SQL statement at a time.
An exception would be if you have other code that copies the database from the assets folder. If so including that would be relevant as if this is the case, this not working could be the issue.
Edit re comments
It has been determined that issue is highly likely that the copy of the database from the assets folder is not being invoked.
To simplify the fix the following is suggested (rather than edit code) :-
Create a Java Class named CopyDBFromAssets i.e. file CopyDBFromAssets.java and copt the following into that class
:-
public class CopyDBFromAssets {
private static final String TAG = "DBASSETCOPY";
String mDBPath, mDatabasename;
CopyDBFromAssets(Context context, String databasename) {
mDatabasename = databasename;
mDBPath = context.getDatabasePath(mDatabasename).getPath();
if(!ifDatabaseExists(mDBPath)) {
Log.d(TAG,
"Attempting to copy database " +
mDatabasename +
" from assets folder."
);
if (copyDatabase(context)) {
Log.d(TAG,"Database " +
mDatabasename + " successfully copied.");
} else {
Log.e(TAG,"Database " + mDatabasename + " NOT COPIED!!!");
}
}
}
private boolean copyDatabase(Context context) {
try {
InputStream inputStream = context.getAssets().open(mDatabasename);
String outFileName = mDBPath;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[] buff = new byte[1024];
int length = 0;
while ((length = inputStream.read(buff)) > 0) {
outputStream.write(buff, 0, length);
}
outputStream.flush();
outputStream.close();
Log.v(TAG, "DB copied");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
private boolean ifDatabaseExists(String dbpath) {
File db = new File(dbpath);
if(db.exists()) return true;
File dir = new File(db.getParent());
if (!dir.exists()) {
dir.mkdirs();
}
return false;
}
}
Edit MainActivity.java to add a single line to invoke the above as per
:-
public class MainActivity extends Activity {
private Session session;
//private Button button;
//DatabaseHelper myDbHelper = new DatabaseHelper(this); //<<<< COMMENTED OUT
DatabaseHelper myDbHelper; //<<<< ADDED
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CopyDBFromAssets cdbfa = new CopyDBFromAssets(this,DatabaseHelper.DB_NAME); //<<<< ADDED LINE
myDbHelper = new DatabaseHelper(this); //<<<< ADDED LINE
session = new Session(this);
// button = (Button)findViewById(R.id.button);
if(session.loggedin()){
startActivity(new Intent(MainActivity.this,Home.class));
finish();
}
}
........ the rest of MainActivity.Java
Notes
DatabaseHelper myDbHelper = new DatabaseHelper(this); has been commented out and split into declaration and instantiation (set)
check all lines with //<<<<
After making the changes above delete the App's data and run. Check the log you should see something along the lines of
:-
04-12 12:39:31.672 1568-1568/soanswers.soanswers D/DBASSETCOPY: Attempting to copy database mydb from assets folder.
04-12 12:39:31.672 1568-1568/soanswers.soanswers V/DBASSETCOPY: DB copied
04-12 12:39:31.672 1568-1568/soanswers.soanswers D/DBASSETCOPY: Database mydb successfully copied.
In the above the database used was called mydb rather than bmkgdb.db
You are inserting record into table which is not exist. Create table before performing insert operation.
i want to check if a phonenumber of my contacts is in a database.
So far i created a listview with a custom adapter and can display contact name, number and image. I added a fourth field that should display if the phonenumber is in the database.
i use asynctask to get a json like this {"android":{"error":"0"}} in case the number is in the database and to {"android":{"error":"1"}} if there is not.
my questions are how can i pass the phonenumber to the asynctask and what should the asynctask return so that the textview can be set to display "ok".
the code i use in all in one class.
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class contactos extends Activity {
ListView lv_addcontacts;
Cursor cur;
ContentResolver cr;
JSONArray android = null;
JSONParser jsonParser = new JSONParser();
private static String url = "my.php";
private static final String TAG_OS = "android";
private static final String TAG_ERROR = "error";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contactos);
readContacts();
if (!((cur.moveToFirst()) || cur.equals(null) || cur.getCount() == 0)) {
} else if (cur.getCount() > 0) {
cur.moveToFirst();
}
lv_addcontacts = (ListView) findViewById(R.id.lv_addcontact);
CustomAdapterAddContacts myad = new CustomAdapterAddContacts();
lv_addcontacts.setAdapter(myad);
}
class CustomAdapterAddContacts extends BaseAdapter {
#Override
public int getCount() {
System.out.println(cur.getCount());
return cur.getCount();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ContactViewHolder contactViewHolder;
if (convertView == null) {
// Inflate the layout
LayoutInflater li = getLayoutInflater();
convertView = li.inflate(
R.layout.contactos_detalle, null);
contactViewHolder = new ContactViewHolder();
contactViewHolder.imgContact = (ImageView) convertView
.findViewById(R.id.imgView_addcontact);
contactViewHolder.txtViewContactName = (TextView) convertView
.findViewById(R.id.txtView_addcontact_contactname);
contactViewHolder.txtViewPhoneNumber = (TextView) convertView
.findViewById(R.id.txtview_addcontact_phonenumber);
contactViewHolder.txtViewCheck = (TextView) convertView
.findViewById(R.id.txtview_addcontact_check);
convertView.setTag(contactViewHolder);
} else {
contactViewHolder = (ContactViewHolder) convertView.getTag();
}
cur.moveToPosition(position);
// Add Contact Name //
String name = cur
.getString(cur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if (name != null)
contactViewHolder.txtViewContactName.setText(name);
else
contactViewHolder.txtViewContactName.setText("Unknown");
// Add Phone Number //
String phoneNumber = cur
.getString(cur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (phoneNumber != null)
contactViewHolder.txtViewPhoneNumber.setText(phoneNumber);
else
contactViewHolder.txtViewPhoneNumber.setText("Unknown");
// start async task to check if phone number is in a database
// if the async task returns true contactViewHolder.txtViewPhoneCheck.setText("OK");
// if the async task returns false contactViewHolder.txtViewPhoneCheck.setText("NOT OK");
new JSONParse().execute(phoneNumber);
Uri uri = getPhotoUri(Long.parseLong(fetchContactIdFromPhoneNumber(phoneNumber)));
if (uri != null) {
contactViewHolder.imgContact.setImageURI(uri);
} else {
contactViewHolder.imgContact
.setImageResource(R.drawable.ic_launcher);
}
return convertView;
}
private String fetchContactIdFromPhoneNumber(String phoneNumber) {
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,Uri.encode(phoneNumber));
Cursor cFetch = getContentResolver().query(uri,
new String[] { PhoneLookup.DISPLAY_NAME, PhoneLookup._ID },
null, null, null);
String contactId = "";
if (cFetch.moveToFirst()) {
cFetch.moveToFirst();
contactId = cFetch.getString(cFetch
.getColumnIndex(PhoneLookup._ID));
}
System.out.println(contactId);
return contactId;
}
public Uri getPhotoUri(long contactId) {
ContentResolver contentResolver = getContentResolver();
try {
Cursor cursor = contentResolver
.query(ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.CONTACT_ID
+ "="
+ contactId
+ " AND "
+ ContactsContract.Data.MIMETYPE
+ "='"
+ ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE
+ "'", null, null);
if (cursor != null) {
if (!cursor.moveToFirst()) {
return null; // no photo
}
} else {
return null; // error in cursor process
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
Uri person = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, contactId);
return Uri.withAppendedPath(person,
ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}
public class ContactViewHolder {
ImageView imgContact;
TextView txtViewContactName;
TextView txtViewPhoneNumber;
TextView txtViewCheck;
}
}
private void readContacts() {
cr = getContentResolver();
cur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
}
// async check if gcm
private class JSONParse extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... args) {
// is this the correct way to get the phoneNumber send in the execute
String phoneNumber = args[0];
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("cel", phoneNumber));
JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
JSONObject android = json.getJSONObject(TAG_OS);
String error = android.optString(TAG_ERROR);
if(Integer.parseInt(error) == 0){
// if the async task returns true contactViewHolder.txtViewPhoneCheck.setText("OK");
// return true;
}
if(Integer.parseInt(error) == 1){
// if the async task returns false contactViewHolder.txtViewPhoneCheck.setText("NOT OK");
// return false;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (cur != null) {
cur.close();
}
}
}
thanks for helping.
You are on the right track with:
new JSONParse().execute(phoneNumber);
Just make sure phoneNumber is a String.
is this the correct way to get the phoneNumber send in the execute
String phoneNumber = args[0];
Yes, that is the correct way. The first and only argument your AsyncTask accepts is phoneNumber and the index of String..args starts at 0
Now, in your onPostExecutemethod, am not conversant with the JSONObject class, but I think if:
if(Integer.parseInt(error) == 0)
and
if(Integer.parseInt(error) == 1){
return true, then you could go ahead to set the edittext as desired?
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();
}
}