How to use Correct Conditioning? - android

Is this the correct query?
DbFertility info = new DbFertility(this);
info.open();
String name = info.getUserInfo();
info.close();
if(name != null){
Intent i = new Intent(this, Create.class);
startActivity(i);
}else{
Intent i2 = new Intent(this, CalendarMain.class);
startActivity(i2);
}
problem: if the name null i want to direct it create class.. my real problem is even my name is empty or not it always direct me to the CalendarMain.(help)
public String getUserInfo() {
String[] columns = new String[]{KEY_USER_ID, KEY_NAME, KEY_AGE, KEY_STATUS};
Cursor c = getOurDatabase().query(TABLE_USER, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_USER_ID);
int iName = c.getColumnIndex(KEY_NAME);
int iAge c.getColumnIndex(KEY_AGE);
int iStatus = c.getColumnIndex(KEY_STATUS);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iName) + " " + c.getString(iAge) + c.getString(iStatus) + "\n";
}
return result;
}
Save:
public long createUser(String name, String age, String status) {
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_AGE, age);
cv.put(KEY_STATUS, status);
return getOurDatabase().insert(TABLE_USER, null, cv);
}

use TextUtils.isEmpty(name), it returns true if the string is null or if its length is equal to zero.
Intent i = null;
if(!TextUtils.isEmpty(name)) {
i = new Intent(this, Create.class);
} else {
i = new Intent(this, CalendarMain.class);
}
startActivity(i);

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.

How to add data in android sqlite?

