how to read the Contact faster? [duplicate] - java

This question already has an answer here:
Reading all contact data
(1 answer)
Closed 5 years ago.
I try to make Contact App and now I try to read the Contacts
I have 450 contacts and its take something like 60 sec to read them all.
I do it with Contact class:
public class Contact {
String name;
public ArrayList<String> PhoneNumber = new ArrayList<>();
public ArrayList<String> Email = new ArrayList<>();
int NumberOfPhones = 0;
int NumberOfMails = 0 ;
}
and I read like this :
tatic final int CODE_FOR_PERMISSION = 123;
List<Contact> ListContact = new ArrayList<Contact>();
Contact TempContact;
String TempName ="";
ArrayList<String> TempPhoneNumber = new ArrayList<>();
public ArrayList<String> TempEmail = new ArrayList<>();
int TempCounter = 0;
private ProgressDialog pDialog;
private Handler updateBarHandler;
ArrayList<String> contactList;
Cursor cursor;
int counter;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_activity);
AskForPermission();
pDialog = new ProgressDialog(this);
pDialog.setMessage("Reading contacts...");
pDialog.setCancelable(false);
pDialog.show();
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();
//init();
//OnAction();
void init(){
textView = (TextView) findViewById(R.id.chekk);
}
void OnAction(){
TempContact.PrintToTextView(textView,ListContact);
}
public void getContacts() {
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);
TempName = 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);
TempPhoneNumber.add(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));
TempEmail.add(email);
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());
TempContact = new Contact(TempName,TempPhoneNumber,TempEmail);
ListContact.add(TempContact);
TempName = "";
TempPhoneNumber.clear();
TempEmail.clear();
}
// Dismiss the progressbar after 500 millisecondds
updateBarHandler.postDelayed(new Runnable() {
#Override
public void run() {
pDialog.cancel();
}
}, 5);
}
}
how I can make the reading from contacts faster?
I have searched in other sutes but I don't know how to do it faster.
it can be done because the default contact app in the phone makes it very fast.

You don't need to query for all contacts + all emails + all phones to display the main contacts list similar to the default contacts app.
You'd probably notice that the main screen of all contacts apps display only names + picture, and not emails or phones.
Just perform the first query in your code to display the list of contacts, and only when the user clicks on one of those contacts, you'll open a new activity with the details of that specific contact only (which is a short query to make)

Related

how to add another column in another spinner of same or other table in android studio

