Skip to main content

Load images from external storage into GridView in Android using Picasso library

Activity:


public class Gallery extends ActionBarActivity {

public GridView imagegrid;
private ArrayList<String> imageUrls;
private ImagesAdapter imageAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
init();
}

private void init() {
final String[] columns= {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID};
final String orderBy= MediaStore.Images.Media.DATE_TAKEN;
Cursor imageCursor= this.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy +" DESC");
this.imageUrls=new ArrayList<String>();
for(int i=0; i< imageCursor.getCount();i++){
imageCursor.moveToPosition(i);
int dataColumnIndex =imageCursor.getColumnIndex(MediaStore.Images.Media.DATA);
imageUrls.add(imageCursor.getString(dataColumnIndex));
}
 
imagegrid = (GridView) findViewById(R.id.GalleryViewLayout);

   DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int width=metrics.widthPixels;
int height=metrics.heightPixels;
float scalefactor = getResources().getDisplayMetrics().density * 100;
int number=width;
int col = (int) ((float) number / (float) scalefactor);
imagegrid.setNumColumns(col);
imageAdapter=new ImagesAdapter(this,imageUrls,width,height);
imagegrid.setAdapter(imageAdapter);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.gallery, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
}

Xml:


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.sachinsandbhor.gallerydemo.Gallery"
    tools:ignore="MergeRootFrame" >

    <GridView
        android:id="@+id/GalleryViewLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:numColumns="3" >
    </GridView>

</RelativeLayout>

Adapter:

public class ImagesAdapter extends BaseAdapter{

ArrayList<String> mList;
    LayoutInflater mInflater;
    Context mContext;
    SparseBooleanArray mSparseBooleanArray;
    int width,height;
    
    public ImagesAdapter(Context context, ArrayList<String> imageList, int Screenwidth, int Screenheight) {
        mContext = context;
        mInflater = LayoutInflater.from(mContext);
        mSparseBooleanArray = new SparseBooleanArray();
        mList = new ArrayList<String>();
        this.mList = imageList;
        this.width=Screenwidth;
        this.height=Screenheight;

    }
    

public void initialize() {
    mList.clear();
    final String[] columns= {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID};
final String orderBy= MediaStore.Images.Media.DATE_TAKEN;
Cursor imageCursor= mContext.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy +" DESC");
this.mList=new ArrayList<String>();
for(int i=0; i< imageCursor.getCount();i++){
imageCursor.moveToPosition(i);
int dataColumnIndex =imageCursor.getColumnIndex(MediaStore.Images.Media.DATA);
mList.add(imageCursor.getString(dataColumnIndex));
System.out.println("=====> Array path => "+mList.get(i));
}
imageCursor.close();
    }

    public ArrayList<String> getCheckedItems() {
        ArrayList<String> mTempArry = new ArrayList<String>();

        for(int i=0;i<mList.size();i++) {
            if(mSparseBooleanArray.get(i)) {
                mTempArry.add(mList.get(i));
            }
        }

        return mTempArry;
    }

    @Override
    public int getCount() {
        return mList.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) {
if(convertView == null) {
    convertView = mInflater.inflate(R.layout.galleryitem, null);
    }
    ImageView imageView = (ImageView) convertView.findViewById(R.id.thumbImage);
    float scalefactor = mContext.getResources().getDisplayMetrics().density * 100;
int number=width;
int columnsSize = (int) ((float) number / (float) scalefactor);
int newWidth=width/columnsSize;
int newHeight=height/4;
    Picasso.with(mContext).load("file://"+mList.get(position)).resize(newWidth,newHeight).centerCrop()
.placeholder(R.drawable.ic_launcher)
.into(imageView);
    return convertView;
}
OnCheckedChangeListener mCheckedChangeListener = new OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);
}
};
}

Custom xml :


<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/FrameLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ImageView
        android:id="@+id/thumbImage"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="5dp"
        android:scaleType="fitXY" />
</FrameLayout>

Add below line to AndroidManifest.xml

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


Screenshot:




Here is the sample Code



Comments

Popular posts from this blog

How to check internet connectivity in Android app using BroadcastReceiver

So let's get started with How to check internet connectivity in Android using BroadcastReceiver. For this post I'm using Kotlin language. Well lots of people are using simple method to get network connectivity using ConnectivityManager. But using that approach we will get network state only when we are calling that method. So how would I know that network state changed. This will achieved using BroadcastReceiver.  What is BroadcastReceiver? BroadcastReceiver uses Publish-Subscribe pattern. Android app can send and receive messages from Android system and other apps.  Android system sends broadcast when various system events occurred like device charging, network state changes. Apps can register to receive specific broadcasts. When a broadcast is sent, the system automatically routes broadcasts to apps that have subscribed to receive that particular type of broadcast. So for this scenario we need to add some changes in AndroidManifest.xml file - ...

How prevent the Android OS to take a screenshot of the app when it's being pushed into the background for security reasons

How to create custom title in Android Application

Custom title is nothing but a layout you bind to your application's title bar. MainActivity.java package com.example.customtitlebar; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.Window; import android.widget.Button; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.activity_main); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.customheader); init(); } private void init() { // TODO Auto-generated method stub Button Left=(Button)findViewById(R.id.header_left_btn); Left.setText("BACK"); Left.setTextColor(Color.GRAY); Button Title=(Button)findViewById(R.id.header_text); Title.setText("Scorecard"); Title.setTextColor(Color.GRAY); Button Right=(Button)findViewById(R.id.header_right_...