I want to add my new values in the previous one at a specific id, but every time when I want to add it created data on a new id rather than added with the previous one.
Here is the method of my databasehelper class:
public boolean addalldata(String value1, String value2, String value3) {
String previous1 = null,previous2 = null,previous3= null;
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
String myquery = "SELECT * FROM student_table WHERE id = 1";
Cursor res = db.rawQuery(myquery, null);
while(res.moveToNext()) {
previous1 = res.getString(1);
previous2 = res.getString(2);
previous3 = res.getString(3);
}
contentValues.put(COL_2, value1 + previous1);
contentValues.put(COL_3, value2 + previous2);
contentValues.put(COL_4, value3 + previous3);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;}
here is the method of mainactivity class
private void AddAllData() {
btnaddall.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDb.addalldata(edit1.getText().toString(),
edit2.getText().toString(),
edit3.getText().toString());
if (isInserted = true)
Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Data not Inserted", Toast.LENGTH_LONG).show();
}
}
);
}
try this:
public boolean addalldata(String value1, String value2, String value3) {
String previous1 = "0",previous2 = "0",previous3= "0";
long result = 0;
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
String myquery = "SELECT * FROM student_table WHERE id = 1";
Cursor res = db.rawQuery(myquery, null);
if(res.getCount()>0){
res.moveToFirst();
previous1 = res.getString(1);
previous2 = res.getString(2);
previous3 = res.getString(3);
try{
contentValues.put(COL_2, Integer.parseInt(value1) + Integer.parseInt(previous1));
contentValues.put(COL_3, Integer.parseInt(value2) + Integer.parseInt(previous2));
contentValues.put(COL_4, Integer.parseInt(value3) + Integer.parseInt(previous3));
result = db.update(TABLE_NAME, contentValues, "id = ?", new String[]{"1"});
}catch(Exception e){
result = -1;
}
if (result == -1)
return false;
else
return true;
}else{
contentValues.put(COL_2, value1);
contentValues.put(COL_3, value2);
contentValues.put(COL_4, value3);
result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
}
if there is no record in the database then insert a new record using db.insert otherwise update the existing record by using db.update
try res.moveToFirst().This will move your cursor to first position so that furthur checking starts from the first row.

rawquery dynamic where clause condition in android?

I'm new to android and using sqlite rawquery dynamic where clause condition for the first time and didn't know how to use it. I want to give dynamic value to where clause to get the listview according to particular "mid". How to provide the mid value from SubjectActivty
Here is my code:
TestTable:
public long insert(String id, String time, int mid, String cmarks, String nmarks,
String questions, String testType, String test,String marks) {
log("insert test : " + test);
ContentValues values = new ContentValues();
values.put(KEY_TESTID, id);
values.put(KEY_MID,mid);
values.put(KEY_TEST, test);
values.put(KEY_TIME, time);
values.put(KEY_CMARK, cmarks);
values.put(KEY_NMARK, nmarks);
values.put(KEY_TESTTYPE, testType);
values.put(KEY_QUESTION, questions);
values.put(KEY_Total_Marks, marks);
return db.insert(TABLE_NAME2, null, values);
}
public ArrayList<NotificationListItem> getAllList(
ArrayList<NotificationListItem> privateArrayList) {
openToRead();
privateArrayList.clear();
Cursor cursor = null;
String sql ="SELECT * FROm test_list WHERE mid=?";
cursor= db.rawQuery(sql, null);
log("getAlllist() cursor : " + cursor.getCount());
if (cursor != null) {
log("getAlllist() cursor not null ");
int index = 0;
cursor.moveToFirst();
while (index < cursor.getCount()) {
NotificationListItem item = new NotificationListItem();
int idIndex = cursor.getColumnIndex(TestTable.KEY_TESTID);
int subid= cursor.getColumnIndex(TestTable.KEY_MID);
int nameIndex = cursor.getColumnIndex(TestTable.KEY_TEST);
int idTime = cursor.getColumnIndex(TestTable.KEY_TIME);
int cMarks = cursor.getColumnIndex(TestTable.KEY_CMARK);
int nMarks = cursor.getColumnIndex(TestTable.KEY_NMARK);
int testTypeIndex = cursor.getColumnIndex(TestTable.KEY_TESTTYPE);
int questions = cursor.getColumnIndex(TestTable.KEY_QUESTION);
item.name = cursor.getString(nameIndex);
item.testID = cursor.getString(idIndex);
item.mid=cursor.getInt(subid);
item.time = cursor.getString(idTime);
item.cmark = cursor.getString(cMarks);
item.nmark = cursor.getString(nMarks);
item.testType = cursor.getString(testTypeIndex);
item.questions = cursor.getString(questions);
index++;
privateArrayList.add(item);
cursor.moveToNext();
}
log(" query(): cursor closing");
cursor.close();
db.close();
db = null;
}
return privateArrayList;
}
SubjectActvity.class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subject);
privateListLV = (ListView) findViewById(R.id.privateListLV);
privatelistTable = new SubjectTable(SubjectActivity.this);
testTableStatic = new StaticTestTable(this);
testTable = new TestTable(SubjectActivity.this);
privatelistTable.openToWrite();
privatelistTable.deleteAll();
privatelistTable.insert(10, "Biology");
privatelistTable.insert(20, "Chemistry");
privatelistTable.insert(30, "English");
privatelistTable.insert(40, "Maths");
privatelistTable.insert(50, "GK");
testTable.openToWrite();
testTable.deleteAll();
testTable.insert("1", "10", 10, "5", "2", "2", "Both", "Anatomy", "10");
testTable.insert("2", "10", 20, "5", "2", "2", "Both", "Paper1", "10");
privateArrayList = new ArrayList<NotificationListItem>();
listAdapter = new SubjectCustomListAdapter(this, privateArrayList,
privatelistTable);
privateListLV.setAdapter(listAdapter);
privateListLV.setOnItemClickListener(new OnItemClickListener() {
#SuppressWarnings("unchecked")
public void onItemClick(AdapterView<?> adapter, View arg1,
int position, long arg3) {
NotificationListItem selection = (NotificationListItem) adapter
.getItemAtPosition(position);
String item = selection.getName();
System.out.println("item" +item);
if (!item.contentEquals(" ")) {
subjectid = privatelistTable.getSinlgeEntry(item);
Log.e("selected Value", " " + subjectid);
Intent testact = new Intent(getApplicationContext(),
TestsActivity.class);
testact.putExtra("subject", item);
testact.putExtra("mid",subjectid);
startActivity(testact);
} else {
return;
}
}
});
}
#Override
protected void onResume() {
super.onResume();
updateList();
}
private void updateList() {
privatelistTable.getAllList(privateArrayList);
listAdapter.notifyDataSetChanged();
}
Do as #Der Golem answer OR another way is
Cursor c =db.rawQuery("SELECT * FROM " + tableName + " where mid=" + mid , null);

Android fetch all contact list (name, email, phone) takes more then a minute for about 700 contacts