how to add second column value of same or other table in another spinner from sqlite database using button click in android studio
retrievebtn.setOnClickListener(arg0 -> {
// TODO Auto-generated method stub
nos.clear();
names.clear();
//OPEN
db.openDB();
//RETRIEVE
Cursor c = db.getAllValues();
c.moveToFirst();
while(!c.isAfterLast())
{
String no = c.getString(0);
nos.add(no);
String name = c.getString(1);
names.add(name);
c.moveToNext();
}
//CLOSE
c.close();
db.close();
//SET IT TO SPINNER
sp1.setAdapter(adapter);
sp2.setAdapter(adapter);
});
Perhaps consider the following working example.
This consists of 2 spinners and 3 buttons. The buttons controlling from which of the 3 tables the data is extracted for the 2nd spinner.
The trick, as such, used is to use AS to utilise a standard column name, irrespective of the actual column name. The one difference is that this rather than using a normal adapter, it utilises a CursorAdapter (SimpleCursorAdapter as it's quite flexible) and thus you can extract the data directly.
First the SQLite side i.e. the class that extends SQLiteOpenHelper :-
class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "the_database.db";
public static final int DATABASE_VERSION = 1;
public static final String TABLE1_TABLE = "_table1";
public static final String TABLE1_ID_COL = BaseColumns._ID;
public static final String TABLE1_NAME_COL = "_name";
public static final String TABLE1_DESC_COL = "_desc";
private static final String TABLE1_CREATE_SQL =
"CREATE TABLE IF NOT EXISTS " + TABLE1_TABLE + "(" +
TABLE1_ID_COL + " INTEGER PRIMARY KEY" +
"," + TABLE1_NAME_COL + " TEXT UNIQUE" +
"," + TABLE1_DESC_COL + " TEXT " +
");";
public static final String TABLE2_TABLE = "_table2";
public static final String TABLE2_ID_COL = BaseColumns._ID;
public static final String TABLE2_TABLE1_ID_MAP_COL = "_table1_id_map";
public static final String TABLE2_NAME_COL = "_name";
private static final String TABLE2_CREATE_SQL =
"CREATE TABLE IF NOT EXISTS " + TABLE2_TABLE + "(" +
TABLE2_ID_COL + " INTEGER PRIMARY KEY" +
"," + TABLE2_TABLE1_ID_MAP_COL + " INTEGER " +
"," + TABLE2_NAME_COL + " TEXT" +
");";
public static final String TABLE3_TABLE = "_table3";
public static final String TABLE3_ID_COL = BaseColumns._ID;
public static final String TABLE3_TABLE2_ID_MAP_COL = "_table2_id_map";
public static final String TABLE3_NAME_COL = "_name";
private static final String TABLE3_CREATE_SQL =
"CREATE TABLE IF NOT EXISTS " + TABLE3_TABLE +"(" +
TABLE3_ID_COL + " INTEGER PRIMARY KEY" +
"," + TABLE3_TABLE2_ID_MAP_COL + " INTEGER " +
"," + TABLE3_NAME_COL + " TEXT " +
");";
private static volatile DBHelper INSTANCE;
private SQLiteDatabase db;
public static final String SPINNER_COLUMN1 = "_spc1";
public static final String SPINNER_COLUMN2 = "_spc2";
private DBHelper(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);
db = this.getWritableDatabase();
}
public static DBHelper getInstance(Context context) {
if (INSTANCE==null) {
INSTANCE = new DBHelper(context);
}
return INSTANCE;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE1_CREATE_SQL);
db.execSQL(TABLE2_CREATE_SQL);
db.execSQL(TABLE3_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
public long insertTable1Row(String name,String description) {
ContentValues cv = new ContentValues();
cv.put(TABLE1_NAME_COL,name);
cv.put(TABLE1_DESC_COL,description);
return db.insert(TABLE1_TABLE,null,cv);
}
public long insertTable2Row(String name, long table1_id) {
ContentValues cv = new ContentValues();
cv.put(TABLE2_NAME_COL,name);
cv.put(TABLE2_TABLE1_ID_MAP_COL,table1_id);
return db.insert(TABLE2_TABLE,null,cv);
}
public long insertTable3Row(String name, long table2_id) {
ContentValues cv = new ContentValues();
cv.put(TABLE3_NAME_COL,name);
cv.put(TABLE3_TABLE2_ID_MAP_COL,table2_id);
return db.insert(TABLE3_TABLE,null,cv);
}
public Cursor getSpinnerData(String table, long map) {
String[] columns = new String[]{};
String whereClause = "";
String[] whereArgs = new String[]{String.valueOf(map)};
switch (table) {
case TABLE1_TABLE:
columns = new String[]{TABLE1_ID_COL,TABLE1_NAME_COL + " AS " + SPINNER_COLUMN1,TABLE1_DESC_COL + " AS " + SPINNER_COLUMN2};
whereClause = "";
break;
case TABLE2_TABLE:
columns = new String[]{TABLE2_ID_COL ,TABLE2_NAME_COL + " AS " + SPINNER_COLUMN1,"'-' AS " + SPINNER_COLUMN2};
whereClause = TABLE2_TABLE1_ID_MAP_COL + "=?";
break;
case TABLE3_TABLE:
columns = new String[]{TABLE3_ID_COL, TABLE3_NAME_COL + " AS " + SPINNER_COLUMN1,"'~' AS " + SPINNER_COLUMN2};
whereClause = TABLE3_TABLE2_ID_MAP_COL + "=?";
break;
}
if (map < 0) {
whereClause="";
whereArgs = new String[]{};
}
if (columns.length > 0) {
return db.query(table,columns,whereClause,whereArgs,null,null,null);
} else {
return db.query(TABLE1_TABLE,new String[]{"0 AS " + TABLE1_ID_COL + ",'ooops' AS " + SPINNER_COLUMN1,"'ooops' AS " + SPINNER_COLUMN2},null,null,null,null,null,"1");
}
}
}
as said there are three tables
a singleton approach has been utilised for the DBHelper
the most relevant aspect in regards to switching spinner data is the getSpinnerData function, which takes two parameters, the most relevant being the first the tablename which drives the resultant query.
Note the use of BaseColumns._ID ALL Cursor adapters must have a column name _id (which is what BaseColumns._ID resolves to). The column should be an integer value that uniquely identifies the row.
the 2nd parameter caters for the selection of only related data, but a negative is used to ignore this aspect.
The Activity "MainActivity" used to demonstrate is :-
public class MainActivity extends AppCompatActivity {
Button btn1, btn2, btn3;
Spinner sp1,sp2;
String[] spinnerColumns = new String[]{DBHelper.SPINNER_COLUMN1,DBHelper.SPINNER_COLUMN2};
SimpleCursorAdapter sca1,sca2;
String sp1_table_name = DBHelper.TABLE1_TABLE;
String sp2_table_name = DBHelper.TABLE2_TABLE;
Cursor csr1, csr2;
DBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = this.findViewById(R.id.button1);
btn2 = this.findViewById(R.id.button2);
btn3 = this.findViewById(R.id.button3);
sp1 = this.findViewById(R.id.spinner1);
sp2 = this.findViewById(R.id.spinner2);
dbHelper = DBHelper.getInstance(this);
Cursor test4Data = dbHelper.getWritableDatabase().query(DBHelper.TABLE1_TABLE,null,null,null,null,null,null, "1");
if (test4Data.getCount() < 1) {
addSomeData();
}
test4Data.close();
sp1_table_name = DBHelper.TABLE1_TABLE;
sp2_table_name = DBHelper.TABLE2_TABLE;
setUpButtons();
setOrRefreshSpinner1();
setOrRefreshSpinner2();
}
void setUpButtons() {
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sp2_table_name = DBHelper.TABLE1_TABLE;
setOrRefreshSpinner2();
setOrRefreshSpinner1();
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sp2_table_name = DBHelper.TABLE2_TABLE;
setOrRefreshSpinner2();
setOrRefreshSpinner1();
}
});
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sp2_table_name = DBHelper.TABLE3_TABLE;
setOrRefreshSpinner2();
setOrRefreshSpinner1();
}
});
}
void setOrRefreshSpinner1() {
csr1 = dbHelper.getSpinnerData(sp1_table_name,-1);
if (sca1==null) {
sca1 = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
csr1,
spinnerColumns,
new int[]{android.R.id.text1, android.R.id.text2},0
);
sp1.setAdapter(sca1);
} else {
sca1.swapCursor(csr1);
}
}
void setOrRefreshSpinner2() {
csr2 = dbHelper.getSpinnerData(sp2_table_name,-1);
if (sca2==null) {
sca2 = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
csr2,
spinnerColumns,
new int[]{android.R.id.text1, android.R.id.text2},0
);
sp2.setAdapter(sca2);
} else {
sca2.swapCursor(csr2);
}
}
private void addSomeData() {
long n1 = dbHelper.insertTable1Row("NAME001","The first name.");
long n2 = dbHelper.insertTable1Row("NAME002","The second name.");
long n3 = dbHelper.insertTable1Row("NAME003","The third name");
long t2n1 = dbHelper.insertTable2Row("CHILDNAME001",n1);
long t2n2 = dbHelper.insertTable2Row("CHILDNAME002",n2);
long t2n3 = dbHelper.insertTable2Row("CHILDNAME003", n3);
dbHelper.insertTable3Row("GRANDCHILDNAME001",t2n1);
dbHelper.insertTable3Row("GRANDCHILDNAME002",t2n1);
dbHelper.insertTable3Row("GRANDCHILDNAME003",t2n1);
dbHelper.insertTable3Row("GRANDCHILDNAME004",t2n2);
dbHelper.insertTable3Row("GRANDCHILDNAME005",t2n3);
}
}
Result
The above when run starts of with :-
With the first spinner dropdown shown :-
With the second spinner dropdown shown :-
If Button1 is clicked then both spinners (i.e. spinner2 has been changed to select data from Table1 rather than Table2) show data from Table1 (useless but for demonstration) :-
If Button3 is clicked then data from Table3 is displayed in the second spinner:-
Clicking Button2 shows data from Table2.
Of course the principle could be applied in many different ways.
My adapters were not set so I made below changes and got expected result.
// RETRIEVE
retrievebtn.setOnClickListener(arg0 -> {
// TODO Auto-generated method stub
nos.clear();
names.clear();
//OPEN
db.openDB();
//RETRIEVE
Cursor c = db.getAllValues();
c.moveToFirst();
while(!c.isAfterLast())
{
String no = c.getString(0);
nos.add(no);
String name = c.getString(1);
names.add(name);
c.moveToNext();
}
//CLOSE
c.close();
db.close();
//SET IT TO SPINNER
ArrayAdapter<String> adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, nos);
ArrayAdapter<String> adapter2 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, names);
sp1.setAdapter(adapter1);
sp2.setAdapter(adapter2);
});

