Set image dynamically by retrieving image name from a data source in android...

    Sometimes there may be situation,where we have the images in our project's drawable folder.But we have to set the images by getting the image name from a data source.In normal condition we can use "R.drawable.imageName"  and the image is set. But in this as we get the image name at run time,we have to set the images dynamically.
     So in this situation first we have to retrieve the image name from the data source(It can be a SQLite database or any other data source).Store it in a string variable.Note here,we have to store  the image name here(not with the extension).So if the data source gives you image name with extension then cut the name from the extension.We need "imageName" here,not "imageName.png".So follow the code below...
try {                
                Class<drawable> res = R.drawable.class;
                if(str!=null){                                    
                Field field = res.getField(str);
                int drawableId = field.getInt(null);
                bengalidaypng.setImageResource(drawableId);               
                }
            }
            catch (Exception e) {
                      System.out.println("Image not found in drawable folder");
            } 
         Here "str" is the string variable that hold the imageName retrieved from a data source.If the image with desired name not found in the project's drawable folder then the "catch" block will execute.Hope it is very easy to understand.Feel free to make a comment if you have a doubt.

Want to run a Progress dialog in your Android apps? Here is the way...

            Hey loving readers,in this post I will discuss about the Progress Dialog features in a android application.Usually we use it,when our application needs some time to process a request or waiting for a resource like internet connection or anything.So here I build a demo application to show you, how the progress dialog actually works.
            In this application we take a button.When we press the button,the progress dialog will appear and it also give the users information that what the application is doing in the background.Int this application we just count 0-900 value in background.You can show the counting in the logcat view(Eclipse IDE is used here).The progress dialog also give some information,when and what the application is counting.

screenshot 1
screenshot 2
screenshot 3

     After the counting process is over,the progress dialog will be dismissed and a toast will be  shown to inform the user that the counting process is completed.Then  the button can be pressed again and the counting process will begin.So simple! Isn't it?
     So lets take a look at the xml layout.It is really simple one with a button only with the name "Counting Button". Lets take a look....

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <Button
        android:id="@+id/button1"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:text="Counting Button" 
        android:layout_gravity="center" 
        android:layout_marginTop="100dp"
        />
</LinearLayout>

           Now it;s time for some java code,that actually runs the progress dialog.Note here, that we don't define a Progress Dialog widget in the xml file.This is not provided by the ADT plugin(Eclipse platform) as we don't need a Progress dialog at start up.We need it,when an event occurs,that requires some time.So we define it in the java file.Lets take a look....

package com.androidcookers.progressdialog;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
/**
 * @author www.androidcookers.co.cc
 * {@link www.androidcookers.co.cc}
 *
 */
public class MyProgressbarActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        final Button btn=(Button)findViewById(R.id.button1);
        btn.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {    
    new Progress().execute("ASD");
   }
  });
    }
    private class Progress extends AsyncTask{
     ProgressDialog pd;
     int count=0;
  public void onPreExecute(){
   pd=new ProgressDialog(MyProgressbarActivity.this);   
   pd.show();
  }
  @Override
  protected String doInBackground(String... params) {
   publishProgress(new Integer(1));
   for(int i=0;i<=300;i++){
    System.out.println(i);
   }
   publishProgress(new Integer(1));
   for(int i=301;i<=600;i++){
    System.out.println(i);
   }
   publishProgress(new Integer(1));
   for(int i=601;i<=900;i++){
    System.out.println(i);
   }
   pd.dismiss();//dismiss the progress dialog here...
   return null;
  }
  protected void onProgressUpdate(Integer... values){
   count++;
   if(count==1){
    pd.setMessage("Now counting 0 to 300...");  
   }
   if(count==2){
    pd.setMessage("Now counting 301 to 600...");
   }
   if(count==3){
    pd.setMessage("Now counting 601 to 900...");
   }
  }
  protected void onPostExecute(String result) {
   Toast.makeText(MyProgressbarActivity.this,"Counting completed!", Toast.LENGTH_LONG).show();
  }
    }     
}

             In this java file,first we initialize the button and when the button is pressed the Progress class is called.This class extends AsyncTask.That enable us to run a thread in the background,that process the counting task.It make us to implement the doInBackground() method.In this method the actual counting process is defined.We additionally define three other methods named onPreExecute(),onProgressUpdate() and the onPostExecute().
             The first one[onPreExecute()] makes a progress dialog object and initialize it. onProgressUpdate() method give us information when and what is counting. onPostExecute() method defines what will happen when the Progress dialog will be dismissed.In this application we showed a toast here.
             Don't forget to dismiss the progress dialog at the end of doInBackground() method by calling the dismiss method.Otherwise the progress dialog will continuously rotate even the background counting process is over.

Professional Android™ 2 Application Development by Reto Meier


Professional Android™ 2 Application Development by Reto Meier:
• Reviews Android as a development platform and best practices
for mobile development
• Provides an in-depth look at the Android application components
• Details creating layouts and Views to produce compelling resolution
independent user interfaces
• Examines Intents and Content Providers for sharing data
• Introduces techniques for creating map-based applications and using
location-based services such as GPS
• Looks at how to create and use background Services, Notifications,
and Alarms
• Demonstrates how to create interactive homescreen components
• Explores the Bluetooth, telephony, and networking APIs
• Examines using hardware, including the camera and sensors such
as the compass and accelerometers


Download now