Can't add items from database to list - java

i am trying to add some items from database to my list but when i run the application i see that the list is empty.
this is what i did to add items to a list
car_size = dbHelper.getSize("cars"); // getSize is a method that count items in database
Random random = new Random();
int cars_random = random.nextInt(car_size);
List<String> myList = dbHelper.read_added_names("cars"); // and this line should add items from database to the list
if(myList!= null && myList.size() > 0) {
textView.setText(myList.get(truth_random));
}else {
Toast.makeText(activity.this, "" + myList.size(), Toast.LENGTH_SHORT).show();
} // here i can see that the size of my list is 0 and it's empty
I'm sure the methode that should read database (here i named it read_aded_names) works fine
public List<String> read_added_names (String subject){
String selectQuery;
List<String> list = new ArrayList<String>();
if (subject.equals("*")) {
selectQuery = "SELECT * FROM " + TABLE_NAME1;
}else {
selectQuery = "SELECT * FROM " + TABLE_NAME1 + " WHERE " + COLUMN_SUBJECT + " = '" + subject+" '";
}
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(1));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return list;
}

Query contains space after subject variable making it "cars " instead of "cars". This can be the issue.

Related

Android studio SQL - How to return data in a string array

I have an SQL method here. I would like to return the data in a String[] array.
How do I do that exactly?
Thank you!
public String[] getLikedSongs() {
SQLiteDatabase db = this.getReadableDatabase();
String[] LikeSong;
Cursor cursor = db.rawQuery(" SELECT " + COL_4 + " FROM " + Table_Name + " WHERE " + COL_4 + " IS NOT NULL", null);
while (cursor.moveToNext()) {
String note = cursor.getString(0);
}
cursor.close();
db.close();
return LikeSong;
}
You must define the array's length and this can be done only after the Cursor fetches all the rows. Then set its length to the nimber of rows of the Cursor.
Then inside the while loop set the items of the array:
public String[] getLikedSongs() {
String[] LikeSong = null;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT " + COL_4 + " FROM " + Table_Name + " WHERE " + COL_4 + " IS NOT NULL", null);
if (cursor.getCount() > 0) {
LikeSong = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext()) {
LikeSong[i] = cursor.getString(0);
i++;
}
}
cursor.close();
db.close();
return LikeSong;
}

SQLite - How to add an order by to this query that searches from an image bucket

