Exercise : 23
Create an application
to pick up any image from the native application gallery and display it on the screen.
Screen Shot:
XML :
main.xml :
main.xml :
JAVA :
TwentythreeActivity.java :
package kmn.Twentythree;
import java.io.File;
import java.io.FileInputStream;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore.Images.Media;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class TwentythreeActivity extends Activity
{
/** @author Y@@D **/
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try
{
String[] projection={Media.DISPLAY_NAME, Media.DATA, Media.SIZE};
Cursor c=managedQuery(Media.EXTERNAL_CONTENT_URI, projection, null, null, null);
ImageView ivImage=(ImageView)findViewById(R.id.myImg);
File file = null;
String imgName = null ;
if(c.getCount()>0)
{
while(c.moveToNext())
{
file=new File(c.getString(1)); //after completing loop, it take last image from native Gallery to display.
imgName=c.getString(0);
}
c.close();
FileInputStream fis=new FileInputStream(file);
byte[] buffer=new byte[fis.available()];
fis.read(buffer);
Bitmap bm=BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
TextView txtTitle=(TextView)findViewById(R.id.txtTitle);
txtTitle.setText(imgName.toString());
ivImage.setImageBitmap(bm);
}
}
catch(Exception e)
{
Toast.makeText(TwentythreeActivity.this, "Error: "+e, Toast.LENGTH_LONG).show();
}
}
}
Step To store images on sdcard and
scanning in to the emulator.
1)click on push on file onto the
device button
2)now select the iamge an upload it
3)goto the "Dev Tools" on
your emulator and click on "Media Scanner".
4)now check your image in
"gallery"
5)run your program
Enjoy..........
