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! :)

Tuesday, January 29, 2013

How to debug Android application using eclipse


At the first time I tried Android programming, I don't know how to debug and you know, it's awful when my app get a bug. And then a long time I tried, I found it so I decide to write this topic (it's maybe my first note) to show you how to debug an android program :) . 
As we know, debugging is one of the most important skills in programming. Within debugging, we can see the value of a variable, a string, the running thread, and how the programing runs step by step.
There are two ways to debug: one is using logcat, another is breakpoints.

1. Using logcat: This is a nice and quick way to exchange information from the application on your device and the development computer.
First of all, we you import android.ulti.Log in your project (It’s not important because we can quick import by using Ctrl + Space). And then, you can call the static class Log from your project to log. The list below shows you some different levels of Logcat. When debugging we’ll just use Debug (D) to log the process. When logging some information, we’ll use Info (I),…
  • V — Verbose (lowest priority)
  • D — Debug
  • I — Info
  • W — Warning
  • E — Error
  • F — Fatal
  • S — Silent (highest priority, on which nothing is ever printed)
Now let get start…! Take a simple demo for android development: Hello world.
This is my code.

We use Log.i(DEBUG_TAG, "String value is: " + hello); to put our information into Logcat. After we run this program, we can see this line as the figure below:

If you don’t see this tab, you can go to Window > Show view > Logcat.
This helps you to find which line is a bug in your program. When your program get stuck, you can guess a put a Log.i(DEBUG_TAG, "This is mark");code into your project, and then you run program again a the see the Logcat display if a line Log.i(DEBUG_TAG, "This is mark"); you have put is in the Logcat list or not. If it is, the code you wrote from the beginning of  your project to this line is fine and you only check all codes after this line. If it is not, the bug is in some code before this line and you check this codes. Or you can use Logcat to see value of a variable in your project to make sure it is what you guess.

2. Using breakpoint: This is a powerful way that Eclipse support to you to debug your application.
To use it, you need some breakpoints in your project first. This means we can add a point to our code where we tell android to halt executing and tell us all he knows about the current state of the application. You can create a breakpoint by clicking to a bar in the left side of your codes. Here I have some:

And then, you click icon  . Then the eclipse will ask you if you want to open debug view. Now I will show you how to navigate through the application within 2 button and 3 arrows in the top.
  •  Resume : It means you don’t want to debug and you want your application keep running. You use it when you debug and know a bug is or it has no bug and you want to see the result.

  • Disconnect : It means you stop running your application anymore because you have found the bug is.
  • The first arrow means is step in (F5), this is good when you used a breakpoint on a function. With this arrow you will step into the function.
  • The second arrow means step over (F6), with this arrow you will go to the next line of code in your application.
  • The last  code is step return (F7), with this arrow you can return to previous states.


You can switch between debug view and java view by using the buttons on the right-top of your windows.

Ok, this was my little article about debugging. For experienced android programmers this is very easy, but for beginners this will save you a lot of work.