How to retrieve contact number from phonebook in android?

/This is my override function. It works fine when I just retrieve names from the phone book. But the app crashes the moment i try to retrieve a contact number./
#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 contactData = data.getData();
Cursor c = getContentResolver().query(contactData, null, null, null, null);
if(c.moveToFirst()) {
String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
String name = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if (hasPhone.equalsIgnoreCase("1"))
{
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
phones.moveToFirst();
String cNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Toast.makeText(getApplicationContext(), cNumber, Toast.LENGTH_SHORT).show();
}
}
c.close();
}
break;
}
}
First of all, create POJO class.
public class ContactEntity {
String name;
String number;
String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
Now, to retrieve contacts.
ArrayList<ContactEntity> contactList = new ArrayList<>();
contactList = getcontactList();
public ArrayList<ContactEntity> getcontactList() //This Context parameter is nothing but your Activity class's Context
{
ArrayList<ContactEntity> allContacts = new ArrayList<>();
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
Integer contactsCount = cursor.getCount(); // get how many contacts you have in your contacts list
if (contactsCount > 0) {
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
//the below cursor will give you details for multiple contacts
Cursor pCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
// continue till this cursor reaches to all phone numbers which are associated with a contact in the contact list
while (pCursor.moveToNext()) {
int phoneType = pCursor.getInt(pCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
//String isStarred = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.STARRED));
String phoneNo = pCursor.getString(pCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//you will get all phone numbers according to it's type as below switch case.
ContactEntity entity = new ContactEntity();
entity.setName(contactName);
entity.setNumber(phoneNo);
allContacts.add(entity);
//Log.e will print all contacts according to contact types. Here you go.
switch (phoneType) {
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
Log.e(contactName + ": TYPE_MOBILE", " " + phoneNo);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
Log.e(contactName + ": TYPE_HOME", " " + phoneNo);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
Log.e(contactName + ": TYPE_WORK", " " + phoneNo);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE:
Log.e(contactName + ": TYPE_WORK_MOBILE", " " + phoneNo);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_OTHER:
Log.e(contactName + ": TYPE_OTHER", " " + phoneNo);
break;
default:
break;
}
}
pCursor.close();
}
}
cursor.close();
}
return allContacts;
}
I don't know what is your problem, but I have a code for getting phone number you can have a try:
public String getPhone(Context context, String contactID) {
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
// Query and loop for every phone number of the contact
Cursor phoneCursor = context.getContentResolver().query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[]{contactID}, null);
String phoneNo = "";
if(phoneCursor != null) {
while (phoneCursor.moveToNext()) {
phoneNo = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
}
phoneCursor.close();
}
return phoneNo;
}

