How to load images from the phone taken in last hour? - android

I want to load and display all images that are taken by my phone in last hour. I am using Content Resolver query with some parameters to get images list. I can use this to display just last 10 images:
String sortOrder = String.format("%s limit 50 ", MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC");
And that is working with code from below, but I want to modify my cursor query to just display images taken in last hour.
Here is the code:
String orderBy = MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC LIMIT 10";
//Current time in millis and hour ago
int now = Calendar.getInstance().get(Calendar.MILLISECOND);
long hourAgo = now - 60*60000;
String[] columns = new String[]{
MediaStore.Images.Media._ID, // get the image
};
ContentResolver contentResolver = getContentResolver();
// Set up an array of the Thumbnail Image ID column we want
String[] projection = {MediaStore.Images.Thumbnails._ID};
// Create the cursor pointing to the SDCard
cursor = contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
columns, // Which columns to return
null, // Return all rows
null,
orderBy);
// Get the column index of the Thumbnails Image ID
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
How I can only get list of images taken in last hour?
I tried to write this also, but it does not work:
final String[] selectionArgs = { MediaStore.Images.ImageColumns.DATE_TAKEN + "<"+ Long.toString(hourAgo) };
cursor = contentResolver.query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
cols, // Which columns to return
null, // Return all rows
selectionArgs ,
orderBy);

Related

How to make sort gallery thumbnails image by date

I am developing an android applicaiton. This application get all thumbnail images from gallery. I want to sort these thumbnails by date, but I can't do it.
Please help me.
Get all images
// Set up an array of the Thumbnail Image ID column we want
String[] columns = {MediaStore.Images.Media._ID};
String orderBy = MediaStore.Images.Thumbnails._ID + " DESC LIMIT 10";
// Create the cursor pointing to the SDCard
cursor = getActivity().managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
columns, // Which columns to return
null, // Return all rows
null,
orderBy);
// Get the column index of the Thumbnails Image ID
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
myGalleryImages = (GridView) view.findViewById(R.id.my_gallery);
myGalleryImages.setAdapter(new ImageAdapter(getActivity()));
set images
// Move cursor to current position
cursor.moveToPosition(position);
// Get the current value for the requested column
int imageID = cursor.getInt(columnIndex);
// Set the content of the image based on the provided URI
holder.image.setImageURI(Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID));
Update columns and orderBy like this:
String[] columns = {MediaStore.Images.Media._ID, MediaStore.Images.ImageColumns.DATE_TAKEN};
String orderBy = MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC";
and see if that helps.
You could also fetch real images instead of thumbnails and use image loading library that will take care of proper re-sizing. In this case replace your Thumbnails references with ImageColumns
this code will save the first 100 thumbs (SORTED by date)
Cursor cursor = this.getContentResolver().query( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Return all rows
null,
"image_id DESC");
// Get the column index of the Thumbnails Image ID
int columnIndex = cursor.getColumnIndex(MediaStore.Images.Thumbnails.DATA);
for(int i =0;i<cursor.getCount();i++){
if (i==100) break;
cursor.moveToPosition(i);
mImagesFromGallery[i] = cursor.getString(columnIndex);
}
cursor.close();

How to actually search for a song in a mediastore cursor using a string

I have set up the cursor but I am still struggling with actually searching it. How do I search for the track name? How do I get its ID so I can pass it to mediaplayer? I have tried different things but didn't succeed.
Basically, I want to know how to search the mediastore for a certain string (string songToPlay in this case), get the results, get the ID of the best match and pass it to my mediaplayer service to play it in the background. The only thing I am asking you is how to get the ID though.
This is the code I am using:
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String[] songToPlay = value.split("play song");
String[] searchWords = songToPlay[1].split(" ");
String [] keywords = null;
StringBuilder where = new StringBuilder();
where.append(MediaStore.Audio.Media.TITLE + " != ''");
String selection = where.toString();
String[] projection = {
BaseColumns._ID,
MediaStore.Audio.Media.MIME_TYPE,
MediaStore.Audio.Artists.ARTIST,
MediaStore.Audio.Albums.ALBUM,
MediaStore.Audio.Media.TITLE
};
for (int i = 0; i < searchWords.length; i++) {
keywords[i] = '%' + MediaStore.Audio.keyFor(searchWords[i]) + '%';
}
Cursor cursor = this.managedQuery(uri, projection, selection, keywords, MediaStore.Audio.Media.TITLE);
if (cursor.moveToFirst()) {
do{
test.setText(cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)));
}while(cursor.moveToNext());
}
I'm very confused and most of this code is from the internet. I have been trying to do this for 2 days now, that's why I'm asking here. I've done hours of trying by myself.
edit: Current code. How am I supposed to find the location - music ID or whatever I need to play that song from the cursor?
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String songToPlay = value.replaceAll("play song", "").trim();
int music_column_index;
String[] projection = {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Artists.ARTIST,
MediaStore.Audio.Albums.ALBUM,
MediaStore.Audio.Media.TITLE
};
#SuppressWarnings("deprecation")
Cursor cursor = this.managedQuery(uri,
null,
MediaStore.Audio.Media.TITLE + "=?",
new String[]{songToPlay},
MediaStore.Audio.Media.TITLE + " ASC");
This will search the MediaStore for all songs with title equal to the value of your songToPlay string.
Cursor cursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
null,
MediaStore.Audio.Media.TITLE + "=?",
new String[]{songToPlay},
MediaStore.Audio.Media.TITLE + " ASC");
You can then of course query the cursor to get the ID (and any other column) of any results.
while (cursor.moveToNext()) {
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
// Whatever else you need
}
However this will require an exact match, you may like to use the LIKE operator for a more fuzzy match.

