Android - List images from external storage into Recycleview - android

I'm trying to do a simple thing and its get all images from the external storage into recycle view and display them.
My problem is that for some reason i recieve null and i dont know why.
I successfully getting all the images into array list of string.
And then on the Reycleview i'm getting error of null exception.
Cant find what im doing wrong.
The log shows me that the error comes from the Recycler.From the method "onBindViewHolder" (i also mentioned this line).
It craches holder.imgView.setImageURI(imageUri); - still cant understand why,
even though i checked that its not null.
My Code
private BootstrapButton btnLoadImage;
private RecyclerView rvImages;
private static final int REQUEST_CODE = 1;
private boolean mStoragePermissions;
private ArrayList<String> imageLists;
private ImageViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLoadImage = (BootstrapButton)findViewById(R.id.btnLoadImges);
rvImages = (RecyclerView)findViewById(R.id.rvPictures);
btnLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mStoragePermissions){
imageLists = getFilePaths();
Log.d("MainActivity",imageLists.toString());
if(imageLists != null)
setAdapter(imageLists);
}else{
verifyStoragePermissions();
}
}
});
}
private void setAdapter(ArrayList<String> imageLists) {
adapter = new ImageViewAdapter(getApplication(),imageLists);
rvImages.setAdapter(adapter);
rvImages.setLayoutManager(new GridLayoutManager(getApplication(),3));
btnLoadImage.setVisibility(View.INVISIBLE);
}
public ArrayList<String> getFilePaths()
{
Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.Images.ImageColumns.DATA};
Cursor c = null;
SortedSet<String> dirList = new TreeSet<String>();
ArrayList<String> resultIAV = new ArrayList<String>();
String[] directories = null;
if (u != null)
{
c = managedQuery(u, projection, null, null, null);
}
if ((c != null) && (c.moveToFirst()))
{
do
{
String tempDir = c.getString(0);
tempDir = tempDir.substring(0, tempDir.lastIndexOf("/"));
try{
dirList.add(tempDir);
}
catch(Exception e)
{
Log.d("MainActivity",e.getMessage().toString());
}
}
while (c.moveToNext());
directories = new String[dirList.size()];
dirList.toArray(directories);
}
for(int i=0;i<dirList.size();i++)
{
File imageDir = new File(directories[i]);
File[] imageList = imageDir.listFiles();
if(imageList == null)
continue;
for (File imagePath : imageList) {
try {
if(imagePath.isDirectory())
{
imageList = imagePath.listFiles();
}
if ( imagePath.getName().contains(".jpg")|| imagePath.getName().contains(".JPG")
|| imagePath.getName().contains(".jpeg")|| imagePath.getName().contains(".JPEG")
|| imagePath.getName().contains(".png") || imagePath.getName().contains(".PNG") )
{
String path= imagePath.getAbsolutePath();
resultIAV.add(path);
}
}
// }
catch (Exception e) {
e.printStackTrace();
}
}
}
return resultIAV;
}
public class ImageViewAdapter extends RecyclerView.Adapter<ImageViewHolder>{
private LayoutInflater inflater;
private Context context;
private ArrayList<String> data;
public ImageViewAdapter(Context context, ArrayList<String> data){
this.context = context;
this.inflater = LayoutInflater.from(context);
this.data = data;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = inflater.inflate(R.layout.image_item,parent,false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder, int position) {
String imgSrc = data.get(position);
Uri imageUri = Uri.parse(imgSrc);
if(imageUri != null) {
//**Here i always getting null exception **
holder.imgView.setImageURI(imageUri);
}
}
#Override
public int getItemCount() {
return data.size();
}
}
public class ImageViewHolder extends RecyclerView.ViewHolder{
private ImageView imgView;
public ImageViewHolder(View itemView){
super(itemView);
imgView = (ImageView)findViewById(R.id.imageView);
}
}
}