why function are not getting executed in sequence?

Here is the problem...I have three different functions namely syncFirebaseContacts(); getAllContacts(); and compareContactUpdateList();. These function's execution order is very important because first function's output becomes input of another. As I have said I have placed these three function in my onCreate() method in sequence as described.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datasource = new AdoreDataSource(this);
datasource.open();
syncFirebaseContacts();
getAllContacts();
compareContactUpdateList();
.......
But while debugging I found out that although pointer points syncFirebaseContacts() first but the code of getAllContact() is executed first and then compareContactUpdateList() is executed and after that syncFirebaseContacts() code is executed.
private void getAllContacts() {
String contactNumber;
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()) {
contactNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//All Mapping Stuff to be done here..
contactNumber = contactNumber.replaceAll("\\s+","");
contactNumber = contactNumber.trim();
lst2.add(contactNumber);
break;
}
pCur.close();
}
} while (cursor.moveToNext());
}
}
private void syncFirebaseContacts() {
Firebase userLocationRef = new Firebase(Constants.FIREBASE_URL_USERS);
userLocationRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dsp : dataSnapshot.getChildren()){
datasource.createContact(String.valueOf(dsp.getKey()));
lst1.add(String.valueOf(dsp.getKey()));
Log.e("Hello", String.valueOf(dsp.getKey()));
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.e("Could not process", "Sorry");
}
});
}
private void compareContactsUpdateList() {
ArrayList<String> commonOfAll = new ArrayList<String>(lst1);
commonOfAll.retainAll(lst2);
ContentResolver cr = this.getContentResolver(); //Activity/Application android.content.Context
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
final ArrayList<ContactsList> contacts = new ArrayList<ContactsList>();
//List<SyncContacts> syncContacts = datasource.getAllContacts();
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 nameOfContact = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String contactNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactNumber = contactNumber.replaceAll("\\s+","");
contactNumber = contactNumber.trim();
Log.d("Name ", nameOfContact + contactNumber);
for(int j =0; j < commonOfAll.size(); j++){
if(contactNumber.equals(commonOfAll)){
Log.d("Name ", nameOfContact);
contacts.add(new ContactsList(contactNumber, nameOfContact, R.mipmap.ic_launcher));
}
}
break;
}
pCur.close();
}
} while (cursor.moveToNext());
}
final ContactsAdapterTwo contactsAdapterTwo = new ContactsAdapterTwo(this, contacts);
final GridView gridView = (GridView) findViewById(R.id.grid);
gridView.post(new Runnable() {
public void run() {
gridView.setAdapter(contactsAdapterTwo);
}
});
}
As my problem is that I want to compare two lists which is done in compareContactsUpdateList() by the line
ArrayList<String> commonOfAll = new ArrayList<String>(lst1);
commonOfAll.retainAll(lst2); as I found out that lst1 is always empty because syncFirebaseContacts() 's code is excuted at last
My applogies if my question length is too long or if my problem is trivial. But it is a big problem for me coz I am new to coding :-) please help me....Anyways Thanx in advance...