Media Gallery ContentProvider

My app will display the complete list of images in my custom gallery .For this, I'm using ContentProvider of Image Thumbnails. Upon selecting the thumbnail's I need to display the actual image.According to my understanding Gallery's image do have same unique ID in Thumb and Media Table.
Here is the code. Firstly I queried Thumbnail's ContentProvider and saved URL and ID.
String pictureThumbTemp[] = { MediaStore.Images.Thumbnails._ID, MediaStore.Images.Thumbnails.DATA };
Cursor imagecursor = context.getContentResolver().query (MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
pictureThumbTemp,null, null, null);
Later I am displaying thumbs in Grid.
Upon selection of thumbnail, I have to display original image. I'm trying to retrieve the original image like
String pictureImageTemp[] = { MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA };
Cursor imagecursor = context.getContentResolver().query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
pictureImageTemp, MediaStore.Images.Media._ID + " = " + mediaID + "", null,
MediaStore.Images.Media._ID);
Overall, I'm showing thumbnail through it's url and upon click I'm querying the thumbnail's media ID in Original image table.
But it is returning a cursor with 0 results.
Please help me out.
Thanks,
sha.
I cracked out a way which worked out.
Retrieved the cursor for Original Images.
From that I pulled the ID for every image and Queried the Thumbnails for the ID which returns a cursor containing paths.
Find the code snippet below.
String pictureCols[] = { MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA };
Cursor imagecursor = mContext.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, pictureCols,
null, null, null);
imagecursor.moveToFirst();
mImageUrls = new ArrayList<String>();
try {
// Iterate the cursor for Image urls
for (int index = 0; index < imagecursor.getCount(); index++) {
imagecursor.moveToPosition(index);
preparePicture(imagecursor);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
imagecursor.close();
}
}
Here is the code for preparePicture method
private void preparePicture(Cursor imageCursor) {
// get the ID for the original image
int idColumnIndex = imageCursor.getColumnIndex(mSelectedImage.mediaID);
Long id = imageCursor.getLong(idColumnIndex);
// Thumbnail image Cursor for this specific image.
String thumbCols[] = { MediaStore.Images.Thumbnails._ID, MediaStore.Images.Thumbnails.DATA };
Cursor thumbCursor = MediaStore.Images.Thumbnails.queryMiniThumbnail(mContext.getContentResolver(), id,
Thumbnails.MINI_KIND, thumbCols);
thumbCursor.moveToFirst();
// Save thumbnail URL in MediaInfo
dataColumnIndex = thumbCursor.getColumnIndex(mSelectedThumb.data);
String thumbURL = thumbCursor.getString(dataColumnIndex);
thumbCursor.close();
mImageUrls.add(url);
}
Finally, I will have all my Thumbnail urls in the ArrayList.
The same logic is not working for video thumbnails. Of course that is a different question :)
Regards,
Sha.
try this one
final String[] pictureImageTemp= { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, pictureImageTemp, null,
null, MediaStore.Images.Media._ID);

How to fast the contacts loading in listview on android

