Sunday, February 10, 2013

How to save an image to directory in sdcard and update to gallery

This is a short tutorial on how to save an image to directory in sdcard and then update it into gallery.
In this tutorial, I will get an image from drawable folder, then save it to directory in sdcard and update into gallery.

First create a new project with main.xml as shown below:


    

Open MainActivity.java and add a method as shown below:
private void savePicture(Bitmap bm, String imgName)
 {  
  OutputStream fOut = null;
  String strDirectory = Environment.getExternalStorageDirectory().toString();

  File f = new File(strDirectory, imgName);
  try {
   fOut = new FileOutputStream(f);
   
   /**Compress image**/
   bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
   fOut.flush();
   fOut.close();

   /**Update image to gallery**/
   MediaStore.Images.Media.insertImage(getContentResolver(),
    f.getAbsolutePath(), f.getName(), f.getName());
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
After compressing, your image will be saved in mnt/sdcard/ with imgName. You can check it by using DDMS prespective. If you want to change where image saved, you can change strDirectory. It can be change to getExternalStoragePublicDirectory(Environment.<your_type>).toString() or your hard path in sdcard.

And the whole MainActivity.java. I set a listener to Button and call savePicture:
private Button saveBtn;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  
  saveBtn = (Button)findViewById(R.id.saveBtn);
  
  final Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.my_image);
   
  saveBtn.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    savePicture(bm, "image_name.jpg");
    Toast.makeText(getApplicationContext(), "Image saved...", Toast.LENGTH_SHORT).show();
   }
  });
 }
 
 private void savePicture(Bitmap bm, String imgName)
 {  
  OutputStream fOut = null;
  String strDirectory = Environment.getExternalStorageDirectory().toString();

  File f = new File(strDirectory, imgName);
  try {
   fOut = new FileOutputStream(f);
   
   /**Compress image**/
   bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
   fOut.flush();
   fOut.close();

   /**Update image to gallery**/
   MediaStore.Images.Media.insertImage(getContentResolver(),
    f.getAbsolutePath(), f.getName(), f.getName());
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

Note that, in my project, I added a image named my_image.jpg and I just simply called it as a resource. You can make your own by creating a new Bitmap variable and use it.

We also add WRITE_EXTERNAL_STORAGE permission in Manifest.xml:


Finally, open Gallery and check if it works!

Friday, February 8, 2013

Populate Android listview with text and image

This is a simple tutorial on how to populate android listview with text and image. For simplicity I use static data in this tutorial, but you can make it dynamic.
Now let's start with a new android project.
Open main.xml and add a listview element as show below (in this, I use default)


    
    


Create list.xml and put it into res/layout/ (main.xml 's folder). This file is used for displaying a row in your listview:


    

    


 Then, open MainActivity (or as your define). Define some variables, we will use later in our class as shown below:
 private LayoutInflater mInflater;
 private ListView mListView;
 private Vector data;
Vector is used for storing our data. LayoutInflater class is used to instantiate layout XML file into its corresponding View objects. Use getSystemService(String) to retrieve a standard LayoutInflater instance that is already hooked up to the current context and correctly configured for the device you are running on.

The whole MainActivity:
private static int[] resID = new int[]{R.drawable.apple, R.drawable.orange};
  
 private LayoutInflater mInflater;
 private ListView mListView;
 private Vector data;
  
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  
  mListView = (ListView)findViewById(R.id.listView1);
  mInflater = (LayoutInflater)getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
  
  data = new Vector();
  data.add("Apple");
  data.add("Orange");
  
  MyAdapter adapter = new MyAdapter(this, R.layout.list, R.id.textView1, data);
  
  mListView.setAdapter(adapter);
  mListView.setTextFilterEnabled(true);
  mListView.setOnItemClickListener(new OnItemClickListener() {

   @Override
   public void onItemClick(AdapterView arg0, View arg1, int position,
     long id) {
    Toast.makeText(getApplicationContext(), "You have selected at item: " + position, Toast.LENGTH_LONG).show();  
   }
  });
 }
 
 private class MyAdapter extends ArrayAdapter
 {

  public MyAdapter(Context context, int resource,
    int textViewResourceId, List objects) {
   super(context, resource, textViewResourceId, objects);
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
   MyView mView = null;
   TextView title = null;
   ImageView img = null;
   String rowData = getItem(position);
   
   if (convertView == null)
   {
    convertView = mInflater.inflate(R.layout.list, null);
    mView = new MyView(convertView);
    convertView.setTag(mView);
   }
   
   mView = (MyView)convertView.getTag();
   
   title = mView.getTitle();
   title.setText(rowData);
   
   img = mView.getImage();
   img.setImageResource(resID[position]);
   
   return convertView;
  }
  
  private class MyView {
   private View _row;
   private TextView _title;
   private ImageView _imgView;
   
   public MyView(View row)
   {
    _row = row;
   }
   
   public TextView getTitle()
   {
    if (_title == null)
     _title = (TextView)_row.findViewById(R.id.textView1);
    return _title;
   }
   
   public ImageView getImage()
   {
    if (_imgView == null)
     _imgView = (ImageView)_row.findViewById(R.id.imageView1);
    return _imgView;
   }
  }
 }
Done! Run it and feel your work! :)

Thursday, February 7, 2013

How to get image data from url



Here is my code to fetch image from an url and then display it into imageview in android (I use android 2.2.3)
  • main.xml layout:


    
    
        
    
    
    
  • MainActivity.java
public static String src_link = "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEizHvU0XODfjwRifjEZqSlbL7tLlgLVsEjUmgQnLIdtud9kr_Fm8NADiZeF-ajC5-7Um8za4iMM6mXwRAzHPGhyphenhyphenMIc_LCekHNtrDkouUI2SXospNb8DjkEAWDkPUqDBl8TIitJZ_MuTZ3c/h120/images.png";
 
 public ImageView imgView;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  
  imgView = (ImageView)findViewById(R.id.imageView1);
  imgView.setImageBitmap(fetchImage(src_link));
 }

 private Bitmap fetchImage(String urlstr) {
  Bitmap img = null;
  try {
   URL url;
   url = new URL(urlstr);
   HttpURLConnection c = (HttpURLConnection) url.openConnection();
   c.setDoInput(true);
   c.connect();
   InputStream is = c.getInputStream();
   img = BitmapFactory.decodeStream(is);
   return img;
  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return img;
 }

  • Finally, add permission in Manifest.xml:
 
 Yep! This is end of this topic. Hope you enjoy it! :)