Use async task to modify element in a contact listview - android

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?

Related

Passing data from one listview to another

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

Android multiple contacts from groups and images

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();
}
}

BitmapFactory decodeFile FileNotFoundException

I have an app where you can select images from the gallery or Photos folder on the device. The selected file's paths are stored in an Intent so they can be passed around between Activities. I access the paths via intent.getDataString().
Once i have all the selected paths to the images, i store them in an ArrayList and pass that to an ImageAdapter, to display in a ListView.
I'm geting a FileNotFoundException, Has anyone any ideas why?
Thanks in advance
Matt.
import java.util.ArrayList;
import uk.co.mobilewebexpert.infowrapsynclibrary.ApplicationObj;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
public class QueuedImagesActivity extends Activity {
private static final String TAG = QueuedImagesActivity.class.getSimpleName();
private ImageAdapter adapter;
private ListView imageList;
ApplicationObj appObj;
Intent[] photos;
String path;
private ArrayList<String> imagePaths= new ArrayList<String>(); // Edit your code here..
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.image_listview);
appObj = (ApplicationObj) getApplication();
boolean includeBeingProcessed = true;
try {
photos = appObj.getQueuedPhotos(includeBeingProcessed);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i = 0; i < photos.length; i++){
path = photos[i].getDataString();
imagePaths.add(path);
Log.e(TAG, "path in QueuedImagesActivity = " + path);
}
imageList= (ListView) findViewById(R.id.listView1);
adapter= new ImageAdapter(getBaseContext(), imagePaths);
imageList.setAdapter(adapter);
}
}
.
import java.util.ArrayList;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
private static final String TAG = ImageAdapter.class.getSimpleName();
static class RowItemHolder{
ImageView imageView;
}
private Context context;
private ArrayList<String> imagePaths= new ArrayList<String>();
public ImageAdapter(Context baseContext, ArrayList<String> imagePaths) {
// TODO Auto-generated constructor stub
this.context= baseContext;
this.imagePaths= imagePaths;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return imagePaths.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View view;
view= convertView;
RowItemHolder holder = null;
if(view== null){
LayoutInflater in =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = in.inflate(R.layout.image_view, parent, false);
holder= new RowItemHolder();
holder.imageView=(ImageView) view.findViewById(R.id.imageView1);
view.setTag(holder);
} else{
holder = (RowItemHolder) view.getTag();
}
//Edit the code here according to you needs..
//like creating option and converting to Bitmap,
//or you can do this job in the main activity.
//holder.imageView.setImageResource(imagePaths.get(position));
Log.e(TAG, "imagePaths.get(position) = " + imagePaths.get(position));
holder.imageView.setImageBitmap(BitmapFactory.decodeFile(imagePaths.get(position)));
return view;
}
}
.
07-02 07:51:33.941: E/QueuedImagesActivity(22700): path in QueuedImagesActivity = content://media/external/images/media/7496
07-02 07:51:33.951: E/ImageAdapter(22700): imagePaths.get(position) = content://media/external/images/media/7496
07-02 07:51:33.961: E/BitmapFactory(22700): Unable to decode stream: FileNotFoundException
07-02 07:51:33.971: E/ImageAdapter(22700): imagePaths.get(position) = content://media/external/images/media/7496
07-02 07:51:33.971: E/BitmapFactory(22700): Unable to decode stream: FileNotFoundException
07-02 07:51:33.981: E/ImageAdapter(22700): imagePaths.get(position) = content://media/external/images/media/7496
07-02 07:51:33.981: E/BitmapFactory(22700): Unable to decode stream: FileNotFoundException
07-02 07:51:33.991: E/ImageAdapter(22700): imagePaths.get(position) = content://media/external/images/media/7496
07-02 07:51:33.991: E/BitmapFactory(22700): Unable to decode stream: FileNotFoundException
The path you are getting is not real path of the Image it is a Uri.If you want to set it it ImageView set it like
imageView.setImageURI(Uri.parse(imagePaths.get(position)));
or
get the Real path by passing your URI and set it to ImageView
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
For more check here Uri to path conversion
It causes because intent.getDataString() returns the uri string. Use intent.getData().getPath() instead.
Try this way,hope this will help you to solve your problem.
public String getAbsolutePath(Uri uri) {
if(Build.VERSION.SDK_INT >= 19){
String id = uri.getLastPathSegment().split(":")[1];
final String[] imageColumns = {MediaStore.Images.Media.DATA };
final String imageOrderBy = null;
Uri tempUri = getUri();
Cursor imageCursor = getContentResolver().query(tempUri, imageColumns,
MediaStore.Images.Media._ID + "="+id, null, imageOrderBy);
if (imageCursor.moveToFirst()) {
return imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
}else{
return null;
}
}else{
String[] projection = { MediaColumns.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}
Your problem is in appObj.getQueuedPhotos- it isn't returning filenames, its returning URIs, decodeFile expects a path. You can, for this case, do a quick string manipulation and remove the content:/ from the front, but you're better off fixing the URIs in your getQueuedPhotos function
content://media/external/images/media/7496 is not the actual location of the stored file, but just the Uri, hence android can't find the file on the specified path. However, you can use the URI to get the absolute path of the file and use that path when decoding.
Use this method to the get the absolute path :
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
From : https://stackoverflow.com/a/3414749/1239966
Check for the inputstream, you are passing just a URI.
BitmapFactory.decodeFile(imagePaths.get(position));
Hence the file is not found, get the absolute path of the Image and pass it over.

Fetch contact photo in android gives null

I want to fetch the photo of the contact while a user enters number.By using phone number i am getting users name but for image it shows null.
my code is following :
public class NewtempActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageView img = (ImageView) findViewById(R.id.imageView1);
final EditText edit = (EditText) findViewById(R.id.editText1);
TextView txt = (TextView) findViewById(R.id.textView1);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Girish", "Clicked");
String name = getContactNameFromNumber(edit.getText()
.toString(), getApplicationContext());
img.setImageBitmap(BitmapFactory
.decodeFile(ContactsContract.PhoneLookup._ID));
Log.d("Girish",
""
+ (BitmapFactory
.decodeFile(ContactsContract.PhoneLookup._ID)));
Toast.makeText(getApplicationContext(), name, name.length())
.show();
}
});
}
public String getContactNameFromNumber(String number, Context ctx) {
/*
* // define the columns I want the query to return String[] projection
* = new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME,
* ContactsContract.PhoneLookup.NUMBER, };
*/
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(number));
// query time
// Cursor c = ctx.getContentResolver().query( contactUri, projection,
// null,
Cursor c = ctx.getContentResolver().query(contactUri, null, null, null,
null);
// if the query returns 1 or more results
// return the first result
if (c.moveToFirst()) {
String name = c.getString(c
.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
return name;
}
// return the original number if no match was found
return number;
}
public static Bitmap loadContactPhoto(ContentResolver cr, long id) {
Uri uri = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, id);
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(cr, uri);
// InputStream input = ContactsContract.Contacts.Photo
if (input == null) {
return null;
}
return BitmapFactory.decodeStream(input);
}
public InputStream openPhoto(long contactId) {
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,
contactId);
Uri photoUri = Uri.withAppendedPath(contactUri,
Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = getContentResolver().query(photoUri, null, null, null,
null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return new ByteArrayInputStream(data);
}
}
} finally {
cursor.close();
}
return null;
}
}
please suggest me where i am doing wrong.I have added read contact permission also
by going through your code i came to know like You are trying to get the contact name from the number. and using that you want the contact image.. but you never called the functions which you made for the contact pic..:).. so what you can do is take id from the contact number and take photo on that id. so you will get the photo for the number..
package com.android.SampleProject;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import android.app.Activity;
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.provider.ContactsContract.Contacts;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class NewtempActivity extends Activity {
private long id;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageView img = (ImageView) findViewById(R.id.imageView1);
final EditText edit = (EditText) findViewById(R.id.editText1);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("Girish", "Clicked");
String name = getContactNameFromNumber(edit.getText()
.toString(), getApplicationContext());
img.setImageBitmap(BitmapFactory
.decodeFile(ContactsContract.PhoneLookup._ID));
img.setImageBitmap(loadContactPhoto(getContentResolver(), id));
Log.d("Girish",
""
+ (BitmapFactory
.decodeFile(ContactsContract.PhoneLookup._ID)));
Toast.makeText(getApplicationContext(), name, name.length())
.show();
}
});
}
public String getContactNameFromNumber(String number, Context ctx) {
/*
* // define the columns I want the query to return String[] projection
* = new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME,
* ContactsContract.PhoneLookup.NUMBER, };
*/
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(number));
// query time
// Cursor c = ctx.getContentResolver().query( contactUri, projection,
// null,
Cursor c = ctx.getContentResolver().query(contactUri, null, null, null,
null);
// if the query returns 1 or more results
// return the first result
if (c.moveToFirst()) {
String name = c.getString(c
.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
id = c.getLong(c
.getColumnIndex(ContactsContract.PhoneLookup._ID));
return name;
}
// return the original number if no match was found
return number;
}
public static Bitmap loadContactPhoto(ContentResolver cr, long id) {
Uri uri = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, id);
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(cr, uri);
// InputStream input = ContactsContract.Contacts.Photo
if (input == null) {
return null;
}
return BitmapFactory.decodeStream(input);
}
public InputStream openPhoto(long contactId) {
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,
contactId);
Uri photoUri = Uri.withAppendedPath(contactUri,
Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = getContentResolver().query(photoUri, null, null, null,
null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return new ByteArrayInputStream(data);
}
}
} finally {
cursor.close();
}
return null;
}
}

listview items disappearing

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.

Categories

Resources