Search sqlite records and go to specific activity Android - android

Hello I know this is a basic question, but I'm so confused what to do. I have hardcoded my first app. Below is what I've tried:
String Search = SearchAuto.getText().toString();
if(SearchAuto.getText().toString().equals("Chowchow") ||
SearchAuto.getText().toString().equals("Chihuahua")||
SearchAuto.getText().toString().equals("German Shephered")||
SearchAuto.getText().toString().equals("Beagle")||
SearchAuto.getText().toString().equals("Shih tzu")||
SearchAuto.getText().toString().equals("Siberian Husky")||
SearchAuto.getText().toString().equals("Pug")||
SearchAuto.getText().toString().equals("Poodle")||
SearchAuto.getText().toString().equals("Pomeranian")||
SearchAuto.getText().toString().equals("Labrador Retriever")){
Intent myIntent = new Intent(Search.this, Dogs.class);
myIntent.putExtra(strDog, SearchAuto.getText().toString().toLowerCase(Locale.ENGLISH));
startActivity(myIntent);
SearchAuto.setText("");
}
else if(SearchAuto.getText().toString().equals("American Shorthair") ||
SearchAuto.getText().toString().equals("Bengal")||
SearchAuto.getText().toString().equals("Himalayan")||
SearchAuto.getText().toString().equals("Maine Coon")||
SearchAuto.getText().toString().equals("Manx")||
SearchAuto.getText().toString().equals("Persian")||
SearchAuto.getText().toString().equals("Ragdoll")||
SearchAuto.getText().toString().equals("Russian Blue")||
SearchAuto.getText().toString().equals("Siamese")||
SearchAuto.getText().toString().equals("Sphynx")){
Intent myIntent = new Intent(Search.this, Cats.class);
myIntent.putExtra(strCat, SearchAuto.getText().toString().toLowerCase(Locale.ENGLISH));
startActivity(myIntent);
SearchAuto.setText("");
}
But I want my data to be dynamic so I created a database to store my data.
Now my problem is how do I create a query/change the above code to satisfy my needs?
THis is what I've tried so far:
DBHelper.class
public Cursor fetchbByAnimalType(String animalType, String breed) throws SQLException {
Cursor mCursor = null;
if (animalType == null || animalType.length () == 0) {
mCursor = myDataBase.query(DB_TABLE, new String[] { KEY_ID, KEY_BREED },
null, null, null, null, null);
}
else {
mCursor = myDataBase.query(DB_TABLE, new String[] { KEY_ID, KEY_BREED },
KEY_ANIMALTYPE + " like '%" + animalType + "%' AND " + KEY_BREED + breed, null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchbBreedByName(CharSequence breed) throws SQLException {
Cursor mCursor = null;
if (breed == null || breed.length () == 0) {
mCursor = myDataBase.query(DB_TABLE, new String[] { KEY_ID, KEY_ANIMALTYPE, KEY_DESCRIPTION,
KEY_DIET, KEY_SHELTER, KEY_HYGIENE, KEY_MEDICATION, KEY_BREED },
null, null, null, null, null);
}
else {
mCursor = myDataBase.query(DB_TABLE, new String[] { KEY_ID, KEY_ANIMALTYPE, KEY_DESCRIPTION,
KEY_DIET, KEY_SHELTER, KEY_HYGIENE, KEY_MEDICATION, KEY_BREED },
KEY_BREED + " like '%" + breed + "%'", null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
Search.class
public void onClick(View arg0) {
String Search = SearchAuto.getText().toString();
Cursor cursor = dbHelper.fetchbBreedByName(Search);
String strID, strBreed, strAnimalType;
strID = cursor.getString(cursor.getColumnIndexOrThrow("_id"));
strBreed = cursor.getString(cursor.getColumnIndexOrThrow("breed"));
strAnimalType = cursor.getString(cursor.getColumnIndexOrThrow("animaltype"));
Log.d("Search", "Search for " + strBreed + " ID is " + strID);
if(Search.equals(strBreed) || strAnimaltype){ <<---- I don't know what condition I have to put in here!!!!!! I need help
Intent myIntent = new Intent(Search.this, Dogs.class);
myIntent.putExtra(strDog, Search);
startActivity(myIntent);
}
}
I put an indicator to the line that I'm having an issue. Although I haven't run this, I know it will crash. Any ideas how to achieve what I want? I really need help in this. Thanks.

What i would do:
create two ArrayLists, say, DogsList and CatsList, and add the respective objects (to be specific, String) into it.
String[] DogsArray = new String {"Chihuahua", "", "", ...};
ArrayList<String> DogsList = new ArrayList<String>(Arrays.asList(DogsArray));
String[] CatsArray = new String {"American Shorthair", "", "", ...};
ArrayList<String> CatsList = new ArrayList<String>(Arrays.asList(CatsArray));
Then,
if(DogsList.contains(SearchAuto.getText().toString()))
{
Intent myIntent = new Intent(Search.this, Dogs.class);
myIntent.putExtra(strDog, SearchAuto.getText().toString().toLowerCase(Locale.ENGLISH));
startActivity(myIntent);
}
else if(CatsList.contains(SearchAuto.getText().toString()))
{
Intent myIntent = new Intent(Search.this, Cats.class);
myIntent.putExtra(strCat, SearchAuto.getText().toString().toLowerCase(Locale.ENGLISH));
startActivity(myIntent);
}
Hope this thing helps you.

Assuming that the SQLite is working, I guess since you already have strBreed and strAnimalType, you can put it like this
if(strAnimalType.equalsIgnoreCase("cat") { /* or the value to indicate cat */
Intent myIntent = new Intent(Search.this, Cats.class);
myIntent.putExtra(strCat, strBreed);
startActivity(myIntent);
} else if(strAnimalType.equalsIgnoreCase("dog") { /* or the value to indicate dog */
Intent myIntent = new Intent(Search.this, Dogs.class);
myIntent.putExtra(strDog, strBreed);
startActivity(myIntent);
}

Related

How to retrieve company name from the selected contact

Using ContactsContract I am able to retrieve and display selected mobile number and the relevant contact name.
But instead of returning the company name it's returning the mobile number again.
The intent I use to select a specific phone number when there are multiple numbers
Intent calContctPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
calContctPickerIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(calContctPickerIntent, 1);
here is the main code
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (1):
if (resultCode == Activity.RESULT_OK) {
Uri contctDataVar = data.getData();
Cursor contctCursorVar = getContentResolver().query(contctDataVar, null, null, null, null);
if (contctCursorVar.getCount() > 0) {
while (contctCursorVar.moveToNext()) {
String ContctUidVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts._ID));
String ContctNamVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String Companyname = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
Log.i("Names", ContctNamVar);
if (Integer.parseInt(contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// Query phone here. Covered next
String ContctMobVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String Companyname2 = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
mobile.setText(ContctMobVar);
custname.setText(ContctNamVar);
companyname.setText(Companyname2);
Log.i("Number", ContctMobVar);
}
}
}
}
break;
}
}
I need to find a way to retrieve the company name saved under the selected contact.
You may try something like this :
ContentResolver mContentResolver = this.getContentResolver();
Cursor contacts = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
String mContactId = contacts.getString(contacts.getColumnIndex(ContactsContract.Contacts._ID));
String mRawContactId = getRawContactID(mContactId);
String mCompanyName = getCompanyName(mRawContactId);
private String getRawContactID(String contactId) {
String[] projection = new String[]{ContactsContract.RawContacts._ID};
String selection = ContactsContract.RawContacts.CONTACT_ID + "=?";
String[] selectionArgs = new String[]{contactId};
Cursor c = mContentResolver.query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
if (c == null) return null;
int rawContactId = -1;
if (c.moveToFirst()) {
rawContactId = c.getInt(c.getColumnIndex(ContactsContract.RawContacts._ID));
}
c.close();
return String.valueOf(rawContactId);
}
private String getCompanyName(String rawContactId) {
try {
String orgWhere = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{rawContactId,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor cursor = mContentResolver.query(ContactsContract.Data.CONTENT_URI,
null, orgWhere, orgWhereParams, null);
if (cursor == null) return null;
String name = null;
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
}
cursor.close();
return name;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
With the help of the solution provided by #Shiva Snape I was able to solve the problem.
Code for button to call contacts app and select the relevant number
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, 1);
Code to collect Contact Number, Name and company name.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME},
null, null, null);
ContentResolver mContentResolver = this.getContentResolver();
if (c != null && c.moveToFirst()) {
String number = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String name = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String contactId = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String rawContactId = getRawContactId(contactId);
String companyName = getCompanyName(rawContactId);
int type = c.getInt(1);
showSelectedNumber(type, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
private String getCompanyName(String rawContactId) {
try {
String orgWhere = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{rawContactId,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor cursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI,
null, orgWhere, orgWhereParams, null);
if (cursor == null) return null;
String Vname = null;
if (cursor.moveToFirst()) {
Vname = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
}
cursor.close();
return Vname;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private String getRawContactId(String contactId) {
String[] projection = new String[]{ContactsContract.RawContacts._ID};
String selection = ContactsContract.RawContacts.CONTACT_ID + "=?";
String[] selectionArgs = new String[]{contactId};
Cursor c = getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
if (c == null) return null;
int rawContactId = -1;
if (c.moveToFirst()) {
rawContactId = c.getInt(c.getColumnIndex(ContactsContract.RawContacts._ID));
}
c.close();
return String.valueOf(rawContactId);
}
public void showSelectedNumber(int type, String number) {
Toast.makeText(this, type + ": " + number, Toast.LENGTH_LONG).show();
}
}
Thanks to the Stack Overflow community for helping me out. Hope this becomes helpful to others.

Find contact ID by display name returning wrong ID

My code is returning ID = 1367(correct ID is 233). What is wrong? I have working code searching ID by phone number, but I need to change it to searching by display name.
String selection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" like'%" + mStructuredName +"%'";
String[] projection = new String[] { ContactsContract.PhoneLookup._ID};
Cursor mcursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, selection, null, null);
long idPhone = 0;
try {
if (mcursor != null) {
if (mcursor.moveToFirst()) {
idPhone = Long.valueOf(mcursor.getString(0));
}
}
} finally {
if (mcursor != null) {
mcursor.close();
}
}
if (idPhone > 0) {
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setData(ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, idPhone));
startActivity(intent);
}
Searching by phone number (working)
Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(tempPhoneNum));
Cursor mcursor = getContentResolver().query(lookupUri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID}, null, null, null);
long idPhone = 0;
try {
if (mcursor != null) {
if (mcursor.moveToFirst()) {
idPhone = Long.valueOf(mcursor.getString(mcursor.getColumnIndex(ContactsContract.PhoneLookup._ID)));
}
}
} finally {
if (mcursor != null) {
mcursor.close();
}
}
if (idPhone > 0) {
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setData(ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, idPhone));
startActivity(intent);
}
Your code seems too complicated, here is mine:
Cursor contacts_cur = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME +" = ?",
new String[]{name}, null);
contacts_cur.moveToNext();
String id = cursor.getString(cursor.getColumnIndex( ContactsContract.Contacts._ID));
Note that is seems dangerous for me to retrieve the id by name since two contacts can have the same name (but not the same id).

Cannot resolve method 'managedQuery"

I have a stand alone app that pulls up the phone number of a contact and fills it into a text box. This works fine as an activity, but when I put the same code into a fragment, I get an error that it cannot resolve the method 'managedQuerry'. I also get the message for getContentResover().
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
try {
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor cur = managedQuery(contactData, null, null, null, null);
ContentResolver contect_resolver = getContentResolver();
if (cur.moveToFirst()) {
String id = cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String name = "";
String no = "";
Cursor phoneCur = contect_resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
if (phoneCur.moveToFirst()) {
name = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
no = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
Log.e("Phone no & name :***: ", name + " : " + no);
//txt.append(name + " : " + no + "\n");
editPhoneNum.setText(no);
id = null;
name = null;
no = null;
phoneCur = null;
}
contect_resolver = null;
cur = null;
// populateContacts();
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
Log.e("IllegalArgException :: ", e.toString());
} catch (Exception e) {
e.printStackTrace();
Log.e("Error :: ", e.toString());
}
}
If you're Using managedQuery in Fragment, please use getActivity() before managedQuery
Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
I had the same problem as you.
This is a dialog of my project that get contacts information and show them
private void contactsdialog() {
final Dialog dialog = new Dialog(getContext());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.contactsdialog);
ListView contacts_list = (ListView)dialog.findViewById(R.id.listView);
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.PHOTO_ID
};
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
Cursor cursor =dialog.getContext().getContentResolver().query(uri, projection, null, null, sortOrder);
ArrayList<String> columnArray1 = new ArrayList<String>();
ArrayList<String> columnArray2 = new ArrayList<String>();
while (cursor.moveToNext()) {
try {
columnArray2.add(cursor.getString(0));
columnArray1.add(cursor.getString(1));
} catch(Exception e) {
// Log.d("error",e.toString());
}
}
cursor.close();
String[] colStrArr1 = (String[]) columnArray1.toArray(new String[columnArray1.size()]);
String[] colStrArr2 = (String[]) columnArray2.toArray(new String[columnArray1.size()]);
contactadapter adapter = new contactadapter(getActivity(),colStrArr1,colStrArr2);
contacts_list.setAdapter(adapter);
dialog.show();
}
As you can see, I didn't use managedquery, because it's deprecated. Instead I used "getContentResolver().query" that is the same as managedquery. Also you need a dialog name like "dialog in my codes" to bound getContentResolver().query with it (because its not on a activity and my main class is fragment like your case). And sorry for bad English