What is null is this in your ImageViewHolder ImageView imgView;
You're using
imgView = (ImageView)findViewById(R.id.imageView);
But look that findViewById is finding a view in your activity, and not in your RecyclerView ViewHolder, precisely in your image_item.xml root layout.
So, just use findViewById in that view:
public ImageViewHolder(View itemView){
super(itemView);
imgView = (ImageView) itemView.findViewById(R.id.imageView);
}

Related

Retrieve all images directories in android

I have tried this to get directories and load images from them but it is very slow to load images and when camera is selected it crashed after some time...
< -------- Code to get directories and images from them ------- >
public static ArrayList<String> getImageBuckets(Context mContext){
ArrayList<String> buckets = new ArrayList<>();
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String [] projection = {MediaStore.Images.Media.BUCKET_DISPLAY_NAME, MediaStore.Images.Media.DATA};
Cursor cursor = mContext.getContentResolver().query(uri, projection, null, null, null);
if(cursor != null){
File file;
while (cursor.moveToNext()){
String bucketPath = cursor.getString(cursor.getColumnIndex(projection[0]));
String fisrtImage = cursor.getString(cursor.getColumnIndex(projection[1]));
file = new File(fisrtImage);
if (file.exists() && !buckets.contains(bucketPath)) {
buckets.add(bucketPath);
}
}
cursor.close();
}
return buckets;
}
public static ArrayList<String> getImagesByBucket(Context mContext , #NonNull String bucketPath){
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String [] projection = {MediaStore.Images.Media.DATA};
String selection = MediaStore.Images.Media.BUCKET_DISPLAY_NAME+" =?";
String orderBy = MediaStore.Images.Media.DATE_ADDED+" DESC";
ArrayList<String> images = new ArrayList<>();
Cursor cursor = mContext.getContentResolver().query(uri, projection, selection,new String[]{bucketPath}, orderBy);
if(cursor != null){
File file;
while (cursor.moveToNext()){
String path = cursor.getString(cursor.getColumnIndex(projection[0]));
file = new File(path);
if (file.exists() && !images.contains(path)) {
images.add(path);
}
}
cursor.close();
}
return images;
}
< ---------- Here is adapter and method to select directory --------->
<--------------------Adapter------------------>
public class GridImageAdapter extends ArrayAdapter<String> {
private Context mContext;
private LayoutInflater mInflater;
private int layoutResource;
private String mAppend;
private ArrayList<String> imgURLs;
public GridImageAdapter(Context context, int layoutResource, String append, ArrayList<String> imgURLs) {
super(context, layoutResource, imgURLs);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = context;
this.layoutResource = layoutResource;
mAppend = append;
this.imgURLs = imgURLs;
}
#Override
public int getCount() {
return imgURLs.size();
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(layoutResource, parent, false);
holder = new ViewHolder();
holder.mProgressBar = (ProgressBar) convertView.findViewById(R.id.gridImageProgressbar);
holder.image = (SquareImageView) convertView.findViewById(R.id.gridImageView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final String imgURL = getItem(position);
Picasso.with(mContext).load(mAppend + imgURL).error(R.drawable.ic_person).into(holder.image, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
if (holder.mProgressBar != null) {
Picasso.with(mContext).load(mAppend + imgURL).into(holder.image);
holder.mProgressBar.setVisibility(View.GONE);
}
}
#Override
public void onError() {
if (holder.mProgressBar != null) {
Picasso.with(mContext).load(mAppend + imgURL).into(holder.image);
holder.mProgressBar.setVisibility(View.GONE);
}
}
});
return convertView;
}
private static class ViewHolder {
SquareImageView image;
ProgressBar mProgressBar;
}
}
< -------------- Method to set grid view ----------->
private void Directory() {
directories = FileSearch.getImageBuckets(getActivity());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity()
,android.R.layout.simple_spinner_item ,directories);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
directorySpinner.setAdapter(adapter);
directorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
Log.d(TAG, "onItemSelected: selected" + directories.get(position));
setGridView(directories.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void setGridView(String selectedDir){
Log.d(TAG, "setGridView: Dir chosen");
final ArrayList<String> imageURL = FileSearch.getImagesByBucket(getActivity() ,selectedDir);
int gridWidth = getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth/NUM_GRID_COLOUMN;
gridView.setColumnWidth(imageWidth);
GridImageAdapter adapter = new GridImageAdapter(getActivity() , R.layout.grid_image_layout ,append , imageURL);
gridView.setAdapter(adapter);
}

Android ArrayList Adapter doesn't show the ListView

I have an ArrayList to represent in a ListView by an Adapter:
private ArrayList <Contact> listContacts = new ArrayList <Contact> ();
This is the (simple) Contact Class:
public class Contact {
String pic;
String name;
String surname1;
String surname2;
String phonenumber;
}
And this is the Adapter Class:
public class ContactsAdapter extends ArrayAdapter<Contact> {
private static class ViewHolder {
ImageView pic;
TextView name;
TextView surname1;
TextView surname2;
TextView phonenumber;
}
Context context;
public ContactsAdapter(Context context, int textViewResourceId, ArrayList<Contact> items) {
super(context, textViewResourceId, items);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(this.getContext())
.inflate(R.layout.layout_contact, parent, false);
holder = new ViewHolder();
holder.pic= (ImageView) convertView.findViewById(R.id.pic);
holder.name= (TextView) convertView.findViewById(name);
holder.surname1= (TextView) convertView.findViewById(R.id.surname1);
holder.surname2= (TextView) convertView.findViewById(R.id.surname2);
holder.phonenumber= (TextView) convertView.findViewById(R.id.phonenumber);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Contact item = getItem(position);
if (item!= null) {
int idImage = context.getResources().getIdentifier(item.pic, "drawable", context.getPackageName());
holder.pic.setImageResource(idImage);
holder.name.setText(item.name);
holder.surname1.setText(item.surname1);
holder.surname2.setText(item.surname2);
holder.phonenumber.setText(item.phonenumber);
}
return convertView;
}
}
The MainActivity is like this:
public class MainActivity extends ListActivity {
private ArrayList <Contact> listContacts = new ArrayList <Contact> ();
ContactsAdapter contactsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean result = loadListFromFiles();
if (result) {
loadContacts();
}
}
private void loadContacts() {
contactsAdapter = new ContactsAdapter(getApplicationContext(), R.layout.activity_main, listContacts);
setListAdapter(contactsAdapter);
}
The loadListFromFiles code:
private boolean loadListFiles(){
boolean result = false;
Context context = getApplicationContext();
File path = context.getFilesDir();
File[] files = path.listFiles();
Log.d("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
Log.d("Files", "FileName:" + files[i].getName());
result = loadFile(files[i].getName());
}
return resultado;
}
private boolean loadFile(String fileName) {
String[] arrayContact = new String[4];
try
{
BufferedReader fin =
new BufferedReader(
new InputStreamReader(
openFileInput(fileName)));
int i = 0;
String line= "";
while ((line= fin.readLine()) != null) {
arrayContact[i] = linea;
i++;
}
fin.close();
Contact contact = new Contact();
contact.pic = arrayContact[3];
contact.name= arrayContact[0];
contact.surname1 = arrayContact[1];
contact.surname2 = arrayContact[2];
contact.phonenumber= arrayContact[3];
listContacts.add(contact);
return true;
}
catch (Exception ex)
{
Log.e("Files", "Error to read file by memory");
return false;
}
}
The ArrayList is right, but the layout don't show anything.
Override getCount() and getItem() methods to return count and contact item.
#Override
public int getCount() {
if(items == null)
return 0;
return items.size();
}
#Override
public Contact getItem(int i) {
return items.get(i);
}
Also, create one variable items in Adapter class and assign it to parameter passed to adapter constructor.
ArrayList<Contact> items;
public ContactsAdapter(Context context, int textViewResourceId, ArrayList<Contact> items) {
super(context, textViewResourceId, items);
this.context = context;
this.items = items;
}

android: How to get album art Image from 'Uri' using Glide?

I'm trying to get Image from Uri using glide but what i'm not getting an Image.
Model class - AlbumData
public class AlbumData {
private long id;
public String title;
public String description;
public Uri imageId;
public long getID() {
return id;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
/*public int getImageId() {
return imageId;
}
*/
public Uri getArtwork(){return imageId;}
public Bitmap getArtworkBitmap(Context ctx) {
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(ctx.getContentResolver(), imageId);
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
public AlbumData(long id, String title, String description, Uri imageId) {
this.id = id;
this.title = title;
this.description = description;
this.imageId = imageId;
}}
RecyclerView - AlbumRecyclerViewAdapter
public class AlbumRecyclerViewAdapter extends RecyclerView.Adapter<AlbumRecyclerViewAdapter.CustomViewHolder> {
private final String TAG = "test1";
Songs myTab;
MediaPlayer mediaPlayer;
public List<AlbumData> list = Collections.emptyList();
Context context;
public AlbumRecyclerViewAdapter(List<AlbumData> list, Context context, Songs myTab) {
this.list = list;
this.context = context;
this.myTab = myTab;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View songView = LayoutInflater.from(parent.getContext()).inflate(R.layout.album_custom_row, parent, false);
CustomViewHolder myHolder = new CustomViewHolder(songView, context, list);
return myHolder;
}
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
AlbumData album = list.get(position);
//Use the provided View Holder on the onCreateViewHolder method to
//Populate the current row on the RecyclerView
holder.getItemId();
holder.title.setText(list.get(position).title);
holder.description.setText(list.get(position).description);
//holder.imageView.setImageResource(list.get(position).imageId);
Bitmap bitmap = null;
/*try {
bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), album.getArtwork());
holder.imageView.setImageBitmap(bitmap);
} catch (Exception exception) {
// log error
}
*/
Glide.with(context).load(Uri.parse("file://" + album.getArtwork())).asBitmap().skipMemoryCache(true).into(holder.imageView);
}
#Override
public int getItemCount() {
//returns the number of elements the RecyclerView will displaye
return list.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
//Insert a new item to the RecyclerView on a predefined position
public void insert(int position, AlbumData data) {
list.add(position, data);
notifyItemChanged(position);
}
public void remove(AlbumData data) {
int position = list.indexOf(data);
list.remove(position);
notifyItemRemoved(position);
}
public static class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CardView cv;
TextView title;
TextView description;
ImageView imageView;
Context context;
List<AlbumData> list = new ArrayList<AlbumData>();
public CustomViewHolder(View itemView, Context context, List<AlbumData> list)
{
super(itemView);
this.context = context;
this.list = list;
this.itemView.setOnClickListener(this);
cv = (CardView) itemView.findViewById(R.id.cardView);
title = (TextView) itemView.findViewById(R.id.playList_name);
description = (TextView) itemView.findViewById(R.id.album_artist);
imageView = (ImageView) itemView.findViewById(R.id.imageView1);
}
#Override
public void onClick(View view) {
int position = getAdapterPosition();
AlbumData list = this.list.get(position);
}
}}
Fragment class - SongFragment
public class Songs extends Fragment {
final public static Uri sArtworkUri = Uri
.parse("content://media/external/audio/albumart");
private MediaPlayer mp;
private Intent playIntent;
private boolean musicBound = false;
private static final String KEY_LAYOUT_MANAGER = "layoutManager";
private RecyclerView mRecyclerView;
private AlbumRecyclerViewAdapter mAdapter;
protected List<AlbumData> songsList;
private enum LayoutManagerType {
GRID_LAYOUT_MANAGER,
LINEAR_LAYOUT_MANAGER
}
protected LayoutManagerType mCurrentLayoutManagerType;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize dataset, this data would usually come from a local content provider or
// remote server.
//fill_with_data();
//Instantiate the list
songsList = new ArrayList<AlbumData>();
getSongList();
Collections.sort(songsList, new Comparator<AlbumData>() {
public int compare(AlbumData a, AlbumData b) {
return a.getTitle().compareTo(b.getTitle());
}
});
}
public Songs() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_songs, container,
false);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;
if (savedInstanceState != null) {
// Restore saved layout manager type.
mCurrentLayoutManagerType = (LayoutManagerType) savedInstanceState
.getSerializable(KEY_LAYOUT_MANAGER);
}
mAdapter = new AlbumRecyclerViewAdapter(songsList, getContext(), Songs.this);
// Set CustomAdapter as the adapter for RecyclerView.
mRecyclerView.setAdapter(mAdapter);
return rootView;
}
public void getSongList() {
//retrieve song info
ContentResolver musicResolver = getActivity().getContentResolver();
Uri musicUri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
if (musicCursor != null && musicCursor.moveToFirst()) {
//get columns
int titleColumn = musicCursor.getColumnIndex
(MediaStore.Audio.Albums.ALBUM);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Albums._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Albums.ARTIST);
//int imageColumn = musicCursor.getColumnIndex
// (MediaStore.Audio.Albums.ALBUM_ART);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
//int thisAlbum = (int) musicCursor.getLong(imageColumn);
Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, thisId);
songsList.add(new AlbumData(thisId, thisTitle, thisArtist, albumArtUri));
}
while (musicCursor.moveToNext());
musicCursor.close();
}
}}
Though I commented out the bitmap section in BindViewHolder as when i using that method, it makes recyclerView slow.
So trying to use glide but I don't know why i'm not getting image. Any help would be precious.!
You are using Uri in ImageId, get string from ImageId like below, hope it will work
Glide.with(this)
.load(list.get(position).imageId)
.centerCrop()
.placeholder(R.mipmap.ic_launcher)
.crossFade()
.into(logoIv);
for simple load
Glide.with(this).load("uri")
.placeholder(R.mipmap.ic_launcher)
.into(logoIv);
and round imageview using glide
Glide.with(this)
.load("uri")
.centerCrop()
.placeholder(R.mipmap.ic_launcher)
.crossFade()
.into(logoIv);
Glide.with(this).load(uri.getPath())
.placeholder(R.mipmap.ic_launcher)
.into(logoIv);
uri.getPath() should solve the issue.
Try this one.
Glide.with(mContext)
.load(new File(pictureUri.getPath())) // Uri of the picture
.into(logoIv);
Finally I got the answer -
Glide.with(context).load(list.get(position).imageId).
placeholder(R.drawable.ic_action_movie).into(holder.imageView);