Is there any way to shorten this time?
I'm running with the cursor and takes the name, phone numbers and emails
if I remove the phone numbers query from the query loop it ends in 3 seconds
any idea how can I improve that query?
Maybe I'm doing something wrong in my query?
(Obviously I'm doing it async but still... it's a very long time that a user can't wait)
Hope someone can share his thoughts about this
this is my code
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
AddressBookEntity adr = new AddressBookEntity();
String id = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
adr.fullName = name;
Cursor emailCur = cr
.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = ?", new String[] { id },
null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
if (!Utils.IsNullOrEmptyString(email)) {
adr.email = email;
}
}
emailCur.close();
if (Integer
.parseInt(cur.getString(cur
.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);
int phoneIndex = 0;
while (pCur.moveToNext()) {
String number = pCur.getString(pCur
.getColumnIndex(Phone.NUMBER));
String country = Utils.GetCountryFromNumber(
number, app);
number = Utils.GetFullPhoneNumber(number, app);
if (phoneIndex == 0) {
if (!Utils.IsNullOrEmptyString(number)) {
adr.contactAdressBookId = id;
adr.phoneNumber = number;
adr.userInsertedId = app.userCred.userId;
adr.country = country;
myContacts.add(adr);
}
} else {
if (!Utils.IsNullOrEmptyString(number)) {
AddressBookEntity adrMore = new AddressBookEntity();
adrMore.fullName = adrMore.fullName;
adrMore.country = adrMore.country;
adrMore.email = adrMore.email;
adrMore.phoneNumber = number;
adrMore.contactAdressBookId = id;
adrMore.country = country;
myContacts.add(adrMore);
}
}
}
pCur.close();
}
}
cur.close();
with the following code for 59 contacts i got the following results on the emulator:
D ╔══════ query execution stats ═══════
D ║ got 59 contacts
D ║ query took 0.012 s (12 ms)
D ╚════════════════════════════════════
ok, that was the best time, but the average is 25-35 ms (for 59 contacts), add the following code in some onClick callback and run in several times in order to get the average time, in your case you should get 30 * 700 / 59 = ~300-400 ms, not 3 seconds, let alone one minute ;)
it uses Uri set to Contactables.CONTENT_URI added in API level 18 but you can use ContactsContract.Data.CONTENT_URI when building for pre 18 API devices
List<AddressBookContact> list = new LinkedList<AddressBookContact>();
LongSparseArray<AddressBookContact> array = new LongSparseArray<AddressBookContact>();
long start = System.currentTimeMillis();
String[] projection = {
ContactsContract.Data.MIMETYPE,
ContactsContract.Data.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Contactables.DATA,
ContactsContract.CommonDataKinds.Contactables.TYPE,
};
String selection = ContactsContract.Data.MIMETYPE + " in (?, ?)";
String[] selectionArgs = {
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
};
String sortOrder = ContactsContract.Contacts.SORT_KEY_ALTERNATIVE;
Uri uri = ContactsContract.CommonDataKinds.Contactables.CONTENT_URI;
// we could also use Uri uri = ContactsContract.Data.CONTENT_URI;
// ok, let's work...
Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
final int mimeTypeIdx = cursor.getColumnIndex(ContactsContract.Data.MIMETYPE);
final int idIdx = cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID);
final int nameIdx = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
final int dataIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.DATA);
final int typeIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.TYPE);
while (cursor.moveToNext()) {
long id = cursor.getLong(idIdx);
AddressBookContact addressBookContact = array.get(id);
if (addressBookContact == null) {
addressBookContact = new AddressBookContact(id, cursor.getString(nameIdx), getResources());
array.put(id, addressBookContact);
list.add(addressBookContact);
}
int type = cursor.getInt(typeIdx);
String data = cursor.getString(dataIdx);
String mimeType = cursor.getString(mimeTypeIdx);
if (mimeType.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) {
// mimeType == ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE
addressBookContact.addEmail(type, data);
} else {
// mimeType == ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE
addressBookContact.addPhone(type, data);
}
}
long ms = System.currentTimeMillis() - start;
cursor.close();
// done!!! show the results...
int i = 1;
for (AddressBookContact addressBookContact : list) {
Log.d(TAG, "AddressBookContact #" + i++ + ": " + addressBookContact.toString(true));
}
final String cOn = "<b><font color='#ff9900'>";
final String cOff = "</font></b>";
Spanned l1 = Html.fromHtml("got " + cOn + array.size() + cOff + " contacts<br/>");
Spanned l2 = Html.fromHtml("query took " + cOn + ms / 1000f + cOff + " s (" + cOn + ms + cOff + " ms)");
Log.d(TAG, "\n\n╔══════ query execution stats ═══════" );
Log.d(TAG, "║ " + l1);
Log.d(TAG, "║ " + l2);
Log.d(TAG, "╚════════════════════════════════════" );
SpannableStringBuilder msg = new SpannableStringBuilder().append(l1).append(l2);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(this);
tv.setTextSize(20);
tv.setBackgroundColor(0xff000033);
tv.setPadding(24, 8, 24, 24);
tv.setText(msg);
ll.addView(tv);
ListView lv = new ListView(this);
lv.setAdapter(new ArrayAdapter<AddressBookContact>(this, android.R.layout.simple_list_item_1, list));
ll.addView(lv);
new AlertDialog.Builder(this).setView(ll).setPositiveButton("close", null).create().show();
the helper AddressBookContact class:
class AddressBookContact {
private long id;
private Resources res;
private String name;
private LongSparseArray<String> emails;
private LongSparseArray<String> phones;
AddressBookContact(long id, String name, Resources res) {
this.id = id;
this.name = name;
this.res = res;
}
#Override
public String toString() {
return toString(false);
}
public String toString(boolean rich) {
SpannableStringBuilder builder = new SpannableStringBuilder();
if (rich) {
builder.append("id: ").append(Long.toString(id))
.append(", name: ").append("\u001b[1m").append(name).append("\u001b[0m");
} else {
builder.append(name);
}
if (phones != null) {
builder.append("\n\tphones: ");
for (int i = 0; i < phones.size(); i++) {
int type = (int) phones.keyAt(i);
builder.append(ContactsContract.CommonDataKinds.Phone.getTypeLabel(res, type, ""))
.append(": ")
.append(phones.valueAt(i));
if (i + 1 < phones.size()) {
builder.append(", ");
}
}
}
if (emails != null) {
builder.append("\n\temails: ");
for (int i = 0; i < emails.size(); i++) {
int type = (int) emails.keyAt(i);
builder.append(ContactsContract.CommonDataKinds.Email.getTypeLabel(res, type, ""))
.append(": ")
.append(emails.valueAt(i));
if (i + 1 < emails.size()) {
builder.append(", ");
}
}
}
return builder.toString();
}
public void addEmail(int type, String address) {
if (emails == null) {
emails = new LongSparseArray<String>();
}
emails.put(type, address);
}
public void addPhone(int type, String number) {
if (phones == null) {
phones = new LongSparseArray<String>();
}
phones.put(type, number);
}
}
try this code ,use a progress dialouge
public void getAllContacts() {
new AsyncTask<String, String, ArrayList<UserInfo>>() {
ArrayList<UserInfo> infos = new ArrayList<>();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected ArrayList<UserInfo> doInBackground(String... params) {
ContentResolver contactResolver = context.getContentResolver();
Cursor cursor = contactResolver.query(ContactsContract.Contacts.CONTENT_URI, new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.HAS_PHONE_NUMBER }, null, null, null);
if(cursor.getCount()>0)
while ( cursor.moveToNext()) {
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// String photoUri = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI));
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
// String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Log.d("TAG", " Name: " + displayName);
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = contactResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { contactId }, null);
while (pCur.moveToNext())
{
String phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String type = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
String s = (String) ContactsContract.CommonDataKinds.Phone.getTypeLabel(context.getResources(), Integer.parseInt(type), "");
Log.d("TAG", s + " phone: " + phone);
}
pCur.close();
}
Cursor emailCursor = contactResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] { contactId }, null);
while (emailCursor.moveToNext())
{
String phone = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
int type = emailCursor.getInt(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
String s = (String) ContactsContract.CommonDataKinds.Email.getTypeLabel(context.getResources(), type, "");
Log.d("TAG", s + " email: " + phone);
}
emailCursor.close();
} cursor.close();
return null;
}
#Override
protected void onPostExecute(ArrayList<UserInfo> aVoid) {
super.onPostExecute(aVoid);
// EventBus.getDefault().post(aVoid);
}
}.execute();
}
You retrieve all columns in your query:
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
This makes the data processing much slower. If you define an array of columns which you really need to retrieve, it will be much faster.

Search sqlite records and go to specific activity 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);
}

Categories

Resources