Currently I have a query retrieves images from my bucket in MediaStore and it's in ascending order (the oldest posts appear first). How do I modify my query so that it displays the newest images first?
String[] PROJECTION_BUCKET = {
MediaStore.Images.ImageColumns.BUCKET_ID,
MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME,
MediaStore.Images.ImageColumns.DATE_TAKEN,
MediaStore.Images.ImageColumns.DATA};
Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
//Not sure how to modify query here
Cursor cur = getContentResolver().query(images, PROJECTION_BUCKET,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME + " like ? ",
new String[] {"%Download%"} , null);
Log.i("ListingImages"," query count=" + cur.getCount());
if (cur.moveToFirst()) {
String bucket;
String date;
String data;
int bucketColumn = cur.getColumnIndex(
MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
int dateColumn = cur.getColumnIndex(
MediaStore.Images.Media.DATE_TAKEN);
int dataColumn = cur.getColumnIndex(
MediaStore.Images.Media.DATA);
do {
bucket = cur.getString(bucketColumn);
date = cur.getString(dateColumn);
data = cur.getString(dataColumn);
Log.i("ListingImages", " bucket=" + bucket
+ " date_taken=" + date
+ " _data=" + data);
} while (cur.moveToNext());
}
You will have to use the last argument of the query() method which is the sortOrder.
So instead of null pass the column followed by DESC to sort descending:
Cursor cur = getContentResolver().query(
images,
PROJECTION_BUCKET,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME + " like ? ",
new String[] {"%Download%"},
MediaStore.Images.Media.DATE_TAKEN + " DESC"
);

how to get all entries of today date?

hi i m fetching the all entries of today date i write the query for that but i did not get the correct entries. please solve my issue .below i write my code.thank you.
public ArrayList<groups> fetchByTodayDate(){
String selectQuery = "SELECT * FROM " + DatabaseHelper.TABLE + " WHERE "+ DatabaseHelper.DATETIME + "<=date('now')";
Cursor cursor = database.rawQuery(selectQuery,null);
ArrayList<groups> all = new ArrayList<groups>();
if (cursor != null && cursor.moveToFirst()) {
do {
groups data = new groups();
smsdata.setMsgtext(cursor.getString(cursor.getColumnIndex(DatabaseHelper.TEXTMSG)));
smsdata.setSmsId(cursor.getString(cursor.getColumnIndex(DatabaseHelper._ID)));
all.add(data);
} while (cursor.moveToNext());
}
cursor.close();
return all;
}
("SELECT * FROM " + table_name + " WHERE " + KEY_DATE + "='" + date + "'", null);
Try this solution for today's entries:-
String selectQuery = "SELECT * FROM " + DatabaseHelper.TABLE + " WHERE date(datetime("+ DatabaseHelper.DATETIME+"/1000, 'unixepoch','localtime'))=date('now')";
Try this
public ArrayList<groups> fetchByTodayDate()
{
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<groups> all = new ArrayList<>();
String selectQuery = "SELECT * FROM " + DatabaseHelper.TABLE;
Cursor cursor = db.rawQuery(selectQuery,null);
cursor.moveToFirst ();
while (!cursor.isAfterLast())
{
all.add(new groups (
cursor.getString(cursor.getColumnIndex(DatabaseHelper.TEXTMSG)),
cursor.getString(cursor.getColumnIndex(DatabaseHelper._ID))
));
cursor.moveToNext ();
}
cursor.close();
db.close();
return all;
}

Obtain matching contact email and phone from android phone

I have managed to extract contact details from the phone by using ContactContract example I found, but I noticed that most of the people on my phone has a unique id key associated to their emails and phone numbers separately. For example, Alan's contact detail is split up as following when I extract it out from database even though they are for the same person:
key name email phone
20121 Alan alan#gmail.com null
20133 Alan null 04xxxxxxxx
So how does the phone manage the association with all these different keys in the contact (I assume there must be a separate table for it)? Is there any way to obtain this association? Because I can not just try match the name as people can have exactly the same name, you have to keep them separated as how they are stored on your phone contact.
(Or the messed up situation is due to all apps are able to save contact related details into the same database on the phone?)
My code looks like following (I forgot where I get this code from, but getDetailedContactList function is returning a list of contact of the above problem):
public static String CONTACT_ID_URI = ContactsContract.Contacts._ID;
public static String DATA_CONTACT_ID_URI = ContactsContract.Data.CONTACT_ID;
public static String MIMETYPE_URI = ContactsContract.Data.MIMETYPE;
public static String EMAIL_URI = ContactsContract.CommonDataKinds.Email.DATA;
public static String PHONE_URI = ContactsContract.CommonDataKinds.Phone.DATA;
public static String NAME_URI = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) ? ContactsContract.Data.DISPLAY_NAME_PRIMARY : ContactsContract.Data.DISPLAY_NAME;
public static String PICTURE_URI = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) ? ContactsContract.Contacts.PHOTO_THUMBNAIL_URI : ContactsContract.Contacts.PHOTO_ID;
public static String MAIL_TYPE = ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE;
public static String PHONE_TYPE = ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE;
public Cursor getContactCursor(String stringQuery, String sortOrder) {
Log.i(TAG, "+++++++++++++++++++++++++++++++++++++++++++++++++++");
Log.e(TAG, "ContactCursor search has started...");
Long t0 = System.currentTimeMillis();
Uri CONTENT_URI;
if (stringQuery == null)
CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
else
CONTENT_URI = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI, Uri.encode(stringQuery));
String[] PROJECTION = new String[]{
CONTACT_ID_URI,
NAME_URI,
PICTURE_URI
};
String SELECTION = NAME_URI + " NOT LIKE ?";
String[] SELECTION_ARGS = new String[]{"%" + "#" + "%"};
Cursor cursor = getContentResolver().query(CONTENT_URI, PROJECTION, SELECTION, SELECTION_ARGS, sortOrder);
Long t1 = System.currentTimeMillis();
Log.e(TAG, "ContactCursor finished in " + (t1 - t0) / 1000 + " secs");
Log.e(TAG, "ContactCursor found " + cursor.getCount() + " contacts");
Log.i(TAG, "+++++++++++++++++++++++++++++++++++++++++++++++++++");
return cursor;
}
public Cursor getContactDetailsCursor() {
Log.i(TAG, "+++++++++++++++++++++++++++++++++++++++++++++++++++");
Log.e(TAG, "ContactDetailsCursor search has started...");
Long t0 = System.currentTimeMillis();
String[] PROJECTION = new String[]{
DATA_CONTACT_ID_URI,
MIMETYPE_URI,
EMAIL_URI,
PHONE_URI
};
String SELECTION = NAME_URI + " NOT LIKE ?" + " AND " + "(" + MIMETYPE_URI + "=? " + " OR " + MIMETYPE_URI + "=? " + ")";
String[] SELECTION_ARGS = new String[]{"%" + "#" + "%", ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE};
Cursor cursor = getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
PROJECTION,
SELECTION,
SELECTION_ARGS,
null);
Long t1 = System.currentTimeMillis();
Log.e(TAG, "ContactDetailsCursor finished in " + (t1 - t0) / 1000 + " secs");
Log.e(TAG, "ContactDetailsCursor found " + cursor.getCount() + " contacts");
Log.i(TAG, "+++++++++++++++++++++++++++++++++++++++++++++++++++");
return cursor;
}
public List<ContactViewModel> getDetailedContactList(String queryString) {
/**
* First we fetch the contacts name and picture uri in alphabetical order for
* display purpose and store these data in HashMap.
*/
Cursor contactCursor = getContactCursor(queryString, NAME_URI);
if(contactCursor.getCount() == 0){
contactCursor.close();
return new ArrayList<>();
}
List<Integer> contactIds = new ArrayList<>();
if (contactCursor.moveToFirst()) {
do {
contactIds.add(contactCursor.getInt(contactCursor.getColumnIndex(CONTACT_ID_URI)));
} while (contactCursor.moveToNext());
}
HashMap<Integer, String> nameMap = new HashMap<>();
HashMap<Integer, String> pictureMap = new HashMap<>();
int idIdx = contactCursor.getColumnIndex(CONTACT_ID_URI);
int nameIdx = contactCursor.getColumnIndex(NAME_URI);
int pictureIdx = contactCursor.getColumnIndex(PICTURE_URI);
if (contactCursor.moveToFirst()) {
do {
nameMap.put(contactCursor.getInt(idIdx), contactCursor.getString(nameIdx));
pictureMap.put(contactCursor.getInt(idIdx), contactCursor.getString(pictureIdx));
} while (contactCursor.moveToNext());
}
/**
* Then we get the remaining contact information. Here email and phone
*/
Cursor detailsCursor = getContactDetailsCursor();
HashMap<Integer, String> emailMap = new HashMap<>();
HashMap<Integer, String> phoneMap = new HashMap<>();
idIdx = detailsCursor.getColumnIndex(DATA_CONTACT_ID_URI);
int mimeIdx = detailsCursor.getColumnIndex(MIMETYPE_URI);
int mailIdx = detailsCursor.getColumnIndex(EMAIL_URI);
int phoneIdx = detailsCursor.getColumnIndex(PHONE_URI);
String mailString;
String phoneString;
if (detailsCursor.moveToFirst()) {
do {
/**
* We forget all details which are not correlated with the contact list
*/
if (!contactIds.contains(detailsCursor.getInt(idIdx))) {
continue;
}
if(detailsCursor.getString(mimeIdx).equals(MAIL_TYPE)){
mailString = detailsCursor.getString(mailIdx);
/**
* We remove all double contact having the same email address
*/
if(!emailMap.containsValue(mailString.toLowerCase()))
emailMap.put(detailsCursor.getInt(idIdx), mailString.toLowerCase());
} else {
phoneString = detailsCursor.getString(phoneIdx);
phoneMap.put(detailsCursor.getInt(idIdx), phoneString);
}
} while (detailsCursor.moveToNext());
}
contactCursor.close();
detailsCursor.close();
/**
* Finally the contact list is build up
*/
List<ContactViewModel> contacts = new ArrayList<>();
Set<Integer> emailsKeySet = emailMap.keySet();
Set<Integer> phoneKeySet = phoneMap.keySet();
for (Integer key : contactIds) {
if( (!emailsKeySet.contains(key) && !phoneKeySet.contains(key))
|| (emailMap.get(key) == null && phoneMap.get(key) == null)
|| mContactDB.isContactExisted(key))
{
continue;
}
contacts.add(new ContactViewModel(key, nameMap.get(key), emailMap.get(key)));
}
return contacts;
}
Try below code to fetch contact number of specific person.
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(Phone.CONTENT_URI, null, Phone.DISPLAY_NAME + "=?", new String[]{contactName}, null);
if(cursor.getCount() > 0){
cursor.moveToFirst();
do {
String number = cursor.getString(mCursor.getColumnIndex(Phone.NUMBER));
}while (cursor.moveToNext() );
}
Android recommends using content resolvers and content providers to provide nicely packaged data between applications. You should probably not go messing around with the database itself, and it was clearly not designed with that in mind (as your experience demonstrates).
Instead, you should use the content resolver to query the Android ContactsContract to find what you need. There is a class called ContactsContract.Contacts that sounds like the entry point for what you need. Each record returned by a query to the class represents a single contact.
See the Content Providers Developer Guide for further details.