Load image From basic gallery To imageview in Custom Listview/

First, I'm sorry for my bad English. please excuse me. :)..
I tried to make a custom listView which has ImageView, TextViews, and Button.
So, I want to change image after I click ImageView in listview and select image from gallery. But.. It's really hard to me.
In my code(customAdapter)Adapter class is not Activity, So it cannot call startActivityForResult directly. So I make new Activity(It is GalleryImage.java). and call startActivity using that class. But it is not working. What should I do...
(Error occur in ImageView.setOnClickListner, getView of PhoneBookAdapter)
CustomAdapter Source Code
//..skip import
public class PhoneBookAdapter extends BaseAdapter implements Filterable {
ArrayList<Contact> m_people = new ArrayList<Contact>();
ArrayList<Contact> m_filteredPeople = new ArrayList<Contact>();
private ItemFilter mFilter = new ItemFilter();
private class CustomHolder {
ImageView m_photo;
TextView m_name, m_phone;
Button m_call, m_reserve;
}
public PhoneBookAdapter(ArrayList<Contact> people) {
m_people = people;
m_filteredPeople = people;
}
#Override
public int getCount() {
return m_filteredPeople.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// final int pos = position;
final Context context = parent.getContext();
final TextView phone;
final ImageView photo;
TextView name;
Button call, reserve;
final int pos = position;
CustomHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.phonebook_list_item, parent,
false);
photo = (ImageView) convertView.findViewById(R.id.iv_photo);
name = (TextView) convertView.findViewById(R.id.tv_name);
phone = (TextView) convertView.findViewById(R.id.tv_phonenumber);
call = (Button) convertView.findViewById(R.id.btn_call);
reserve = (Button) convertView.findViewById(R.id.btn_reserve);
holder = new CustomHolder();
holder.m_photo = photo;
holder.m_name = name;
holder.m_phone = phone;
holder.m_call = call;
holder.m_reserve = reserve;
convertView.setTag(holder);
} else {
holder = (CustomHolder) convertView.getTag();
photo = holder.m_photo;
name = holder.m_name;
phone = holder.m_phone;
call = holder.m_call;
reserve = holder.m_reserve;
}
//photo.setImageResource(m_filteredPeople.get(position).getImage());
name.setText(m_filteredPeople.get(position).getName());
phone.setText(m_filteredPeople.get(position).getNumber());
photo.setOnClickListener(new OnClickListener() {
Activity activity;
int SELECT_IMAGE=90;
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
intent.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GalleryImage gallery = new GalleryImage(SELECT_IMAGE, photo);
gallery.startActivityForResult(intent, SELECT_IMAGE);
}
});
call.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO make real phone call
Toast.makeText(context, "call " + phone.getText(),
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_CALL, Uri
.parse("tel:" + m_filteredPeople.get(pos).getNumber()));
context.startActivity(intent);
}
});
reserve.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "reserve " + phone.getText(),
Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
#Override
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString();
FilterResults results = new FilterResults();
final ArrayList<Contact> m_IFpeople = m_people;
int count = m_IFpeople.size();
final ArrayList<Contact> n_people = new ArrayList<Contact>();
String filterableString;
if (filterString != null
&& filterString.trim().equalsIgnoreCase("") != true) {
// Whitespace와 null 제거
// for (int i = 0; i < count; i++) {
// filterableString = m_IFpeople.get(i).getName();
// if (filterableString.indexOf(filterString) >= 0) {
// n_people.add(m_IFpeople.get(i));
// }
// }
for (int i = 0; i < count; i++) {
filterableString = HangulUtils.getHangulInitialSound(
m_IFpeople.get(i).getName(), filterString);
if (filterableString.indexOf(filterString) >= 0) {
n_people.add(m_IFpeople.get(i));
}
}
results.values = n_people;
results.count = n_people.size();
} else {
results.values = m_IFpeople;
results.count = m_IFpeople.size();
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
m_filteredPeople = (ArrayList<Contact>) results.values;
notifyDataSetChanged();
}
}
}
GalleryImage.java(new Activity)
//..skip import
public class GalleryImage extends Activity {
final int REQ_CODE_SELECT_IMAGE;
ImageView photo;
public GalleryImage(int codeImage, ImageView m_photo) {
REQ_CODE_SELECT_IMAGE = codeImage;
photo = m_photo;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Intent intent = new Intent(Intent.ACTION_PICK);
// intent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
// intent.setData(
// android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// startActivityForResult(intent, REQ_CODE_SELECT_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_CODE_SELECT_IMAGE && resultCode == Activity.RESULT_OK
&& data != null) {
final Uri selectImageUri = data.getData();
final String[] filePathColumn = { MediaStore.Images.Media.DATA };
final Cursor imageCursor = this.getContentResolver()
.query(selectImageUri, filePathColumn, null, null, null);
final int columnIndex = imageCursor.getColumnIndex(filePathColumn[0]);
final String imagePath = imageCursor.getString(columnIndex);
imageCursor.close();
final Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
}
}
}
Thanks for your help. :D.
Solution here is not creating a new instance of Activity but being able to access already existing instance created by Android Framework. Instance of an Activity should never be created by an application programmer.
Best approach would be to add a parameter of type Activity to the constructor of PhoneBookAdapter. Such as:
private Activity activity;
public PhoneBookAdapter(Activity activity, ArrayList<Contact> people) {
this.activity = activity;
m_people = people;
m_filteredPeople = people;
}
You can than then call activity.startActivityForResult on this instance of Activity.
You then pass in the instance of Activity when you create the adapter. In Activity you would simply pass this and in Fragment you can obtain the instance by calling getActivity() method of Fragment class.
As to processing the result of the started Activity you would need to implement this in the Activity or Fragment in which you display the list.

