I have an array list.
1) my first ArrayList<String> some_num = new ArrayList<String>(); which contain the value like this.
[1111111111, 2222222222]
Now I am trying to compare this with my mobile contact like this.
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor people = getActivity().getContentResolver().query(uri, projection, null, null, null);
int indexName = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int j_count=0;
String number;
people.moveToFirst();
do {
String name = people.getString(indexName);
number = people.getString(indexNumber);
j_count++;
// Do work...
} while (people.moveToNext());
for(int j=0;j<=j_count;j++){
if (some_num.contains(number)){
// do nothing
}
else{
Log.e("num",number);
}
}
I am trying to get those number which is not present in my ArrayList from the mobile phone book. I know that in for condition i have to get the value of array but when i try to do this i am not getting the rest of my contact.
Thanks in advance
dont use any other loop to compare the numbers. What's wrong with your code then?
You are comparing your array with number variable which holds the last number reference. because of which your are getting only single result.
if your still want to use your code then create another arrayList in which you store all the number like this:
ArrayList<String> numberList = new ArrayList<String>();
and to add the number in this list use below line before j++;
numberList.add(number);
Now update your last iterator block to work like this:
for(int j=0;j<numberList.siz();j++){
if (some_num.contains(numberList.get(i)){
// do nothing
}
else{
Log.e("num",numberList.get(i));
}
}
To get complete detail of User you can create the Model class which contains the user details like this:
public class UserDetails{
private String userName;
private String userPhone;
private String userImage;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPhone() {
return userPhone;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone;
}
public String getUserImage() {
return userImage;
}
public void setUserImage(String userImage) {
this.userImage = userImage;
}
}
Now you have to use this model in your activity to get and set the details of user:
ArrayList<UserDetails> mUserDetailList = new ArrayList<UserDetails>();
and to get the contacts name use this code:
String name = people.getString(indexName);
now store name and phonenumber like this:
UserDetails mUserModel = new UserDetails();
mUserModel.setUserPhone(number);
mUserModel.setUserName(name);
mUserDetailList.add(mUserModel);
Now to check whether the number exists or not:
for(int j=0;j<mUserDetailList.siz();j++){
if (some_num.contains(mUserDetailList.get(i).getUserPhone()){
// do nothing
}
else{
Log.e("num",numberList.get(i).getUserPhone());
Log.e("name",numberList.get(i).getUserName());
}
}
Hope this will solve your problem.
One ideal solution could be to use a hasp map.
Store the entire contact in a hash map as the key
and check if your list has those number by simply trying to put the value to the hash map.
This will work as hash map wont have duplicatesand when u try to insert a duplicate key you will know that
EDIT
I think your code might work with this fix
String number;
people.moveToFirst();
do {
String name = people.getString(indexName);
number = people.getString(indexNumber);
// for(int j=0;j<=j_count;j++){
if (some_num.contains(number)){
// do nothing
}
else{
Log.e("num",number);
//}
j_count++;
// Do work...
} while (people.moveToNext());
}
try as follows and dont forget to clear the list when ever reusing it
ArrayList<String> list = new ArrayList<String>();
people.moveToFirst();
do {
String name = people.getString(indexName);
number = people.getString(indexNumber);
list.add(number);
j_count++;
// Do work...
} while (people.moveToNext());
for(String str:list)
{
if(yournumber.equalsIgnoreCase(str))
{
//do your stuff
}
}
Related
I want to ask that why it isn't working so I can better help myself next time. How to fix IllegalStateException error in android studio. I'm getting this error while the data is being retrieved from the database. The error I'm getting is an Illegal State Exception as described below.
Fatal Exception: java.lang.IllegalStateException
Couldn't read row 6023, col 0 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
com.navdemo.ui.forms.FormDetailViewModel$10.run
The code, I'm getting this error on is:
private void initScansForForm() {
if (form == null) {
return;
}
final String formId = form.getFormId();
new Thread() {
public void run() {
List<Scan> scans = new ArrayList<>();
Cursor c = db.fetchFormScans(formId);
int id = 0;
while (c.moveToNext()) {
if (!c.isNull(0)){
id = c.getInt(0);
}
else {
Log.d(TAG, "run: "+id);
}
int formId = c.getInt(1);
String scanTime = c.getString(2);
String locationName = c.getString(3);
double latitude = c.getDouble(4);
double longitude = c.getDouble(5);
scans.add(new Scan(id, formId, scanTime, locationName, latitude, longitude));
}
setScans(scans);
}
}.start();
}
public Cursor fetchFormScans(#NonNull String formId) {
return fetchFormScans(Integer.parseInt(formId));
}
public Cursor fetchFormScans(#NonNull String formId) `enter code here`{
return fetchFormScans(Integer.parseInt(formId));
}
Try to check that !cursor.isAfterLast() before doing moveToNext
Kindly make sure that you are getting a number in
String formId = form.getFormId();
As your fetchFormScans() method is parsing string formId to integer so it can be problematic if your formId contains alphabets in it.
I am trying to make simple android app where the user enter his information and then save it in the database and display the user info using listview. I have three java files: DBHelper.java, MainActivity.java and userInfo.java.
(MainActivity.java) is where the user enters his name and email.
(DBHelper.java) is where the database is created to save the user info.
(userInfo.java) is where the user info can be displayed.
in my app I successfully displayed the data from database using textview, and my question is how I can display the data from database using listview.
updated:
this is the getData() method from DBHelper.java file:
public List<Person> getData() {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ID2, KEY_NAME, KEY_EMAIL};
Cursor c = ourDbase.query(TABLE_SCORE, columns, null, null, null, null, null + " DESC");
List<Person> people = new ArrayList<Person>();
int iRow = c.getColumnIndex(KEY_ID);
int iName = c.getColumnIndex(KEY_NAME);
int iEmail= c.getColumnIndex(KEY_EMAIL);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
Person p = new Person();
p.setEmail(c.getString(iEmail));
//set other info, like id, name
people.add(person);
}
return people;
}
here is the Person class:
public class Person {
private int ID;
private String NAME;
private String EMAIL;
public Person()
{
ID=0;
NAME="";
EMAIL="";
}
public Person(String qNAME, int qEMAIL) {
NAME = qNAME;
EMAIL= qEMAIL;
}
public int getID()
{
return ID;
}
public String getNAME() {
return NAME;
}
public int getEMAIL() {
return EMAIL;
}
public void setID(int id)
{
ID=id;
}
public void setNAME(String qNAME) {
NAME = qNAME;
}
public void setSCORE(int qEMAIL) {
EMAIL= qEMAIL;
}
}
and this is the code where I get the data from database and set it in textview from userInfo.java:
DbHelper userInfo = new DbHelper(this);
userInfo .open();
String data = userInfo .getData();
userInfo .close();
tv.setText(data);
how I can display the data from database using listview.
Since you dont provide any code about the listview and its adapter, i assume you dont know where to start.
You should create a listview, either with custom-created adapter or basic adapter (from android). After that, add the data from the database to your listview's adapter and use notifyDataSetChanged() to make sure the data is refreshed on the listview.
Simple tutorial : http://androidexample.com/Create_A_Simple_Listview_-_Android_Example/index.php?view=article_discription&aid=65&aaid=90
In-depth (recommended) tutorial : http://www.vogella.com/tutorials/AndroidListView/article.html
the code idea is originally like this , i want to add the persons from android contacts
public final class People{
public static Person[] PEOPLE = {
new Person(1, R.drawable.person1, "Betty Boo", "is having her hair cut at 6pm"),
new Person(1, R.drawable.person2, "Lisa James", "is going to Avicii live ft.. event"),
};
}
in activity
ViewGroup people = (ViewGroup) findViewById(R.id.people);
for(int i = 0; i < People.PEOPLE.length; i++){
people.addView(People.inflatePersonView(this, people, People.PEOPLE[i]));
}
i want to put the items into array from the query , my attempts were as follows
public final class People{
public static Person[] PEOPLE(ContentResolver cr) {
Person[] PEOPLE = {};
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, "starred=?",
new String[] {"1"}, null);
int i=0;
int contactID;
String contactName;
while (cursor.moveToNext()) {
contactID = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
PEOPLE[i] = new Person(contactID, R.drawable.person1, contactName, contactName);
i++;
}
cursor.close();
return PEOPLE;
}
}
thanks !
An array isn't the most appropriate data structure for this, as it cannot be resized to add new elements (well, it can, but you actually need to create a new array and copy the contents -- definitely not suitable for adding items one by one).
I would suggest using a List<Person> instead (using ArrayList or LinkedList as the actual class). More or less like this:
public static List<Person> PEOPLE(ContentResolver cr) {
ArrayList<Person> people = new ArrayList<Person>();
...
while (cursor.moveToNext()) {
...
people.add(new Person(...);
}
return people;
}
To iterate over a List, you can use a for loop:
for (Person person : People.PEOPLE(cr)) {
... person
or, if you prefer, a more traditional
List<Person> people = People.PEOPLE(cr);
for (int i = 0; i < people.size(); i++) {
Person person = people.get(i);
...
I am using the following, where AuthorName column value i want to find on the basis of AuthorID. catid is an array that contains AuthorID
public Cursor Authorname(String[] catid) {
myDataBase.rawQuery("SELECT AuthorName FROM AUTHOR_NAME WHERE AuthorID = ?",catid);
}
but it return IllegalArgumentException. Can anybody help me to short out this. Thanks in advance.
You can use only one query to get all the users. Here's an example.
private static final String QUERY = "SELECT AuthorName FROM AUTHOR_NAME WHERE AuthorID IN %ids";
public Cursor Authorname(String[] catid) {
// Build the string with all the IDs, e.g. "(1,2,3,4)"
StringBuilder ids = new StringBuilder();
ids.append("(");
for(int i = 0; i < catid.length; i++) {
ids.append(String.valueOf(catid[i]);
if (i < catid.length - 1) {
ids.append(",");
}
}
ids.append(")");
// Use the string with the ids in the query
String finalQuery = QUERY.replaceAll("%ids", ids.toString());
// Execute the query
return myDataBase.rawQuery(finalQuery);
}
Change your query
myDataBase.rawQuery("SELECT AuthorName FROM AUTHOR_NAME WHERE AuthorID = ?",catid);
as below
cursor = myDataBase.query("AUTHOR_NAME",
new String[] {"AuthorName"}, "AuthorID IN(?)", catid, null, null, null);
Try the above Solution hope it works for you.
I'm trying to write an activity that shows the DisplayNames of contacts evolved in SMS conversations.
Unfortunately:
The SMS database doesn't contain the DisplayName
so I used a function that uses the address "phone number" to get the DisplayName
I don't know how to query unique addresses from the SMS database
so I used sorted query, used a loop to find unique DisplayNames, and then put them in an array
If not, is it better to run this process in the background? but how will the activity open if the list is not prepared yet?!
Finally, I used this array in an ArrayAdapter to populate my ListView (pretty much trying to mimic the native Messaging app)
The activity turned out to take a lot of time to open up (around 2-3 seconds, and I don't have much messages)
Is there a way to solve any or both of my problems efficiently?
Here's my code
public class MessagesPicker extends Activity {
Cursor myCursor;
ListView pickerListView;
public static final String MessageAddress = address;
public static final String MessageID = _id;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.picker);
ContentResolver cr = getContentResolver();
myCursor = cr.query(Uri.parse(contentsms), null, null, null, MessageAddress + ASC); //getting sorted data to easy finding uniqueness
/**setting up unique DisplayNames array**/
int allCount = myCursor.getCount(), uniqueCount = 0;
String[] uniqueNames = new String[allCount];
String temp1,temp2;
myCursor.moveToFirst();
temp1 = getContactDiplayNameByAddr();
uniqueNames[uniqueCount++] = temp1;
do {
temp2 = getContactDiplayNameByAddr();
if (temp1.compareTo(temp2) != 0){
uniqueNames[uniqueCount++] = temp2;
temp1 = temp2;
}
}while(myCursor.moveToNext());
String [] valuesArray = new String[uniqueCount]; //filling the array
for (int i = 0 ; i uniqueCount ; i++)
valuesArray[i] = uniqueNames[i];
/**setting up the ListView**/
ArrayAdapterString adapter = new ArrayAdapterString(this, android.R.layout.simple_list_item_multiple_choice, valuesArray);
pickerListView = (ListView)findViewById(R.id.PickerLV); //linking the object to the interface
pickerListView.setAdapter(adapter); //setting the adapter
pickerListView.setItemsCanFocus(false); //allowing to check the checkbox
pickerListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); //allowing multiple choices
}
String getContactDiplayNameByAddr() { //this function returns DisplayName, or if not available, returns the address
String Address = myCursor.getString(myCursor.getColumnIndex(address));
Uri personUri = Uri.withAppendedPath( ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Address);
Cursor cur = getContentResolver().query(personUri,
new String[] {PhoneLookup.DISPLAY_NAME},
null, null, null );
if( cur.moveToFirst() ) {
String DisplayName = cur.getString(cur.getColumnIndex(PhoneLookup.DISPLAY_NAME));
cur.close();
return DisplayName;
}
return Address;
}
}