in my app i am listing contacts in a listview. no of contacts is 1000+. i get the contacts
by using ContentResolver query that is cr.query(...),store the values in an arraylist
and after that load the array list in setListAdapter(...). to display the all contacts my
apps takes nearly 1 minute so that i use Async task but there is no big differences by using the async task.
i need to display all contacts within 2 to 4 seconds. i check in the default contacts
application on android simulator which is load within in 2 to 4 seconds. i have spend
long time in google. but i could not get any helpful solution. please help me how to fast the loading contacts on listview. please help me.
my coding sample:
private ArrayList<ContactListEntry> loadContactListInternal(String searchString) {
ArrayList<ContactListEntry> contactList = new ArrayList<ContactListEntry>();
ContentResolver cr = getContentResolver();
Cursor cur = null;
String[] projection = new String[] {BaseColumns._ID,ContactsContract.Contacts.DISPLAY_NAME,ContactsContract.Contacts.PHOTO_ID};
....
cur=cr.query(ContactsContract.Contacts.CONTENT_URI, projection, selection, null, ContactsContract.Contacts.DISPLAY_NAME + " ASC");
while (cur.moveToNext()) {
int id = Integer.parseInt(cur.getString(0));
....
if (input !=null)
photo = BitmapFactory.decodeStream(input);
....
ArrayList<ContactListEntry.PhoneEntry> phoneEntries = new ArrayList<ContactListEntry.PhoneEntry>();
String[] projection1 = new String[] {ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKinds.Phone.TYPE};
Cursor pcur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,projection1, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { String.valueOf(id) }, null);
while (pcur.moveToNext()) {
...
}
pcur.close();
ContactListEntry entry = new ContactListEntry(id, name, photo, phoneEntries);
contactList.add(entry);
}
cur.close();
return contactList;
}
.....
in another class
private void selectionUpdated() {
....
setListAdapter(new SelectedArrayAdapter(this, app.selectedContacts));
...
}
Use the Concept of projections and selection arguments to retrive the contacts in my case for 500 contacts intially it was taking 12 sec.
Now it is taking 350ms(lessthan second)
void getAllContacts() {
long startnow;
long endnow;
startnow = android.os.SystemClock.uptimeMillis();
ArrayList arrContacts = new ArrayList();
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Cursor cursor = ctx.getContentResolver().query(uri, new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.Contacts._ID}, selection, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
String contactNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
int phoneContactID = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
int contactID = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Log.d("con ", "name " + contactName + " " + " PhoeContactID " + phoneContactID + " ContactID " + contactID)
cursor.moveToNext();
}
cursor.close();
cursor = null;
endnow = android.os.SystemClock.uptimeMillis();
Log.d("END", "TimeForContacts " + (endnow - startnow) + " ms");
}
More information on this link http://www.blazin.in/2016/02/loading-contacts-fast-from-android.html ....
So your problem is that you do a lot of subqueries for each contact. I has the same issue once upon a time. My case was that I showed many contacts and allowed the user to click on any of them. After that I started processing the contact in another activity.
Back then I finally decided that I should display only the name and lazily fetch all the other data later on, just before I launch the next activity. This was amazing: decreased the speed of my program almost by a factor of 200, and the operations became completely invisible to the user.
The default android list does the same if I am not wrong - it displays only the name, and later on loads all the other contact-related data.
i use cursor adapter and i cut the databse,arrayadapter and optimize the code.
Consider having just one query and getting rid of the sub query idea (as already suggested). You can achieve speed by just querying using the Content Uri:
"ContactsContract.CommonDataKinds.Phone.CONTENT_URI"
This URI also has the "ContactsContract.Contacts.DISPLAY_NAME" field.
You might also want to consider doing this query and working with your adapter in a seperate thread to make it completely transparent.
This worked for me.
OPTIMIZED SOLUTION HERE.....
private static final String[] PROJECTION = new String[] {
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
.
.
.
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, null, null, null);
if (cursor != null) {
try {
final int nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
final int numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String name, number;
while (cursor.moveToNext()) {
name = cursor.getString(nameIndex);
number = cursor.getString(numberIndex);
}
} finally {
cursor.close();
}
}
CHEERS...:)

How can I get an URL from a cursor object

I have a Cursor points to a Contact. How can I get an url built from that Cursor?
I need to know that because from here
http://developer.android.com/guide/topics/providers/content-providers.html
I need to have an url so that I can build a phone uri, like this:
phoneUri = Uri.withAppendedPath(uri, People.Phones.CONTENT_DIRECTORY);
and I can query all the phone numbers for that contact.
You can use the following query to retrieve all numbers for a certain contact:
/* the following line assumes that the contactCursor you described
* has the People._ID column at index 0 in its projection. */
int contactId = contactCursor.getInt(0);
Cursor numberCursor = getContentResolver().query(Phones.CONTENT_URI,
new String[] {Phones.NUMBER}, Phones.PERSON_ID + "=" + contactId, null, null);
while(cursor.moveToNext()) {
String number = cursor.getString(0);
}
cursor.close();

Categories

Resources