Can't add more than one record, ID not autoincrimenting

I'm trying to add site details to a database and then after I insert a row, output the result to a TextView. The record is being inserted into the database because it's being shown in a TextView, however I can only insert one record and I'm not sure why. I'm been using the tutorial here and modifying it to meet my needs.
Here is my DBAdapter:
public class DBAdapter {
// ///////////////////////////////////////////////////////////////////
// Constants & Data
// ///////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_PORT = "port";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_ADDRESS = 2;
public static final int COL_USERNAME = 3;
public static final int COL_PASSWORD = 4;
public static final int COL_PORT = 5;
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_NAME,
KEY_ADDRESS, KEY_USERNAME, KEY_PASSWORD, KEY_PORT };
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "Sites";
public static final String DATABASE_TABLE = "SiteTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL = "create table "
+ DATABASE_TABLE
+ " ("
+ KEY_ROWID
+ " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a
// value).
// NOTE: All must be comma separated (end of line!) Last one must
// have NO comma!!
+ KEY_NAME + " string not null, " + KEY_ADDRESS
+ " string not null, " + KEY_USERNAME + " string not null, "
+ KEY_PASSWORD + " string not null, " + KEY_PORT
+ " integer not null"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
// ///////////////////////////////////////////////////////////////////
// Public methods:
// ///////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String name, String address, String username,
String password, int port) {
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_ADDRESS, address);
initialValues.put(KEY_USERNAME, username);
initialValues.put(KEY_PASSWORD, password);
initialValues.put(KEY_PORT, port);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String name, String address,
String username, String password, String port) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, name);
newValues.put(KEY_ADDRESS, address);
newValues.put(KEY_USERNAME, username);
// newValues.put(KEY_PASSWORD, password);
// newValues.put(KEY_PORT, port);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
// ///////////////////////////////////////////////////////////////////
// Private Helper Classes:
// ///////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading. Used to
* handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version "
+ oldVersion + " to " + newVersion
+ ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
I'm querying the database here:
public class FTPConnector extends Activity {
DBAdapter myDb;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.ftp);
status = (TextView) findViewById(R.id.status);
editAddress = (EditText) findViewById(R.id.editAddress);
editUser = (EditText) findViewById(R.id.editUsername);
editPassword = (EditText) findViewById(R.id.editPassword);
addsiteBtn = (Button) findViewById(R.id.addsiteBtn);
addsiteBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
siteManager();
}
});
openDb();
}
private void openDb() {
myDb = new DBAdapter(this);
myDb.open();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
closeDb();
}
private void closeDb() {
myDb.close();
}
//Where the insertRecord() happens
public void siteManager() {
final AlertDialog customDialog = new AlertDialog.Builder(this).create();
LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.site_manager, null);
final EditText tmpname = (EditText) view
.findViewById(R.id.dialogsitename);
final EditText tmpaddress = (EditText) view
.findViewById(R.id.dialogaddress);
final EditText tmpuser = (EditText) view
.findViewById(R.id.dialogusername);
final EditText tmppass = (EditText) view
.findViewById(R.id.dialogpassword);
final EditText tmpport = (EditText) view.findViewById(R.id.dialogport);
final TextView tmpsites = (TextView) view.findViewById(R.id.textView6);
final CheckBox tmppassive = (CheckBox) view
.findViewById(R.id.dialogpassive);
final Button tmpclose = (Button) view.findViewById(R.id.closeBtn);
final Button tmptestBtn = (Button) view.findViewById(R.id.testBtn);
final Button tmpsavetsite = (Button) view.findViewById(R.id.saveSite);
customDialog.setView(tmpclose);
customDialog.setView(tmptestBtn);
customDialog.setView(tmpname);
customDialog.setView(tmpaddress);
customDialog.setView(tmpuser);
customDialog.setView(tmppass);
customDialog.setView(tmpport);
customDialog.setView(tmppassive);
customDialog.setView(tmpsavetsite);
customDialog.setView(tmpsites);
tmpclose.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
}
});
tmptestBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = tmpname.getText().toString();
_address = tmpaddress.getText().toString();
_user = tmpuser.getText().toString();
_pass = tmppass.getText().toString();
_port = Integer.parseInt(tmpport.getText().toString());
_passive = false;
if (tmppassive.isChecked()) {
_passive = true;
}
boolean status = ftpConnect(_address, _user, _pass, _port);
if (status == true) {
Toast.makeText(FTPConnector.this, "Connection Succesful",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(FTPConnector.this,
"Connection Failed:" + status, Toast.LENGTH_LONG)
.show();
}
}
});
tmpsavetsite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
tmpsites.setText("");
String msg = "!";
_name = tmpname.getText().toString();
_address = tmpaddress.getText().toString();
_user = tmpuser.getText().toString();
_pass = tmppass.getText().toString();
_port = Integer.parseInt(tmpport.getText().toString());
long newId = myDb.insertRow(_name, _address, _user, _pass, 21);
Cursor c = myDb.getAllRows();
if (c.moveToFirst()) {
int id = c.getInt(0);
String _name = c.getString(1);
String _address = c.getString(2);
String _user = c.getString(3);
String _pass = c.getString(4);
int _port = c.getInt(5);
msg += "id=" + id + "\n";
msg += ", name=" + _name + "\n";
msg += ", address=" + _address + "\n";
msg += ", username=" + _user + "\n";
msg += ", password=" + _pass + "\n";
msg += ", port=" + _port + "\n";
while (c.moveToNext());
}
c.close();
// displayText(msg);
tmpsites.setText(msg);
}
});
customDialog.setView(view);
customDialog.show();
}
Why can't I add more than one record?
In here :
while (c.moveToNext()); //<<<
currently you are not using any loop like do-while for iterating through cursor(you forget to add do block with while). get all data from cursor as using for loop:
//more to the first row
c.moveToFirst();
//iterate over rows
for (int i = 0; i < c.getCount(); i++) {
// get all data here from current row..
//move to the next row
c.moveToNext();
}
//close the cursor
c.close();
and using do-while you can get all values from current row as:
c.moveToFirst(); //more to the first row
do {
// get all data here from current row..
} while (c.moveToNext());

