I have a problem with retrieving albumArt and setting that art to ImageView using AsyncTask in cursor adapter.
When I open my app it looks like this:
Then I scroll down the list and everything is fine(but also if I scroll list not very fast):
Then I scroll list back to the very beggining(not fast) and it looks fine as well:
Probably I do something wrong, I think, so I have question:
Is it possible somehow to solve that problem, I already tried a lot of different ways on how to implement AsyncTask and make it works fine, but in the end of the day it looks always the same.
Below is code for cursor adapter:
public class AllSongsCursorAdapter extends CursorAdapter {
public AllSongsCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
public boolean isCheckBoxVisible;
private AddToFavouritesArray favouritesArray = AddToFavouritesArray.getInstance();
private static class ViewHolder {
CheckBox checkBox;
TextView title;
TextView artist;
ImageView albumArt;
private ViewHolder(View view) {
checkBox = (CheckBox) view.findViewById(R.id.favouritesCheckBox);
title = (TextView) view.findViewById(R.id.title);
artist = (TextView) view.findViewById(R.id.artist);
albumArt = (ImageView) view.findViewById(R.id.albumArt);
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
View view = LayoutInflater.from(context).inflate(R.layout.song_item, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
return view;
}
#Override
public void bindView(View view, Context context, final Cursor cursor) {
final ViewHolder viewHolder = (ViewHolder) view.getTag();
if (isCheckBoxVisible) {
viewHolder.checkBox.setVisibility(View.VISIBLE);
} else {
viewHolder.checkBox.setVisibility(View.GONE);
}
final int position = cursor.getPosition();
viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
favouritesArray.integerArray.add(position);
} else {
favouritesArray.integerArray.remove(Integer.valueOf(position));
}
}
});
int songTitle = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
int songArtist = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
String currentTitle = cursor.getString(songTitle);
String currentArtist = cursor.getString(songArtist);
viewHolder.title.setText(currentTitle);
viewHolder.artist.setText(currentArtist);
//__________________________ALBUM_ART_______________________________________________________
viewHolder.albumArt.setTag(cursor.getPosition());
new AsyncTask<ViewHolder, Void, Bitmap>(){
private ViewHolder viewHolder;
#Override
protected Bitmap doInBackground(ViewHolder... viewHolders) {
viewHolder = viewHolders[0];
int id = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
long songId = cursor.getLong(id);
Bitmap albumArt = getAlbumId(context, songId);
return albumArt;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if(bitmap != null) {
viewHolder.albumArt.setImageBitmap(bitmap);
}else{
viewHolder.albumArt.setImageResource(R.drawable.placeholder);
}
}
}.execute(viewHolder);
}
private Bitmap getAlbumId(Context context, long id) {
Bitmap albumArt = null;
String selection = MediaStore.Audio.Media._ID + " = " + id + "";
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[]{
MediaStore.Audio.Media._ID, MediaStore.Audio.Media.ALBUM_ID},
selection, null, null);
if (cursor.moveToFirst()) {
long albumId = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
albumArt = getAlbumArt(context, albumId);
}
cursor.close();
return albumArt;
}
private Bitmap getAlbumArt(Context context, long albumId) {
Bitmap albumArt = null;
String selection = MediaStore.Audio.Albums._ID + " = " + albumId + "";
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, null, selection, null, null);
if (cursor.moveToFirst()) {
int art = cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART);
String currentArt = cursor.getString(art);
albumArt = BitmapFactory.decodeFile(currentArt);
}
cursor.close();
return albumArt;
}
}
And yes, sure, without AsyncTask everything works fine except scrolling is very slow.
Thank you in advance!
EDIT
In the end of the day, that's how it works. Thank you very much # Orest Savchak, my up-vote and acceptance for your answer. Thanks a lot.
//__________________________ALBUM_ART_______________________________________________________
int id = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
long songId = cursor.getLong(id);
String string = getAlbumArtPath(context, songId);
if(string!=null) {
Picasso.with(context)
.load(new File(string))
.into(viewHolder.albumArt);
}else{
viewHolder.albumArt.setImageResource(R.drawable.placeholder);
}
}
private String getAlbumArtPath(Context context, long id) {
String selection = MediaStore.Audio.Media._ID + " = " + id + "";
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[]{
MediaStore.Audio.Media._ID, MediaStore.Audio.Media.ALBUM_ID},
selection, null, null);
if (cursor.moveToFirst()) {
long albumId = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
return getAlbumArt(context, albumId);
}
cursor.close();
return null;
}
private String getAlbumArt(Context context, long albumId) {
String selection = MediaStore.Audio.Albums._ID + " = " + albumId + "";
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, null, selection, null, null);
if (cursor.moveToFirst()) {
int art = cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART);
return cursor.getString(art);
}
cursor.close();
return null;
}
You should manage your tasks by yourself. Your views are recycled, so, you have one view for different rows, it causes a problem. Most of project use some libraries, that do it automatically for you - much easier, e.g Picasso
Picasso.with(context).load(new File(getAlbumArtPath(context, songId))).into(viewHolder.albumArt);
private String getAlbumArtPath(Context context, long id) {
String selection = MediaStore.Audio.Media._ID + " = " + id + "";
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[]{
MediaStore.Audio.Media._ID, MediaStore.Audio.Media.ALBUM_ID},
selection, null, null);
if (cursor.moveToFirst()) {
long albumId = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
return getAlbumArt(context, albumId);
}
cursor.close();
return null;
}
private String getAlbumArt(Context context, long albumId) {
String selection = MediaStore.Audio.Albums._ID + " = " + albumId + "";
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, null, selection, null, null);
if (cursor.moveToFirst()) {
int art = cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART);
return cursor.getString(art);
}
cursor.close();
return null;
}
Related
public void getAlbumArt(){
final Uri albumArtUri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
Cursor albumCursor = getContentResolver().query(albumArtUri, null, null, null, null);
if (albumCursor != null && albumCursor.moveToFirst()){
int album_Art = albumCursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM_ART);
do {
String albumArt = albumCursor.getString(album_Art);
QuerySongs querySongs = new QuerySongs(null, null, null, null, null, albumArt);
songList.add(querySongs);
}while(albumCursor.moveToNext());
albumCursor.close();
}
}
Adapter class
public void onBindViewHolder(SongHolder holder, final int position) {
//holder.tvIndex.setText(String.format(Locale.US, "%d", position));
holder.tvSongTitle.setText(songList.get(position).getTitle());
holder.tvArtistName.setText(songList.get(position).getArtist());
Picasso.with(context)
.load(Uri.parse("file://"+songList.get(position).getAlbumart()))
.error(R.drawable.no_album)
.into(holder.albumIv);
}
I have a problem with getting the album art from songs on the sd-card, what is the easiest way to get the album art, and display it in an imageview?
I have no clue what i'm doing wrong, i looked at other posts on this forum, but with no avail, still haven't found out how to do it correctly.
Thanks,
EDIT
public void getAlbumArt(){
final Uri albumArtUri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
Cursor albumCursor = getContentResolver().query(albumArtUri, null, null, null, null);
if (albumCursor != null && albumCursor.moveToFirst()){
int albumart_Column = albumCursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM_ART);
do {
String albumArt = albumCursor.getString(albumart_Column);
QuerySongs querySongs = new QuerySongs(null, null, null, null, null, albumArt);
songList.add(querySongs);
}while(albumCursor.moveToNext());
albumCursor.close();
}
albumIv = findViewById(R.id.albumIv);
Picasso.with(context)
.load(albumArtUri)
.error(R.drawable.no_album)
.into(albumIv);
}
Song Constructor
package com.vince_mp3player.mp3player;
/**
* Created by Vincent on 12/11/2017.
*/
public class QuerySongs {
long id;
long albumid;
String data;
String title;
String artist;
String albumart;
public QuerySongs(Long songId, Long albumId, String songData, String
songName, String songArtist, String albumArt){
this.id = songId;
this.albumid = albumId;
this.data = songData;
this.title = songName;
this.artist = songArtist;
this.albumart = albumArt;
}
public Long getId(){
return id;
}
public long getAlbumid() { return albumid; }
public String getData(){
return data;
}
public String getTitle() {
return title;
}
public String getArtist() {
return artist;
}
public String getAlbumart() { return albumart; }
}
Display Song Class
public void getAlbumArt(){
final Uri albumArtUri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
Cursor albumCursor = getContentResolver().query(albumArtUri, null, null, null, null);
if (albumCursor != null && albumCursor.moveToFirst()){
int albumart_Column = albumCursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM_ART);
do {
Uri albumArt = Uri.parse(albumCursor.getString(albumart_Column));
QuerySongs querySongs = new QuerySongs(null, null, null, null, null, albumArt);
songList.add(querySongs);
}while(albumCursor.moveToNext());
albumCursor.close();
}
}
SongAdapter
#Override
public void onBindViewHolder(SongHolder holder, final int position) {
//holder.tvIndex.setText(String.format(Locale.US, "%d", position));
holder.tvSongTitle.setText(songList.get(position).getTitle());
holder.tvArtistName.setText(songList.get(position).getArtist());
Picasso.with(context)
.load(Uri.parse(songList.get(songIndex).getAlbumart()))
.error(R.drawable.no_album)
.into(holder.albumIv);
}
EDIT 2
public void getSongs() {
final Uri songUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + "!=0";
Cursor myCursor = getContentResolver().query(songUri, null, selection, null, null);
if (myCursor != null && myCursor.moveToFirst()) {
int id_Column = myCursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
int albumId_Column = myCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID);
int data_Column = myCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
int title_Column = myCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
int artist_Column = myCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST);
int album_Column = myCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM);
do {
Long songId = myCursor.getLong(id_Column);
Long albumId = myCursor.getLong(albumId_Column);
String songData = myCursor.getString(data_Column);
String songName = myCursor.getString(title_Column);
String songArtist = myCursor.getString(artist_Column);
String songAlbum = myCursor.getString(album_Column);
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, albumId);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), albumArtUri);
bitmap = Bitmap.createScaledBitmap(bitmap, 30, 30, true);
}catch (FileNotFoundException exception ){
exception.printStackTrace();
bitmap = BitmapFactory.decodeResource(context.getResources(),R.drawable.no_album);
}catch (Exception e){
e.printStackTrace();
}
QuerySongs querySongs = new QuerySongs(songId, albumId, songData, songName, songArtist, songAlbum);
songList.add(querySongs);
} while (myCursor.moveToNext());
myCursor.close();
}
}
Fetch Album Id
public void getSongs() {
final Uri songUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + "!=0";
Cursor myCursor = getContentResolver().query(songUri, null, selection, null, null);
if (myCursor != null && myCursor.moveToFirst()) {
int id_Column = myCursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
int albumId_Column = myCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID);
int data_Column = myCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
int title_Column = myCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
int artist_Column = myCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST);
do {
Long songId = myCursor.getLong(id_Column);
Long albumId = myCursor.getLong(albumId_Column);
String songData = myCursor.getString(data_Column);
String songName = myCursor.getString(title_Column);
String songArtist = myCursor.getString(artist_Column);
QuerySongs querySongs = new QuerySongs(songId, albumId, songData, songName, songArtist);
songList.add(querySongs);
} while (myCursor.moveToNext());
myCursor.close();
}
}
In your Adapter Class
#Override
public void onBindViewHolder(SongHolder holder, final int position) {
//holder.tvIndex.setText(String.format(Locale.US, "%d", position));
holder.tvSongTitle.setText(songList.get(position).getTitle());
holder.tvArtistName.setText(songList.get(position).getArtist());
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, songList.get(position).getAlbumid());
Picasso.with(context)
.load(albumArtUri)
.error(R.drawable.no_album)
.into(holder.albumIv);
}
First, you're going to need runtime permissions to read files from disk.
Try doing this in the cursor loop
Uri albumArt = Uri.parse(albumCursor.getString(album_Art));
Add that to your list (after you change it's type from a string)
private Uri albumart;
public Uri getAlbumart() { return albumart; }
Picasso loads Uri objects, and I'm not sure file:// is resolvable, or appending it to the album art path is correct.
public void onBindViewHolder(SongHolder holder, final int position) {
holder.tvSongTitle.setText(songList.get(position).getTitle());
holder.tvArtistName.setText(songList.get(position).getArtist());
Picasso.with(context)
.load(songList.get(position).getAlbumart())
.error(R.drawable.no_album)
.into(holder.albumIv);
}
Also, lots of code here, but might get something out of it - Get Album Art With Album Name Android
I'm retrieving all contacts from both Google accounts and the phone.
I don't understand why pics are right for some and wrong for others.
Thanks a lot advance for any help.
This is my code,
List<AddressBookContact> list = new LinkedList<>();
LongSparseArray<AddressBookContact> array = new LongSparseArray<>();
String[] projection = {
ContactsContract.Data.MIMETYPE,
ContactsContract.Data.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.PHOTO_THUMBNAIL_URI,
ContactsContract.CommonDataKinds.Contactables.DATA,
ContactsContract.CommonDataKinds.Contactables.TYPE,
ContactsContract.RawContacts.ACCOUNT_TYPE
};
String selection = ContactsContract.Data.MIMETYPE + " in (?, ?)";
String[] selectionArgs = {
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
};
String sortOrder = ContactsContract.Contacts.SORT_KEY_ALTERNATIVE;
Uri uri = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
uri = ContactsContract.Data.CONTENT_URI;
}
assert uri != null;
Cursor cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
assert cursor != null;
final int idIdx = cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID);
final int nameIdx = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
final int picIdx = cursor.getColumnIndex(ContactsContract.Data.PHOTO_THUMBNAIL_URI);
final int dataIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.DATA);
final int typeIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.TYPE);
//final int typeDir = cursor.getColumnIndex(ContactsContract.Directory.ACCOUNT_TYPE);
I loop across the cursor and do some filters to avoid some duplicates
The idea is to gather same contact info under a same contact (object)
while (cursor.moveToNext()) {
long id = cursor.getLong(idIdx);
AddressBookContact addressBookContact = array.get(id);
//if(!cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE)).equals("com.google")){
//lastName = cursor.getString(nameIdx);
if(!lastName.toLowerCase().contains(cursor.getString(nameIdx).toLowerCase())){
if(!cursor.getString(nameIdx).toLowerCase().contains("unsub") && !cursor.getString(nameIdx).toLowerCase().contains("noreply")) {
if (!StringUtils.isEmailValid(cursor.getString(nameIdx).toLowerCase())) {
lastName = cursor.getString(nameIdx);
if (addressBookContact == null) {
addressBookContact = new AddressBookContact(id, cursor.getString(nameIdx), context.getResources());
addressBookContact.setImagepath(cursor.getString(picIdx));
array.put(id, addressBookContact);
list.add(addressBookContact);
addressBookContact.setId(id);
}
int type = cursor.getInt(typeIdx);
String data = cursor.getString(dataIdx);
addressBookContact.addEmail(type, data);
}
}
}
else{
if(addressBookContact != null){
int type = cursor.getInt(typeIdx);
String data = cursor.getString(dataIdx);
addressBookContact.addEmail(type, data);
}
}
//}
}
cursor.close();
return list;
}
Based on this, I create an object Contact which is retrieved within a Viewholder
#Override
public void onBindViewHolder(MyContactListViewHolder holder, int position) {
String imagepath = mainInfo.get(position).getImagepath();
if (imagepath != null && !imagepath.isEmpty()) {
ImageView imageView = (ImageView)holder.itemView.findViewById(R.id.imageview_contact_picture);
imageView.setImageURI(Uri.parse(imagepath));
}
else{
String firstLetter = mainInfo.get(position).getName().substring(0,1).toUpperCase();
TextDrawable drawable = TextDrawable.builder()
.buildRound(firstLetter, 0xff3fbfe8);
ImageView image = (ImageView) holder.itemView.findViewById(R.id.imageview_contact_no_picture);
image.setVisibility(View.VISIBLE);
image.setImageDrawable(drawable);
}
holder.textViewShowName.setText(mainInfo.get(position).getName());
}
Code for MyContactListViewHolder
class MyContactListViewHolder extends RecyclerView.ViewHolder{
ImageView imageViewUserImage;
TextView textViewShowName;
MyContactListViewHolder(View itemView) {
super(itemView);
textViewShowName = (TextView) itemView.findViewById(R.id.textview_contact_name);
imageViewUserImage = (ImageView) itemView.findViewById(R.id.imageview_contact_picture);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyBottomSheetDialogFragment bottomSheetDialogFragment = MyBottomSheetDialogFragment.newInstance();
Bundle bundle = new Bundle();
bundle.putParcelable("contact", mainInfo.get(getAdapterPosition()));
bottomSheetDialogFragment.setArguments(bundle);
bottomSheetDialogFragment.show(fragmentManager, null);
}
});
}
}
#Override
public MyContactListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.contacts_list_item, parent, false);
return new MyContactListViewHolder(v);
}
Don't use findViewById in the onBindViewHolder method. Do it in MyContactListViewHolder (which you are already doing).
Try the following code,
#Override
public void onBindViewHolder(MyContactListViewHolder holder, int position) {
String imagepath = mainInfo.get(position).getImagepath();
if (imagepath != null && !imagepath.isEmpty()) {
holder.imageViewUserImage.setImageURI(Uri.parse(imagepath));
} else{
String firstLetter = mainInfo.get(position).getName().substring(0,1).toUpperCase();
TextDrawable drawable = TextDrawable.builder().buildRound(firstLetter, 0xff3fbfe8);
holder.imageViewUserImage.setVisibility(View.VISIBLE);
holder.imageViewUserImage.setImageDrawable(drawable);
}
holder.textViewShowName.setText(mainInfo.get(position).getName());
}
I need to get all contacts that have at least a phone number. Android contacts may be picked from many accounts like gmail,skype,vibe etc. I made the classes i need to get the contacts i need. My problem that it gets anyway contacts that don't have at least 1 phone number and shows just their name and avatar. Can any1 say what I am doing wrong in my code? My code source is shared below.
ContactsActivity.class
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
selectionString = edtSearch.getText().toString();
String[] selectionArgs = {"%" + selectionString + "%", selectionString + "%", "%" + selectionString};
String selection = ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? OR "
+ ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? OR "
+ ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? AND "
+ ContactsContract.Contacts.HAS_PHONE_NUMBER + "=='1'";
return new CursorLoader(this,
ContactsContract.Contacts.CONTENT_URI, // URI
null, // projection fields
selection, // the selection criteria
selectionArgs, // the selection args
ContactsContract.Contacts.DISPLAY_NAME + " ASC" // the sort order
);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
ContactsAdapter.createCheckedContacts(data.getCount());
contactsAdapter.setCursor(data);
contactsAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
contactsAdapter.swapCursor(null);
}
ContactsAdapter.class
public class ContactsAdapter extends CursorAdapter {
static boolean status = true;
private static boolean[] checkedContacts;
private static Context context;
private static Cursor cursor;
public ContactsAdapter(Context context, Cursor c) {
super(context, c, 0);
this.context = context;
}
public static void setCursor(Cursor cursor) {
ContactsAdapter.cursor = cursor;
}
public static void createCheckedContacts(int count) {
checkedContacts = new boolean[count];
}
public static void saveSelectedContacts(ClientDao contactDao) {
for (int i = 0; i < checkedContacts.length; i++) {
if (checkedContacts[i]) {
cursor.moveToPosition(i);
DatabaseHelper.getInstance().saveClient(ContactUtils.cursorToContact(cursor, context), status);
status = !status;
}
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View convertView = ((Activity) context).getLayoutInflater().inflate(R.layout.contact_item, parent, false);
ViewHolder holder = new ViewHolder(convertView);
convertView.setTag(holder);
return convertView;
}
#Override
public void bindView(View convertView, final Context context, final Cursor cursor) {
final ViewHolder holder = (ViewHolder) convertView.getTag();
final Contact contact = ContactUtils.cursorToContact(cursor, context);
holder.tvName.setText(contact.getDisplayName());
if (isFirst(cursor)) {
holder.tvLetter.setVisibility(View.VISIBLE);
String letter = String.valueOf(Character.toUpperCase(contact.getDisplayName().charAt(0)));
holder.tvLetter.setText(letter);
} else {
holder.tvLetter.setVisibility(View.INVISIBLE);
}
convertView.setTag(convertView.getId(), contact);
if (!TextUtils.isEmpty(contact.getPhotoUri())) {
new ImageLoaderUtils.ContactImage(contact, convertView, holder.ivUserImage, context).execute();
} else {
holder.ivUserImage.setImageResource(R.drawable.ic_profile);
}
holder.inviteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ContactInvitationActivity_.class);
intent.putExtra("contact", contact);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
}
});
}
private boolean isFirst(Cursor cursor) {
Contact c1 = ContactUtils.cursorToContact(cursor, context);
if (cursor.getPosition() == 0)
return true;
cursor.moveToPrevious();
Contact c2 = ContactUtils.cursorToContact(cursor, context);
if (c1.getDisplayName() == null || c2.getDisplayName() == null)
return false;
if (Character.toUpperCase(c1.getDisplayName().charAt(0)) != Character.toUpperCase(c2.getDisplayName().charAt(0)))
return true;
return false;
}
private static class ViewHolder {
TextView tvName;
TextView tvLetter;
ImageView ivUserImage;
Button inviteBtn;
RelativeLayout rlContact;
private ViewHolder(View convertView) {
tvName = (TextView) convertView.findViewById(R.id.tvContactsName);
tvLetter = (TextView) convertView.findViewById(R.id.tvLetter);
ivUserImage = (ImageView) convertView.findViewById(R.id.ivUserIcon);
inviteBtn = (Button) convertView.findViewById(R.id.inviteBtn);
rlContact = (RelativeLayout) convertView.findViewById(R.id.rlContact);
}
}
}
ContactUtil.class
public class ContactUtils {
public static Contact cursorToContact(Cursor c, Context context) {
if (c == null || c.getPosition() < 0) return null;
Contact contactObj = new Contact();
try {
contactObj.setID(c.getString(c.getColumnIndex(ContactsContract.Contacts._ID)));
contactObj.setDisplayName(c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
contactObj.setPhotoUri(c.getString(c.getColumnIndex(ContactsContract.Contacts.PHOTO_URI)));
contactObj.setPhoneNumber("");
contactObj.setEmail("");
setPhoneNumber(c, contactObj, context);
setEmail(contactObj, context);
} catch (Exception e) {
e.printStackTrace();
}
return contactObj;
}
public static void setPhoneNumber(Cursor c, Contact contactObj, Context context) {
if (Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// Query phone here. Covered next
Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactObj.getID(), null, null);
phones.moveToFirst();
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i("Number", phoneNumber);
contactObj.setPhoneNumber(phoneNumber);
phones.close();
}
}
public static void setEmail(Contact contactObj, Context context) {
Cursor emailCur = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{contactObj.getID()}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String emailType = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
contactObj.setEmail(email);
}
emailCur.close();
}
}
Application need to read the phonebook contacts and show it to the user, have more than 8000 contacts on the phone.
Problem is it stuck for very long time while rendering all contacts on the screen.
Please suggest best way to accomplish this task. thanks
Main Method:
Cursor contactsCursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
LogUtils.d("### cursorCount" + contactsCursor.getCount());
contacts = new ArrayList<ImportContactModel>();
importContactList = new ArrayList<ImportContactModel>();
showProgressDialog();
asyncLoader = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
fetchContacts();
return null;
}
protected void onPostExecute(Void result) {
// create an array of Strings, that will be put to our
// ListActivity
adapter = new ImportContactArrayAdapter(
ImportContactSelection.this, contacts);
contactList.setAdapter(adapter);
contactList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
initSearch();
dismissProgressDialog();
};
}.execute();
Class to get Data:
public void fetchContacts() {
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;
String PROFILE_PIC = ContactsContract.CommonDataKinds.Phone.PHOTO_URI;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
Uri EMAIL_CONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EMAIL_CONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String EMAIL = ContactsContract.CommonDataKinds.Email.DATA;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null,
null);
// Loop for every contact in the phone
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
ImportContactModel tempContact = new ImportContactModel();
String contact_id = cursor
.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor
.getColumnIndex(DISPLAY_NAME));
String image_uri = cursor.getString(cursor
.getColumnIndex(PROFILE_PIC));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor
.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
tempContact.setId(contact_id);
if (image_uri != null)
tempContact.setProfilePic(cursor.getString(cursor
.getColumnIndex(PROFILE_PIC)));
else
tempContact.setProfilePic("");
tempContact.setContactName(name);
// Query and loop for every phone number of the contact
Cursor phoneCursor = contentResolver.query(
PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?",
new String[] { contact_id }, null);
// Get All Phone Numbers
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor
.getColumnIndex(NUMBER));
tempContact.setContactNo(phoneNumber);
break;
}
phoneCursor.close();
Cursor emailCursor = contentResolver.query(
EMAIL_CONTENT_URI, null, EMAIL_CONTACT_ID + "=?",
new String[] { contact_id }, null);
while (emailCursor.moveToNext()) {
String contactId = emailCursor.getString(emailCursor
.getColumnIndex(EMAIL_CONTACT_ID));
email = emailCursor.getString(emailCursor
.getColumnIndex(EMAIL));
tempContact.setEmail(email);
break;
}
emailCursor.close();
contacts.add(tempContact);
}
}
}
}
Adapter Class
public class ImportContactArrayAdapter extends ArrayAdapter<ImportContactModel> {
private final List<ImportContactModel> list;
private final Activity context;
private ImageLoader mImageLoader;
public ImportContactArrayAdapter(Activity context, List<ImportContactModel> list) {
super(context, R.layout.item_task_contact_select, list);
this.context = context;
this.list = list;
this.mImageLoader = ImageLoader.getInstance();
}
static class ViewHolder {
protected ImageView profilePic;
protected TextView contactName;
protected TextView contactNo;
protected CheckBox checkbox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.item_task_contact_select, null);
final ViewHolder viewHolder = new ViewHolder();
//viewHolder.profilePic = (ImageView) view.findViewById(R.id.img_import_profilePic);
viewHolder.contactName = (TextView) view.findViewById(R.id.name_text);
viewHolder.contactNo = (TextView)view.findViewById(R.id.tag_text_1);
viewHolder.contactNo.setVisibility(View.VISIBLE);
viewHolder.contactNo.setTextSize(11);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.select_checkbox);
viewHolder.checkbox.setClickable(true);
viewHolder.checkbox
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
ImportContactModel element = (ImportContactModel) viewHolder.checkbox
.getTag();
element.setSelected(buttonView.isChecked());
}
});
view.setTag(viewHolder);
viewHolder.checkbox.setTag(list.get(position));
} else {
view = convertView;
((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
ImageView avatar = (ImageView) view.findViewById(R.id.img_avatar);
ImageView avatarBorder = (ImageView) view.findViewById(R.id.img_avatar_overlay);
ProgressBar avatarProgress = (ProgressBar) view.findViewById(R.id.img_avatar_progress);
if(!list.get(position).equals(""))
//holder.profilePic.setImageURI(Uri.parse(list.get(position).getProfilePic()));
mImageLoader.displayImage(list.get(position).getProfilePic(), avatar, new AvatarsImageLoadingListener(avatarProgress, avatarBorder, R.drawable.bg_nophoto));
holder.contactName.setText(list.get(position).getContactName());
holder.contactNo.setText(list.get(position).getContactNo());
holder.checkbox.setChecked(list.get(position).isSelected());
return view;
}
public ArrayList<ImportContactModel> getCheckList(){
ArrayList<ImportContactModel> tempList = new ArrayList<ImportContactModel>();
for(int i=0;i<list.size();i++){
if(list.get(i).isSelected()){
tempList.add(list.get(i));
LogUtils.d(""+list.get(i).getContactName());
}
}
return tempList;
}
}
So it just shows Loading screen for huge amount of time..
You don't have to fetch all contacts to display them. AsyncTask has publishProgress method. I'm not experienced with Cursor class, since I prefer ORM for that, so I'll write in pseudo code, you'll have to adapt it yourself.
//in AsyncTask
protected Void doInBackground(params){
while(cursor.moveToNext()){
contactInfo = createContact(currentCursorValue);
publishProgress(contactInfo);
}
}
onProgressUpdate(contactInfo){
if(adapter==null){
//first time adapter setup
}
adapter.add(contactInfo);
adapter.notifyDataSetChanged();
}
This way, every time you pull a record from Db, you publish it, and items are added continuously. User won't notice any delay, unless he tries searching for not yet existing items, or you want to implement that big pop up letter for fast scroll. Still, above code is not very effective, since publishing the progress every .001 second or so, is not very smart, so you can either publish every 20 results, or publish them every second, up to you.
I'm trying to create a custom gallery that allows users to pick from all the photos and videos contained on their Android device. I know how to create a gallery of just photos and just videos, but if I want to combine both, how can I do this?
I think the issue comes down to how I create my cursor. To select all videos, I created the cursor this way:
String[] videoParams = {MediaStore.Video.Media._ID,
MediaStore.Video.Media.DATA,
MediaStore.Video.Media.DATE_TAKEN,
MediaStore.Video.Thumbnails.DATA};
videocursor = getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoParams, null, null, null);
If I want to query all the media files, not just video, what do I do?
This is what I tried, based off of: Custom Gallery with Images and Videos in android to select multiple items
String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
String jpg_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("jpg");
String png_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("png");
String mp4_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("mp4");
String[] selectionArgs = new String[]{jpg_mimeType, png_mimeType, mp4_mimeType};
mediaCursor = getContentResolver().query(MediaStore.Files.getContentUri("internal"), null, selectionMimeType, selectionArgs, MediaStore.Files.FileColumns.DATE_ADDED);
This gives me the error java.lang.IllegalArgumentException: Cannot bind argument at index 3 because the index is out of range. The statement has 1 parameters at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:167)
Perhaps my approach is completely wrong, but I can't find any examples of custom android galleries using both images and videos, which is bizarre to me as this seems like it would be a common thing to create.
Here's all of my code, in case it's helpful:
public class GridViewCompatActivity extends Activity {
GridViewCompat gridView;
private static final String TAG = "GridViewCompatActivity";
Cursor videocursor;
Cursor mediaCursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid_view_compat);
gridView = (GridViewCompat) findViewById(R.id.gridView1);
// NOTE: We are using setChoiceMode, as I said, its a drop-in replacement
gridView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
gridView.setAdapter(new ImageAdapter(getApplicationContext()));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> view, View arg1, int pos, long id) {
// We need to invalidate all views on 4.x versions
GridViewCompat gridView = (GridViewCompat) view;
gridView.invalidateViews();
}
});
findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SparseBooleanArray checkArray;
checkArray = gridView.getCheckedItemPositions();
String selectedPos = "Selected positions: ";
int count = checkArray.size();
for (int i = 0; i < count; i++) {
if (checkArray.valueAt(i))
selectedPos += checkArray.keyAt(i) + ",";
}
Intent intent = new Intent();
intent.putExtra("result", selectedPos);
setResult(Activity.RESULT_OK, intent);
finish();
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
Log.d(TAG, "number of media: " + Integer.toString(MediaStore.Files.FileColumns.DATA.length()));
int mediaParams = MediaStore.MediaColumns.DATA.length();
return mediaParams;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new grid view item for each item referenced by the Adapter
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
CheckBox checkBox;
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
convertView = layoutInflater.inflate(R.layout.grid_view_item, parent, false);
}
imageView = (ImageView) convertView.findViewById(R.id.imageView1);
checkBox = (CheckBox) convertView.findViewById(R.id.checkBox1);
GridViewCompat gvc = (GridViewCompat) parent;
if (gvc.getChoiceMode() == ListView.CHOICE_MODE_MULTIPLE) {
SparseBooleanArray checkArray;
checkArray = gvc.getCheckedItemPositions();
checkBox.setChecked(false);
if (checkArray != null) {
if (checkArray.get(position)) {
checkBox.setChecked(true);
}
}
}
// imageView.setImageResource(mThumbIds[position]);
Bitmap bmThumbnail;
Log.d(TAG, "position: " + position);
mediaCursor = getContentResolver().query(MediaStore.Files.getContentUri("internal"), null, selectionMimeType, selectionArgs, MediaStore.Files.FileColumns.DATE_ADDED);
Log.d(TAG, Integer.toString(mediaCursor.getCount()));
for (int i = 0; i < mediaCursor.getCount(); i++){
mediaCursor.moveToPosition(i);
Boolean isVideo = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA)).length() > 0;
Log.d(TAG, "isVideo: " + isVideo);
String mediaPath = "";
if(isVideo){
mediaPath = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
video_paths.add(mediaPath);
}else{
mediaPath = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Images.Media.DATA));
video_paths.add(mediaPath);
}
Log.d(TAG, "mediaPath: " +mediaPath);
}
mediaCursor.moveToPosition(position);
String video_path = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
Log.d(TAG, "video_path: " + video_path);
imageView.setImageBitmap(ThumbnailUtils.createVideoThumbnail(video_path, Thumbnails.MICRO_KIND));
return convertView;
}
ArrayList<String> video_paths = new ArrayList<String>();
String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
String jpg_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("jpg");
String png_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("png");
String mp4_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("mp4");
String[] selectionArgs = new String[]{jpg_mimeType, png_mimeType, mp4_mimeType};
// String[] videoParams = {MediaStore.Video.Media._ID,
// MediaStore.Video.Media.DATA,
// MediaStore.Video.Media.DATE_TAKEN,
// MediaStore.Video.Thumbnails.DATA};
// }
}
}
public class GalleryFragment extends Fragment
{
private int count;
private Bitmap[] thumbnails;
private boolean[] thumbnailsselection;
private String[] arrPath;
private int[] typeMedia;
private ImageAdapter imageAdapter;
#SuppressLint("NewApi") #Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.gallery_gridview, container, false);
String[] columns = { MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.DATE_ADDED,
MediaStore.Files.FileColumns.MEDIA_TYPE,
MediaStore.Files.FileColumns.MIME_TYPE,
MediaStore.Files.FileColumns.TITLE,
};
String selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE
+ " OR "
+ MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO;
final String orderBy = MediaStore.Files.FileColumns.DATE_ADDED;
Uri queryUri = MediaStore.Files.getContentUri("external");
#SuppressWarnings("deprecation")
Cursor imagecursor = getActivity().managedQuery(queryUri,
columns,
selection,
null, // Selection args (none).
MediaStore.Files.FileColumns.DATE_ADDED + " DESC" // Sort order.
);
int image_column_index = imagecursor.getColumnIndex(MediaStore.Files.FileColumns._ID);
this.count = imagecursor.getCount();
this.thumbnails = new Bitmap[this.count];
this.arrPath = new String[this.count];
this.typeMedia = new int[this.count];
this.thumbnailsselection = new boolean[this.count];
for (int i = 0; i < this.count; i++) {
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 4;
bmOptions.inPurgeable = true;
int type = imagecursor.getColumnIndex(MediaStore.Files.FileColumns.MEDIA_TYPE);
int t = imagecursor.getInt(type);
if(t == 1)
thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail(
getActivity().getContentResolver(), id,
MediaStore.Images.Thumbnails.MINI_KIND, bmOptions);
else if(t == 3)
thumbnails[i] = MediaStore.Video.Thumbnails.getThumbnail(
getActivity().getContentResolver(), id,
MediaStore.Video.Thumbnails.MINI_KIND, bmOptions);
arrPath[i]= imagecursor.getString(dataColumnIndex);
typeMedia[i] = imagecursor.getInt(type);
}
GridView imagegrid = (GridView) v.findViewById(R.id.PhoneImageGrid);
Button reSizeGallery = (Button) v.findViewById(R.id.reSizeGallery);
imageAdapter = new ImageAdapter();
imagegrid.setAdapter(imageAdapter);
imagecursor.close();
reSizeGallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ChatViewerAdapter.ScreenResize(getActivity());
}
});
return v;//super.onCreateView(inflater, container, savedInstanceState);
}
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ImageAdapter() {
mInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
#SuppressLint("NewApi") public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(
R.layout.gallery_view, null);
holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
holder.videoICON = (ImageView) convertView.findViewById(R.id.videoICON);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.imageview.getLayoutParams().height = height/6;
holder.imageview.getLayoutParams().width = width/4;
holder.imageview.setId(position);
if(typeMedia[position] == 1)
holder.videoICON.setVisibility(View.GONE);
else if(typeMedia[position] == 3)
holder.videoICON.setVisibility(View.VISIBLE);
holder.imageview.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int id = v.getId();
Display display = ((WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int height = display.getHeight();
final int height_half = (int) (height/2.5);
RelativeLayout fragment_layout = (RelativeLayout) getActivity().findViewById(R.id.fragment_gallery);
fragment_layout.setVisibility(View.VISIBLE);
fragment_layout.getLayoutParams().height = height_half;
GalleryImageChooseFragment f_img_choose =new GalleryImageChooseFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Bundle args = new Bundle();
args.putString("PATH", arrPath[id]);
f_img_choose.setArguments(args);
ft.show(f_img_choose);
ft.replace(R.id.fragment_tattle, f_img_choose);
ft.addToBackStack("f_img_choose");
ft.commit();
}
});
holder.imageview.setImageBitmap(thumbnails[position]);
holder.id = position;
return convertView;
}
}
class ViewHolder {
ImageView imageview;
ImageView videoICON;
int id;
}
}
Download source code form here (Get all videos from gallery android).
public void fn_video() {
int int_position = 0;
Uri uri;
Cursor cursor;
int column_index_data, column_index_folder_name,column_id,thum;
String absolutePathOfImage = null;
uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Video.Media.BUCKET_DISPLAY_NAME,MediaStore.Video.Media._ID,MediaStore.Video.Thumbnails.DATA};
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
cursor = getApplicationContext().getContentResolver().query(uri, projection, null, null, orderBy + " DESC");
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
column_index_folder_name = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.BUCKET_DISPLAY_NAME);
column_id = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
thum = cursor.getColumnIndexOrThrow(MediaStore.Video.Thumbnails.DATA);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
Log.e("Column", absolutePathOfImage);
Log.e("Folder", cursor.getString(column_index_folder_name));
Log.e("column_id", cursor.getString(column_id));
Log.e("thum", cursor.getString(thum));
Model_Video obj_model = new Model_Video();
obj_model.setBoolean_selected(false);
obj_model.setStr_path(absolutePathOfImage);
obj_model.setStr_thumb(cursor.getString(thum));
al_video.add(obj_model);
}
}
This function will return arraylist of gallery images and videos in descending order. Just pass this function to adapter and show gallery stuff in recyclerview in kotlin.
#SuppressLint("Range")
fun getAllGalleryMedia(): ArrayList<Media> {
val result = ArrayList<Media>()
val projection = arrayOf(
MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.DATE_ADDED,
MediaStore.Files.FileColumns.DISPLAY_NAME,
MediaStore.Files.FileColumns.MEDIA_TYPE,
MediaStore.Files.FileColumns.MIME_TYPE,
MediaStore.Files.FileColumns.TITLE
)
val selection = (MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE
+ " OR "
+ MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO)
val queryUri = MediaStore.Files.getContentUri("external")
Handler(Looper.getMainLooper()).post {
val cursorLoader = CursorLoader(
context,
queryUri,
projection,
selection,
null,
MediaStore.Files.FileColumns.DATE_ADDED + " DESC"
)
val cursor: Cursor? = cursorLoader.loadInBackground()
if (cursor != null) {
while (cursor.moveToNext()) {
val id = cursor.getLong(cursor.getColumnIndex(MediaStore.Files.FileColumns._ID))
val displayName =
cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DISPLAY_NAME))
val imagePath =
cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA))
val dateAdded =
cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATE_ADDED))
val mimeType =
cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.MIME_TYPE))
result.add(Media(id, displayName, imagePath, dateAdded, mimeType))
}
cursor.close()
}
}
return result
}
This is model class,you can modify according to your needs.
class Media:java.io.Serializable{
var id:Long=0
var displayName:String=""
var imagePath:String=""
var dateAdded:String=""
var mimeType:String=""
var isSelected:Boolean = false
constructor(){
// empty constructor
}
constructor(
id: Long,
displayName: String,
imagePath: String,
dateAdded: String,
mimeType: String
){
this.id = id
this.displayName = displayName
this.imagePath = imagePath
this.dateAdded = dateAdded
this.mimeType = mimeType
}}