Slow loading images from sdcard to gridview

I've been trying to create multiple image chooser, everything works fine, but the grid scroll is very lazy and slow, I've been tried to use different libraries for image loading in getView() (Picasso,aquery..)
but its no difference ,even with asynctask, that's my code:
Main:
public class Media extends ActionBarActivity {
private AQuery aq;
GridView myGridView;
MyAdapter mySimpleCursorAdapter;
boolean isOddClicked = true;
static String img=null;
final Uri srcUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
final String srcData = MediaStore.Images.Media.DATA;
final String srcImgId = MediaStore.Images.Media._ID;
final Uri thumbUri = MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI;
final String thumb_DATA = MediaStore.Images.Thumbnails.DATA;
final String thumb_IMAGE_ID = MediaStore.Images.Thumbnails.IMAGE_ID;
ArrayList<String> al = new ArrayList<String>(5);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.media);
//Always show the menu
try {
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if(menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception ex) {}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
myGridView = (GridView)findViewById(R.id.gridview);
//
CursorLoader cursorLoader = new CursorLoader(
this,srcUri,null,null,null,MediaStore.Images.Media.DATE_TAKEN+ " DESC");
//
Cursor cursor = cursorLoader.loadInBackground();
//
int[] to = {android.R.id.text1};
String[] from = {MediaStore.MediaColumns.TITLE};
mySimpleCursorAdapter = new MyAdapter(
this,android.R.layout.simple_list_item_1,
cursor,from,to,CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
//
myGridView.setAdapter(mySimpleCursorAdapter);
myGridView.setOnItemClickListener(myOnItemClickListener);
}
OnItemClickListener myOnItemClickListener = new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Cursor cursor = mySimpleCursorAdapter.getCursor();
cursor.moveToPosition(position);
int int_ID = cursor.getInt(cursor.getColumnIndex(MediaStore.Images.Media._ID));
}
};
private Bitmap getThumbnail(int id){
String[] thumbColumns = {srcData, srcImgId};
CursorLoader thumbCursorLoader = new CursorLoader(
this,srcUri,thumbColumns,srcImgId + "=" + id,null,null);
Cursor thumbCursor = thumbCursorLoader.loadInBackground();
Bitmap thumbBitmap = null;
if(thumbCursor.moveToFirst()){
int thCulumnIndex = thumbCursor.getColumnIndex(srcData);
String thumbPath = thumbCursor.getString(thCulumnIndex);
Toast.makeText(getApplicationContext(),thumbPath,Toast.LENGTH_LONG).show();
thumbBitmap = BitmapFactory.decodeFile(thumbPath);
//Create a Dialog to display the thumbnail
AlertDialog.Builder thumbDialog = new AlertDialog.Builder(Media.this);
ImageView thumbView = new ImageView(Media.this);
thumbView.setImageBitmap(thumbBitmap);
LinearLayout layout = new LinearLayout(Media.this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(thumbView);
thumbDialog.setView(layout);
thumbDialog.show();
}else{
Toast.makeText(getApplicationContext(),"NO Thumbnail!",Toast.LENGTH_LONG).show();
}
return thumbBitmap;
}
public class MyAdapter extends SimpleCursorAdapter{
Cursor myCursor;
Context myContext;
public MyAdapter(Context context, int layout, Cursor c, String[] from,int[] to, int flags) {
super(context, layout, c, from, to, flags);
myCursor = c;
myContext = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater=getLayoutInflater();
convertView =inflater.inflate(R.layout.media_row, parent, false);
holder = new ViewHolder();
holder.thumbnail = (ImageView)convertView.findViewById(R.id.thumb);
holder.title = (CheckBox) convertView.findViewById(R.id.itemCheckBox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
myCursor.moveToPosition(position);
final int myID = myCursor.getInt(myCursor.getColumnIndex(MediaStore.Images.Media._ID));
final String[] thumbColumns = {srcData ,srcImgId};
CursorLoader thumbCursorLoader = new CursorLoader(
myContext,srcUri,thumbColumns,srcImgId + "=" + myID,null,null);
Cursor thumbCursor = thumbCursorLoader.loadInBackground();
if(thumbCursor.moveToFirst()){
final int thCulumnIndex = thumbCursor.getColumnIndex(thumb_DATA);
final String thumbPath = thumbCursor.getString(thCulumnIndex);
Bitmap o = MediaStore.Images.Thumbnails.getThumbnail(getApplicationContext().getContentResolver(), myID, Images.Thumbnails.MICRO_KIND, null);
//holder.thumbnail.setImageBitmap(o);
//Phase II:
String uri = null;
Cursor cursor = MediaStore.Images.Thumbnails.queryMiniThumbnail(
getContentResolver(), myID,
MediaStore.Images.Thumbnails.MINI_KIND,null );
if( cursor != null && cursor.getCount() > 0 ) {
cursor.moveToFirst();//**EDIT**
uri = cursor.getString( cursor.getColumnIndex( MediaStore.Images.Thumbnails.DATA ) );
}
MediaAsync loadAsync = new MediaAsync(getApplicationContext(), holder.thumbnail);
loadAsync.onPostExecute(thumbPath);
/*
holder.thumbnail.setOnClickListener(new OnClickListener(){
public void onClick(View v){
img = thumbPath;
al.add(thumbPath);
if (holder.title.isChecked()) {
holder.title.setChecked(false);
holder.thumbnail.setBackgroundResource(0);
}else{
holder.title.setChecked(true);
holder.thumbnail.setBackgroundResource(R.drawable.media_row_border);
}
}
});
*/
}
return convertView ;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.media, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
}
else if (id == R.id.done) {
Intent main = new Intent(this, Main.class);
main.putStringArrayListExtra("media_lst", al);
startActivity(main);
}
return super.onOptionsItemSelected(item);
}
private static class ViewHolder {
ImageView thumbnail;
CheckBox title;
}
}
mediaAsynce :
public class MediaAsync extends AsyncTask<String,String, String>{
private ImageView mImageView;
private Context mContext;
public MediaAsync(Context context,ImageView imageView) {
mImageView = imageView;
mContext = context;
}
#Override
protected String doInBackground(String... params) {
String url = params[0].toString();
return url;
}
#Override
protected void onPostExecute(String result) {
Uri uri = Uri.fromFile(new File(result));
Picasso.with(mContext)
.load(uri)
//.resize(100, mWidth)
.into(mImageView);
// AQuery aq = new AQuery(mContext);
// aq.id(mImageView).image(result, true, true, 0, R.drawable.ic_launcher);
}
}
As you said you have tried picasso library it should work
Just try once again using picassso like this Async task and all is not required
Just create a simple adapter and load images.
public class GridViewDynamicAdapter extends BaseDynamicGridAdapter {
ImageDetails details;
public static List<ImageDetails> list;
public GridViewDynamicAdapter(Context context, List<ImageDetails> items,
int columnCount) {
super(context, items, columnCount);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
CheeseViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.item_grid, null);
holder = new CheeseViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (CheeseViewHolder) convertView.getTag();
}
if (position == getCount() - 1) {
ImageApplication.fromRecorderPaths = (List<ImageDetails>) getItems();
}
details = (ImageDetails) getItem(position);
// Log.d("Setting=", details.path);
holder.build(getContext(), details.path);
return convertView;
}
private class CheeseViewHolder {
private ImageView image;
private CheeseViewHolder(View view) {
image = (ImageView) view.findViewById(R.id.item_img);
}
void build(final Context context, String title) {
Picasso.with(context).load(new File(title)).centerCrop()
.resize(150, 150).error(R.drawable.ic_launcher).into(image);
}
}
}
OR
Try this example

Categories

Resources