retrieve multiple rows form android sqlite

I am going to fetch some rows with specific tag in android Sqlite.
The problems are
I got 15 with cursor.getCount(); but 13 rows retrieved.
the 13 rows just repeat last row data
here is my code
public ArrayList<HashMap<String, String>> getTodo(String tag) {
ArrayList<HashMap<String,String>> arList = new ArrayList<HashMap<String,String>>();
HashMap<String, String> todo = new HashMap<String, String>();
String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE "
+ COLUMN_TAG + " = ?";
String[] args={tag};
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, args);
// Move to first row
cursor.moveToFirst();
System.out.println(cursor.getCount());
if (cursor.getCount() > 0) {
do {
todo.put(COLUMN_ID, cursor.getString(cursor.getColumnIndex(COLUMN_ID)));
todo.put(COLUMN_FROM, cursor.getString(cursor.getColumnIndex(COLUMN_FROM)));
todo.put(COLUMN_TO, cursor.getString(cursor.getColumnIndex(COLUMN_TO)));
todo.put(COLUMN_TITLE, cursor.getString(cursor.getColumnIndex(COLUMN_TITLE)));
todo.put(COLUMN_TAG, cursor.getString(cursor.getColumnIndex(COLUMN_TAG)));
arList.add(todo);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return todo
return arList;
}
Please help. Thanks
You are using the same todo object for all rows, so you end up with lots of references to the same object.
Create a new one for each row in the loop:
Cursor cursor = db.rawQuery(selectQuery, args);
try {
while (cursor.moveToNext()) {
HashMap<String, String> todo = new HashMap<String, String>();
todo.put(...);
...
arList.add(todo);
}
finally {
cursor.close();
}
It's better to make the todo's you want to acquire into objects
public class Todo {
public String id, from, to, title, tag;
//setters and getters (not necessary)
}
public ArrayList<MyData> getTodo(String tag) {
ArrayList<MyData> arList = new ArrayList<MyData>();
String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE "
+ COLUMN_TAG + " = ?";
String[] args={tag};
try {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, args);
// Move to first row
if (!cursor.moveToFirst())
return arList;
do {
Todo todo = new Todo();
todo.id = cursor.getString(cursor.getColumnIndex(COLUMN_ID));
todo.from = cursor.getString(cursor.getColumnIndex(COLUMN_FROM));
todo.to = cursor.getString(cursor.getColumnIndex(COLUMN_TO));
todo.title = cursor.getString(cursor.getColumnIndex(COLUMN_TITLE))
todo.tag = cursor.getString(cursor.getColumnIndex(COLUMN_TAG));
arList.add(todo);
} while(cursor.moveToNext());
cursor.close();
db.close();
return arList;
}
finally {
cursor.close();
db.close();
}
}
You keep putting new strings to an already created hashmap, but you keep using the same keys, and therefore, many entries get replaced. The Todo object keeps your code readable. You should also check if the cursor can jump to the first entry (which makes a getCount call unnecessary)

Categories

Resources