Populate Android Listview from SQLite database

I've been trying to populate an Android Listview from a SQLite database using the code below. I have successfully done this from an array inside the same class. But in this case I'm attempting to populate it from a String array I have returned from another class. I'm new to this so am possibly doing this completely wrong. If anyone could look at the code and advise to what I'm doing wrong that'd be brilliant.
Any help would be really appreciated with this as I'm under serious pressure to get it finished, Thanks!
LoginActivity Class
public class LoginActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
final EditText txtUserName = (EditText)findViewById(R.id.txtUsername);
final EditText txtPassword = (EditText)findViewById(R.id.txtPassword);
Button btnLogin = (Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String username = txtUserName.getText().toString();
String password = txtPassword.getText().toString();
try{
if(username.length() > 0 && password.length() >0)
{
DBUserAdapter dbUser = new DBUserAdapter(LoginActivity.this);
dbUser.open();
int UID = dbUser.Login(username, password);
if(UID != -1)
{
// TEST
//int UID = dbUser.getUserID(username, password);
//getSitesByClientname(UID);
// END TEST
// MY TEST CODE TO CHANGE ACTIVITY TO CLIENT SITES
Intent myIntent = new Intent(LoginActivity.this, ClientSites.class);
//Intent myIntent = new Intent(getApplicationContext(), ClientSites.class);
myIntent.putExtra("userID", UID);
startActivity(myIntent);
//finish();
// END MY TEST CODE
//Cursor UserID = dbUser.getUserID();
Toast.makeText(LoginActivity.this,"Successfully Logged In", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(LoginActivity.this,"Invalid Username/Password", Toast.LENGTH_LONG).show();
}
dbUser.close();
}
}catch(Exception e)
{
Toast.makeText(LoginActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
}
Method from DBHelper Class to return String Array
public String[] getSitesByClientname(String id) {
String[] args={id};
//return db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
// loop through all rows and adding to array
int count;
count = myCursor.getCount();
final String[] results = new String[count];
results[0] = new String();
int i = 0;
try{
if (myCursor.moveToFirst()) {
do {
results[i] = myCursor.getString(myCursor.getColumnIndex("client_sitename"));
} while (myCursor.moveToNext());
}
}finally{
myCursor.close();
}
db.close();
// return results array
return results;
ClientSites Class
public class ClientSites extends ListActivity {
public final static String ID_EXTRA="com.example.loginfromlocal._ID";
private DBUserAdapter dbHelper = null;
//private Cursor ourCursor = null;
private ArrayAdapter<String> adapter=null;
//#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
public void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.client_sites);
Intent i = getIntent();
String uID = String.valueOf(i.getIntExtra("userID", 0));
//int uID = i.getIntExtra("userID", 0);
//ListView myListView = (ListView)findViewById(R.id.myListView);
dbHelper = new DBUserAdapter(this);
dbHelper.createDatabase();
//dbHelper.openDataBase();
dbHelper.open();
String[] results = dbHelper.getSitesByClientname(uID);
//setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results));
//adapter = new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results);
setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.layout.client_sites, results));
//ListView myListView = (ListView)findViewById(R.id.myListView);
ListView listView = getListView();
listView.setTextFilterEnabled(true);
//#SuppressWarnings("deprecation")
//SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null);
//CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0);
//adapter = new Adapter(ourCursor);
//Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show();
//myListView.setAdapter(adapter);
//myListView.setOnItemClickListener(onListClick);
}
catch (Exception e)
{
Log.e("ERROR", "XXERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
}
Any help with this would be great, Thanks!
Create own project with few activities. Start working with sqlite database
Create new application. Create login activity and DB helper. Trying to upload dada from DB. Reseach and development
Here is an example how to work with SQLite DB.
public class DBHelper extends SQLiteOpenHelper {
private static DBHelper instance;
private static final String DATABASE_NAME = "UserClientBase";
private static final int DATABASE_VERSION = 1;
public static interface USER extends BaseColumns {
String TABLE_NAME = "userTable";
String NAME = "userName";
String PASSWORD = "userPassword";
}
public static interface CLIENT extends BaseColumns {
String TABLE_NAME = "clientTable";
String NAME = "clientName";
String USER_ID = "userId";
}
private static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS ";
private static final String DROP_TABLE = "DROP TABLE IF EXISTS ";
private static final String UNIQUE = "UNIQUE ON CONFLICT ABORT";
private static final String CREATE_TABLE_USER = CREATE_TABLE + USER.TABLE_NAME + " (" + USER._ID
+ " INTEGER PRIMARY KEY, " + USER.NAME + " TEXT " + UNIQUE + ", " + USER.PASSWORD + " TEXT);";
private static final String CREATE_TABLE_CLIENT = CREATE_TABLE + CLIENT.TABLE_NAME + " (" + CLIENT._ID
+ " INTEGER PRIMARY KEY, " + CLIENT.NAME + " TEXT UNIQUE, " + CLIENT.USER_ID + " INTEGER);";
private DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static DBHelper getInstance(Context context) {
if (instance == null) {
instance = new DBHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_USER);
db.execSQL(CREATE_TABLE_CLIENT);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE + USER.TABLE_NAME);
db.execSQL(DROP_TABLE + CLIENT.TABLE_NAME);
onCreate(db);
}
public long createUser(String newUserName, String newUserPassword) {
ContentValues values = new ContentValues();
values.put(USER.NAME, newUserName);
values.put(USER.PASSWORD, newUserPassword);
return getWritableDatabase().insert(USER.TABLE_NAME, null, values);
}
public long createClient(long userId, String newClientName) {
ContentValues values = new ContentValues();
values.put(CLIENT.USER_ID, userId);
values.put(CLIENT.NAME, newClientName);
return getWritableDatabase().insert(CLIENT.TABLE_NAME, null, values);
}
public boolean isCorrectLoginPassword(String login, String password) {
Cursor userListCursor = getReadableDatabase().rawQuery(
"SELECT * FROM " + USER.TABLE_NAME + " WHERE " + USER.NAME + " =? AND " + USER.PASSWORD
+ " =?", new String[] { login, password });
if ((userListCursor != null) && (userListCursor.getCount() > 0)) {
return true;
} else {
return false;
}
}
public Cursor getUserClientList(String userName) {
Cursor userClientList = getReadableDatabase().rawQuery(
"SELECT * FROM " + CLIENT.TABLE_NAME + " INNER JOIN " + USER.TABLE_NAME
+ " ON " + CLIENT.USER_ID + " = " + USER.TABLE_NAME + "." + USER._ID + " WHERE "
+ USER.NAME + " =?", new String[] { userName });
return userClientList;
}
}
Example of login button click listener.
String login = loginEdt.getText().toString();
String password = passwordEdt.getText().toString();
boolean loginSuccess = databaseHelper.isCorrectLoginPassword(login, password);
if(loginSuccess) {
Intent clientListIntent = new Intent(LoginActivity.this, ClientListActivity.class);
clientListIntent.putExtra(ClientListActivity.EXTRAS_LOGIN, login);
startActivity(clientListIntent);
} else {
Toast.makeText(LoginActivity.this, "Incorrect login/password", Toast.LENGTH_SHORT).show();
}
And example of listview with data from sql:
clientLv= (ListView)findViewById(R.id.listClient);
login = getIntent().getExtras().getString(EXTRAS_LOGIN);
dbHelper = DBHelper.getInstance(this);
Cursor clientList = dbHelper.getUserClientList(login);
adapter = new SimpleCursorAdapter(this, R.layout.row_client, clientList, new String[]{DBHelper.CLIENT.NAME}, new int[]{R.id.txtClientName} , SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
clientLv.setAdapter(adapter);

Categories