User login in Sqlite?

I want to use a log in system in Android with only the username. The code below works only for the first row ( For example my database has names : 1- Joseph 2 - Najib , if i input Joseph it works fine, but if i input Najib or some other value that does not exist in my DB the program apparently keeps looping and does not respond..How can I correct this code to return the message ( either the username being in the DB or an invalid username) accordingly? Do I have an error in the while statement?
public void checklogin() {
DatabaseHelper dbh = new DatabaseHelper(LoginActivity.this);
DatabaseAdapter dba = new DatabaseAdapter(LoginActivity.this);
db = dbh.getWritableDatabase();
TextView usernametry = (TextView) findViewById(R.id.usernametry);
String usertry = usernametry.getText().toString();
String[] allColumnsofuserstable = { dba.COLUMN_ID, dba.COLUMN_NAME,
dba.COLUMN_AGE, dba.COLUMN_GENDER, dba.COLUMN_WEIGHT,
dba.COLUMN_HEIGHT, dba.COLUMN_CALORIES };
Log.d("TAG", usertry);
Cursor mCursor = db.query(dba.TABLE_USERS,
new String[] { dba.COLUMN_NAME }, null, null, null, null, null,
mCursor.moveToNext();
while (!mCursor.isAfterLast()) {
String k = mCursor.getString(0);
if (k.equalsIgnoreCase(usertry)) {
Toast.makeText(LoginActivity.this,
"Logged in as " + mCursor.getString(0).toString(),
Toast.LENGTH_LONG).show();
mCursor.moveToNext();
} else
Toast.makeText(LoginActivity.this, "invalid username",
Toast.LENGTH_LONG).show();
}
mCursor.close();
dbh.close();
return;
}
The best would be to modify your query to look for string rather than getting all the results and loop through for a lookup.
Cursor mCursor = db.query(dba.TABLE_USERS,
new String[] { dba.COLUMN_NAME }, dba.COLUMN_NAME + "=?", new String[]{usertry},
null, null, null);
Your loop is broken because you only move the pointer in the cursor (mCursor.moveToNext();) in case that the username is found in the database. Cursor can't move after last item and while (!mCursor.isAfterLast()) never stops.
You need to make sure to always move the cursor. E.g. like so:
Cursor mCursor = db.query(dba.TABLE_USERS,
new String[] { dba.COLUMN_NAME }, null, null, null, null, null,
boolean loggedIn = false;
while (mCursor.moveToNext()) {
String k = mCursor.getString(0);
if (k.equalsIgnoreCase(usertry)) {
Toast.makeText(LoginActivity.this,
"Logged in as " + mCursor.getString(0).toString(),
Toast.LENGTH_LONG).show();
loggedIn = true;
break;
}
}
if (!loggedIn)
Toast.makeText(LoginActivity.this, "invalid username",
Toast.LENGTH_LONG).show();
Or you change your query (see #Waqas) to do the work for you (LIKE ? = equalsIgnoreCase, = ? = equals)
Cursor mCursor = db.query(dba.TABLE_USERS,
new String[] { dba.COLUMN_NAME }, dba.COLUMN_NAME + " LIKE ?", new String[]{usertry},
null, null, null);
if (mCursor.moveToFirst()) {
String k = mCursor.getString(0);
Toast.makeText(LoginActivity.this,
"Logged in as " + mCursor.getString(0).toString(),
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(LoginActivity.this, "invalid username",
Toast.LENGTH_LONG).show();
}

MMS sender address problem

I am trying to get the address of the sender but I run into a little problem. If the person that sends the message is the first person in any of the conversations to send one, the query of the content://mms/inbox returns with zero rows?? but when someone sends any other mms message it will return back with the _id fine and i dont understand why the first one wont work right?
private String checkMmsMessages(Context context){
String address = "address";
Cursor curPdu = context.getContentResolver ().query(Uri.parse("content://mms/inbox"), null, null, null, null);
if(curPdu.moveToNext()){ //first MMS message curPdu.moveToNext() is false
String id = curPdu.getString (curPdu.getColumnIndex ("_id"));
Log.v("MMS", "ID1: " + id.toString());
Uri uriAddr = Uri.parse ("content://mms/" + id + "/addr");
Cursor curAddr = context.getContentResolver().query(uriAddr,null,"type=137",null,null);
if(curAddr.moveToNext()){
address = curAddr.getString (curAddr.getColumnIndex ("address"));
Log.v("MMS", "Address1: " + address.toString());
if(address.contentEquals("insert-address-token")){
Cursor curAddr2 = context.getContentResolver().query(uriAddr,null,"type=151", null,null);
if(curAddr2.moveToNext()){
address = curAddr2.getString(curAddr2.getColumnIndex("address"));
}
}
}
}
Log.v("MMS", address.toString());
return address;
}
Also something else that does not make sense is when when i have the phone plugged into the computer and step through the that section with the debugger, that problem does not happen and it gets the address every time.... it only happens when the phone is not connected, i just dont understand?
The problem was I was checking the database before the message was put into the database so I had to put a delay on the check
I think the issue is you are passing a value for selectionArgs instead of null to the query() method. I am not actually calling the mCursor's moveToNext() method in my code but instead I am implementing this logic in the getView() method of a SimpleCursorAdapter.
Uri uri = Uri.parse("content://mms-sms/conversations/" + mThreadId);
String[] projection = new String[] { "body", "person", "sub",
"subject", "retr_st", "type", "date", "ct_cls", "sub_cs",
"_id", "read", "ct_l", "st", "msg_box", "reply_path_present",
"m_cls", "read_status", "ct_t", "status", "retr_txt_cs",
"d_rpt", "error_code", "m_id", "date_sent", "m_type", "v",
"exp", "pri", "service_center", "address", "rr", "rpt_a",
"resp_txt", "locked", "resp_st", "m_size" };
String sortOrder = "normalized_date";
Cursor mCursor = getActivity().getContentResolver().query(uri,projection, null, null, sortOrder);
String messageAddress;
int type;
while (mCursor.moveToNext()) {
String messageId = mCursor.getString(mCursor.getColumnIndex("_id"));
Uri.Builder builder = Uri.parse("content://mms").buildUpon();
builder.appendPath(messageId).appendPath("addr");
Cursor c = mContext.getContentResolver().query(builder.build(), new String[] {
"*"
}, null, null, null);
while (c.moveToNext()) {
messageAddress = c.getString(c.getColumnIndex("address"));
if (!messageAddress.equals("insert-address-token")) {
type = c.getInt(c.getColumnIndex("type"));
c.moveToLast();
}
}
c.close();
}
try this...
private String getAddressNumber(String id) {
String selectionAdd = new String("msg_id=" + id);
String uriStr = MessageFormat.format("content://mms/{0}/addr", id);
Uri uriAddress = Uri.parse(uriStr);
Cursor cursor = getContentResolver().query(uriAddress, null, selectionAdd, null, null);
String phoneNum = null;
if (cursor.moveToFirst()) {
do {
String number = cursor.getString(cursor.getColumnIndex("address"));
if (number != null) {
boolean isNumberFormat = true;
try {
Long.parseLong(number.replace("-", ""));
phoneNum = number;
} catch (NumberFormatException e) { // ex) "insert-address-token"
// if (phoneNum == null) {
// phoneNum = number;
// }
isNumberFormat = false;
}
if (isNumberFormat)
break;
}
} while (cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
return phoneNum;
}

Categories

Resources