I'm trying to write an activity that shows the DisplayNames of contacts evolved in SMS conversations.
Unfortunately:
The SMS database doesn't contain the DisplayName
so I used a function that uses the address "phone number" to get the DisplayName
I don't know how to query unique addresses from the SMS database
so I used sorted query, used a loop to find unique DisplayNames, and then put them in an array
If not, is it better to run this process in the background? but how will the activity open if the list is not prepared yet?!
Finally, I used this array in an ArrayAdapter to populate my ListView (pretty much trying to mimic the native Messaging app)
The activity turned out to take a lot of time to open up (around 2-3 seconds, and I don't have much messages)
Is there a way to solve any or both of my problems efficiently?
Here's my code
public class MessagesPicker extends Activity {
Cursor myCursor;
ListView pickerListView;
public static final String MessageAddress = address;
public static final String MessageID = _id;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.picker);
ContentResolver cr = getContentResolver();
myCursor = cr.query(Uri.parse(contentsms), null, null, null, MessageAddress + ASC); //getting sorted data to easy finding uniqueness
/**setting up unique DisplayNames array**/
int allCount = myCursor.getCount(), uniqueCount = 0;
String[] uniqueNames = new String[allCount];
String temp1,temp2;
myCursor.moveToFirst();
temp1 = getContactDiplayNameByAddr();
uniqueNames[uniqueCount++] = temp1;
do {
temp2 = getContactDiplayNameByAddr();
if (temp1.compareTo(temp2) != 0){
uniqueNames[uniqueCount++] = temp2;
temp1 = temp2;
}
}while(myCursor.moveToNext());
String [] valuesArray = new String[uniqueCount]; //filling the array
for (int i = 0 ; i uniqueCount ; i++)
valuesArray[i] = uniqueNames[i];
/**setting up the ListView**/
ArrayAdapterString adapter = new ArrayAdapterString(this, android.R.layout.simple_list_item_multiple_choice, valuesArray);
pickerListView = (ListView)findViewById(R.id.PickerLV); //linking the object to the interface
pickerListView.setAdapter(adapter); //setting the adapter
pickerListView.setItemsCanFocus(false); //allowing to check the checkbox
pickerListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); //allowing multiple choices
}
String getContactDiplayNameByAddr() { //this function returns DisplayName, or if not available, returns the address
String Address = myCursor.getString(myCursor.getColumnIndex(address));
Uri personUri = Uri.withAppendedPath( ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Address);
Cursor cur = getContentResolver().query(personUri,
new String[] {PhoneLookup.DISPLAY_NAME},
null, null, null );
if( cur.moveToFirst() ) {
String DisplayName = cur.getString(cur.getColumnIndex(PhoneLookup.DISPLAY_NAME));
cur.close();
return DisplayName;
}
return Address;
}
}
Related
I develop simple sms/mms client. With sms everything work good, but with mms I have problem related to address field in conversation.
I have next method to load conversations. There are last sms and mms.
public static List<Conversation> getConversations(Context c) {
List<Conversation> conversations = new ArrayList<>();
Conversation conversation;
Uri uri = Uri.parse("content://mms-sms/conversations/");
Cursor cursor = c.getContentResolver().query(uri, null, null, null, "normalized_date DESC");
if (cursor.moveToFirst()) {
for (int i = 0; i < cursor.getCount(); i++) {
conversation = new Conversation();
conversation.setId(cursor.getString(cursor.getColumnIndexOrThrow("_id")));
conversation.setThreadID(cursor.getString(cursor.getColumnIndexOrThrow("thread_id")));
conversation.setDate(new Date(Long.valueOf(cursor.getString(cursor.getColumnIndexOrThrow("date")))));
conversation.setReadType(ReadType.values()[Integer.parseInt(cursor.getString(cursor.getColumnIndexOrThrow("read")))]);
String type = cursor.getString(cursor.getColumnIndexOrThrow("type"));
if (isSMS(type)) {
conversation.setBody(cursor.getString(cursor.getColumnIndexOrThrow("body")));
conversation.setNumber(cursor.getString(cursor.getColumnIndexOrThrow("address")));
conversation.setMessageFromType(MessageFromType.values()[Integer.parseInt(type) - 1]);
} else {
Map<String, String> mmsContent = getMMSByID(c, conversation.getId());
conversation.setBody(mmsContent.get("body"));
conversation.setNumber(mmsContent.get("address"));
}
conversations.add(conversation);
cursor.moveToNext();
}
}
cursor.close();
return conversations;
}
The problem is that when I sent mms, my number was put to address field of conversation. With sms everything is okay. So after that I don't know who is my opponent in chat.
Also I load mms number in the next way
private String getNumber(Context c, String mmsdid) {
String add = "";
final String[] projection = new String[]{"address", "contact_id"};
Uri.Builder builder = Uri.parse("content://mms").buildUpon();
builder.appendPath(String.valueOf(mmsid)).appendPath("addr");
Cursor cursor = c.getContentResolver().query(
builder.build(),
projection,
null,
null, null);
if (cursor.moveToFirst()) {
add = cursor.getString(cursor.getColumnIndex("address"));
}
return add;
}
Maybe someone have the same problem? Or have any suggestions how to solve it?
The answer was pretty easy, hope it may help someone. Everything is okay except one part. In selection parameter I should add
"from=151"
or
"from="+PduHeaders.TO
So code will look like this:
private static String getNumber(Context c, String id) {
String add = "";
final String[] projection = new String[]{"address"};
Uri.Builder builder = Uri.parse("content://mms").buildUpon();
builder.appendPath(String.valueOf(id)).appendPath("addr");
Cursor cursor = c.getContentResolver().query(
builder.build(),
projection,
"type="+PduHeaders.TO,
null, null);
if (cursor.moveToFirst()) {
add = cursor.getString(cursor.getColumnIndex("address"));
}
cursor.close();
return add;
}
Am trying to use the ContactsProvider with my AutoCompleteTextview using a method that fetches the data (name and phone number) and stores them in a list. As expected, this method will always take time to complete as am calling the method in the onCreateView method of my Fragment class.
This is the method:
...
ArrayList<String> phoneValues;
ArrayList<String> nameValues;
...
private void readContactData() {
try {
/*********** Reading Contacts Name And Number **********/
String phoneNumber = "";
ContentResolver contentResolver = getActivity()
.getContentResolver();
//Query to get contact name
Cursor cursor = contentResolver
.query(ContactsContract.Contacts.CONTENT_URI,
null,
null,
null,
null);
// If data data found in contacts
if (cursor.getCount() > 0) {
int k=0;
String name = "";
while (cursor.moveToNext())
{
String id = cursor
.getString(cursor
.getColumnIndex(ContactsContract.Contacts._ID));
name = cursor
.getString(cursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//Check contact have phone number
if (Integer
.parseInt(cursor
.getString(cursor
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
//Create query to get phone number by contact id
Cursor pCur = contentResolver
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?",
new String[] { id },
null);
int j=0;
while (pCur
.moveToNext())
{
// Sometimes get multiple data
if(j==0)
{
// Get Phone number
phoneNumber =""+pCur.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// Add contacts names to adapter
autocompleteAdapter.add(name);
// Add ArrayList names to adapter
phoneValues.add(phoneNumber.toString());
nameValues.add(name.toString());
j++;
k++;
}
} // End while loop
pCur.close();
} // End if
} // End while loop
} // End Cursor value check
cursor.close();
} catch (Exception e) {
Log.i("AutocompleteContacts","Exception : "+ e);
}
}
Am sure there is a better way to accomplish this, but this method works and the suggestions are presented when I type into the AutocompleteTextview. Am just worried about the time it takes. How can I accomplish this without populating an ArrayList?
I have looked at this question: Getting name and email from contact list is very slow and applied the suggestions in the answer to my code, but now nothing is suggested when I type.How can I improve the performance of my current code?
This is how i have implemented AutoCompleteTextView and it works fine for me ..
final AutoCompleteTextView act=(AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);
ArrayList<String> alContacts = new ArrayList<String>();
ArrayList<String> alNames= new ArrayList<String>();
ContentResolver cr = this.getContentResolver(); //Activity/Application android.content.Context
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if(cursor.moveToFirst())
{
do
{
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
if(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",new String[]{ id }, null);
while (pCur.moveToNext())
{
String contactNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String contactName=pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
alNames.add(contactName);
alContacts.add(contactNumber);
break;
}
pCur.close();
}
} while (cursor.moveToNext()) ;
}
String[] array=new String[alNames.size()];
array=(String[]) alNames.toArray(array);
ArrayAdapter<String> myArr= new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,array);
act.setAdapter(myArr);
act.setThreshold(1);
I got rid of the slow response by placing the method inside an AsynTask.
public class AutocompleteAsyncTask extends AsyncTask<Void, Void, Void> {
public Void doInBackground(Void...params) {
try {
/*********** Reading Contacts Name And Number **********/
String phoneNumber = "";
ContentResolver contentResolver = getActivity()
.getContentResolver();
//Query to get contact name
Cursor cursor = contentResolver
.query(ContactsContract.Contacts.CONTENT_URI,
null,
null,
null,
null);
// If data data found in contacts
if (cursor.getCount() > 0) {
int k=0;
String name = "";
while (cursor.moveToNext())
{
//...Rest of the same code as above
and then calling this in my onCreateView():
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
new AutocompleteAsyncTask().execute();
return rootView;
}
Now the task of inflating my view and fetching the data are separated into two different threads.
The CursorLoader option mentioned by Eugen Pechanec is kinda the best option, so I'll update this answer with that option when I can.
I have class called unviersityClient and method name `getallstudent,but how to include them in cursor to get results displayed
this is in mainactivity
public class MainActivity extends ActionBarActivity {
private TextView tv;
private Button bt;
private Context mycontext;
Cursor c;
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.textView1);
bt=(Button)findViewById(R.id.button1);
mycontext=this.getApplication();
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// universityClient.addStudents(mycontext, "christy");
// universityClient.addStudents(mycontext, "joe");
universityClient.getAllStudents(mycontext);
c.moveToFirst();
while(!c.isAfterLast()){
String dir =c.getString(c.getColumnIndex("name"));
tv.setText("Name : "+dir);
c.moveToNext();
}
and this is in .java created by json. it's already created the db
public static Cursor getAllStudents(Context c) {
ContentResolver cr = c.getContentResolver();
String[] result_columns = new String[]{
universityDB.STUDENTS__ID_COLUMN,
universityDB.STUDENTS_NAME_COLUMN,
};
String where = null;
String whereArgs[] = null;
String order = null;
Cursor resultCursor = cr.query(university.STUDENTS_URI, result_columns, where, whereArgs, order);
return resultCursor;
}
if you have all the students in a database you can use this to get all the names and then send them to a variable
String SELECT_QUERY = "SELECT * FROM Tutores t1 INNER JOIN Tutorados t2 ON t1._id = t2.id_tutor and t1._id = " + ET1.getText().toString().trim();
cursor = db.rawQuery(SELECT_QUERY, null);
if (cursor.getCount() != 0) {
if (cursor.moveToFirst()) {
do {
C1 = cursor.getString(cursor
.getColumnIndex("_id"));
C2 = cursor.getString(cursor
.getColumnIndex("name"));
Fin += C1 + "-" + C2 + "\n";
} while (cursor.moveToNext());
}
}
cursor.close();
Fin is a String and you can get all the names or whatever you want from the columns with the getColumnIndex("nameOfTheColumn") and send "Fin" to a textview or something like that
hope that helps!, see ya
Cant understand why you want to put json data in cursor while json parsing is the best way to do the same. If your priority is to bring data somewhere else and fetch one by one using loop, you can use arraylist/hashmap like collection objects. If you have many fields in one json object, you can create a class having those fields and make an arraylist of that having type of class and store data in that. Like this:
1. Fetch single json object at a time, fetch values of fields.
2. create class object by passing those values in constructor.
3. Create arraylist of that class type.
4. put class objects in that arraylist one by one and fetch as well.
ArrayList<Person> person = new ArrayList<Person>();
Person newPerson = new Person("balvier", "27", "Male");
person.add(newPerson);
Person newPersonAnother = new Person("Adel", "20", "FeMale");
person.add(newPersonAnother);
I am trying to display the contents of my mysqlite database into a listview,
I am able to get the contents and display them in a textview, but for some
reason I can't add the details to an arraylist ? I am not too sure what am doing
wrong. I have looked for multiple solutions but none of them seem to work, am getting an error
Android.database.CursorIndexOutOfBoundsExecption: Index requested -1
Here is what I currently have:
OnCreate:
ArrayAdapter<Contact> currentContactsAdapter = new ContactArrayAdapter();
ListView lvcontacts = (ListView) findViewById(R.id.lvContacts);
lvcontacts.setAdapter(currentContactsAdapter);
tdb = new TestDBOpenHelper(this, "contact.db", null, 1);
sdb = tdb.getWritableDatabase();
new MyContacts().execute();
ListView Adapter:
private class ContactArrayAdapter extends ArrayAdapter<Contact>{
public ContactArrayAdapter(){
super(MainActivity.this, R.layout.listviewitem, addedContacts);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if(itemView == null){
itemView = getLayoutInflater().inflate(R.layout.listviewitem, parent, false);
}
Contact currentContact = addedContacts.get(position);
TextView name = (TextView) itemView.findViewById(R.id.tvNameitem);
name.setText(currentContact.getName());
TextView phone = (TextView) itemView.findViewById(R.id.tvPhoneitem);
phone.setText(currentContact.getPhone());
TextView email = (TextView) itemView.findViewById(R.id.tvEmailitem);
email.setText(currentContact.getEmail());
return itemView;
}
}
GetContacts:
class MyContacts extends AsyncTask<String, String, String> {
List<Contact> retrievedContacts = new ArrayList<Contact>();
protected String doInBackground(String... args) {
String cname;
String cphone;
String cemail;
// name of the table to query
String table_name = "contact";
// the columns that we wish to retrieve from the tables
String[] columns = {"FIRST_NAME", "PHONE", "EMAIL"};
// where clause of the query. DO NOT WRITE WHERE IN THIS
String where = null;
// arguments to provide to the where clause
String where_args[] = null;
// group by clause of the query. DO NOT WRITE GROUP BY IN THIS
String group_by = null;
// having clause of the query. DO NOT WRITE HAVING IN THIS
String having = null;
// order by clause of the query. DO NOT WRITE ORDER BY IN THIS
String order_by = null;
// run the query. this will give us a cursor into the database
// that will enable us to change the table row that we are working with
Cursor c = sdb.query(table_name, columns, where, where_args, group_by,
having, order_by);
for(int i = 0; i < c.getCount(); i++) {
cname = c.getString(c.getColumnIndex("FIRST_NAME"));
cphone = c.getString(c.getColumnIndex("PHONE"));
cemail = c.getString(c.getColumnIndex("EMAIL"));
c.moveToNext();
retrievedContacts.add(new Contact(cname,cphone,cemail));
}
return null;
}
//Update Contact list when response from server is received
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
for(Contact contact: retrievedContacts)
addedContacts.add(contact);
}
}
It seems that your table "contact" doesn't have the exact structure you are trying to read.
Android.database.CursorIndexOutOfBoundsExecption: Index requested -1
This means that one of these column names is not part of it.
c.getColumnIndex("FIRST_NAME")
c.getColumnIndex("PHONE")
c.getColumnIndex("EMAIL")
So one of them return -1 instead of the index because they not exist in the table.
EDIT:
Then the for loop may be faulty. I suggest to use something like:
if (c != null ) {
if (c.moveToFirst()) { // Always move at the first item
do {
cname = c.getString(c.getColumnIndex("FIRST_NAME"));
cphone = c.getString(c.getColumnIndex("PHONE"));
cemail = c.getString(c.getColumnIndex("EMAIL"));
retrievedContacts.add(new Contact(cname, cphone, cemail));
} while (c.moveToNext());
}
}
c.close(); // always close when done!
I have an application where I want to use the values returned from an SQL query against a database in my application. I want to use attach these values to a uri that links to a script on remote host. I am doing a call to the method to retrieve the values, after which I will now extract them. The issue is that I am facing a challenge in going about this. I know a bit of php and what I want in android is done like this in php:
....(preceding code)...$row['email'];
and I can now assign a variable e.g. $email=$row['email'];
How can I do this in android?
I don't want a cursor returned, just the values of the columns as strings.
Below is my code (I will need help to retrieve the password column)
public String[] selectAll()
{
Cursor cursor = db.query(DB_TABLE_NAME, new String[] { "email","password"},null, null, null, null,null);
if(cursor.getCount() >0)
{
String[] str = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext())
{
str[i] = cursor.getString(cursor.getColumnIndex("email"));
i++;
}
return str;
}
else
{
return new String[] {};
}
}
I need help on inserting the "password" column so that it will be returned with the email.
try this way
String[][] str = new String[cursor.getCount()][cursor.getColumnCount()];
while (cursor.moveToNext())
{
for(int j=0;j<cursor.getColumnCount();j++)
str[i][j] = cursor.getString(j); /// may be this column start with the 1 not with the 0
i++;
}
you need to store this in two dimenstion array for row wise and column wise
but if this will give only one result everytime
String[] str = new String[cursor.getColumnCount()]; // here you have pass the total column value
while (cursor.moveToNext())
{
str[0] = cursor.getString(cursor.getColumnIndex("email"));
str[1] = cursor.getString(cursor.getColumnIndex("password"));
}
You should change your design like this
public Cursor selectAll() {
Cursor cursor = db.query(DB_TABLE_NAME, new String[] { "email","password"},null, null, null, null,null);
return cursor;
}
and use the selectAll function like this
Cursor cursor=selectAll();
String[] mail = new String[cursor.getCount()];
String[] pass = new String[cursor.getCount()];
int i=0;
while (cursor.moveToNext())
{
mail[i] = cursor.getString(cursor.getColumnIndex("email"));
pass[i] = cursor.getString(cursor.getColumnIndex("password"));
i++;
}