April 29, 2011

How to use AsyncTask to load images on Android

If you are looking for an example of Haw to load an image from web you can find it here. If you need that the images were loaded asynchronously, find below an full example.















Add into your AndroidManifest.xml this permission:



main.xml


 
 

 
  
  
 
 
  
  
 
 



main.java
package com.blog.usingasynctask;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

public class main extends Activity {
 
 final String[] links = {
      "http://www.android.com/media/wallpaper/gif/android_logo.gif",
      "http://www.android.com/media/wallpaper/gif/cupcake_2009.gif",
      "http://www.android.com/media/wallpaper/gif/donut_2009.gif",
      "http://www.android.com/media/wallpaper/gif/eclair_2009.gif",
      "http://www.android.com/media/wallpaper/gif/androids.gif"          
    };
 TextView count; 
 int id;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        id = 0;
        count = (TextView) findViewById(R.id.textView2);  
        startDownload( id );
    }
    
    public void startDownload(int id){
     // calling the asynchronous task 
     new ImageLoadingTask().execute();
    };
    
    public void displayImage(Drawable image){
     
     ImageView iv = null;
   
     switch (id){
      case 0 : iv = (ImageView) findViewById(R.id.imageView1);
       break;
      case 1 : iv = (ImageView) findViewById(R.id.imageView2);
       break;
      case 2 : iv = (ImageView) findViewById(R.id.imageView3);
    break;
      case 3 : iv = (ImageView) findViewById(R.id.imageView4);
    break;
      case 4 : iv = (ImageView) findViewById(R.id.imageView5);
    break;
     
     }
     
     iv.setImageDrawable(image);
     id++;
     if (id < 5) new ImageLoadingTask().execute();
    };

 public class ImageLoadingTask extends AsyncTask{

  @Override
  protected void onPreExecute(){   
   count.setText( count.getText() + " ... in progress image "+ id+1 );
  }
  
  @Override
  protected Drawable doInBackground(Void... params) {   
   //write here code that can take a long time   
   Drawable image = ImageOperations(getApplicationContext() ,links[id], id +".gif");    
   //publishProgress calls onProgressUpdate to update somthing on UI
   publishProgress();   
   
   return image;
  }
  
  @Override
  // Call this method when doInBackground is working to update the progress 
  protected void onProgressUpdate(Void... values) {  
   int number = id+1;
   count.setText("Loaded " + number + "/5");
  }
  
  @Override 
  protected void onPostExecute(Drawable result) {        
   // update the UI with loaded information
   displayImage(result);    
  }
  
  // Additional method to load images from web
   private Drawable ImageOperations(Context ctx,  String url, String saveFilename) { 
    try {
     URL imageUrl = new URL(url);
     InputStream is = (InputStream) imageUrl.getContent();
     Drawable d = Drawable.createFromStream(is, "src");
     return d;
    } catch (MalformedURLException e) {
     e.printStackTrace();
     return null;
    } catch (IOException e) {
     e.printStackTrace();
     return null;
    }
   }
 }
}

How to create a listview with custom adapter on Android

To create a ListView with your custom layout you need to create a custom adapter, override the getView method, and set the list adapter.
Find below an example with a TextView, ImageView and Button in the layout.
















main.xml

    
    
    
    
    




main.java
package com.blog.listviewwithcustomadapter;

import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class main extends ListActivity {

 public final String[] Colors = { "Blue", "Green", "Black" };

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  // setContentView(R.layout.main);
  // instantiate our custom adapter
  MyCustomAdapter adapter = new MyCustomAdapter(this, R.layout.main, Colors);
  //setting the adapter
  setListAdapter(adapter);
 }

 public class MyCustomAdapter extends ArrayAdapter {

  public MyCustomAdapter(Context context, int textViewResourceId, String[] list) {
   super(context, textViewResourceId, list);
  }

  @Override
     public View getView(int position, View convertView, ViewGroup parent) {
            
      View row = convertView;

      if (row == null) {
       LayoutInflater inflater = getLayoutInflater();
       row = inflater.inflate(R.layout.main, parent, false);
      }
      final int itemPosition = position;
      
      TextView listItem = (TextView) row.findViewById(R.id.colors );
      listItem.setText(Colors[position]);
      
      ImageView image = (ImageView) row.findViewById(R.id.imgAndroid);
      image.setImageResource(R.drawable.icon);
      
      Button btn = (Button) row.findViewById(R.id.btnColor);
      btn.setOnClickListener( new View.OnClickListener() {
    
    @Override
    public void onClick(View v) {
     Toast.makeText(getApplicationContext(), "Toast from button"+ Colors[itemPosition], Toast.LENGTH_SHORT).show();     
    }
   });
            
      row.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
        Toast.makeText(getApplicationContext(), Colors[itemPosition], Toast.LENGTH_SHORT).show();
       }     
      });
      return row;
     }
 }
}

April 20, 2011

How to load an image from Web on Android

Find below complete code for a simple application that loads an image from web. You have to insert the url and click the button. You can use this example in your applications when you need to load images from web.
Example:






Add this line in your AndroidManifest.xml file:


Layout main.xml


 
 
 


main.java
package com.blog.loadimage;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

public class main extends Activity {
 
 EditText imageUrl;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);         
        imageUrl = (EditText)findViewById(R.id.editTextUrl);
  Button getImageButton = (Button)findViewById(R.id.buttonGetImage);
  getImageButton.setOnClickListener( new View.OnClickListener() {   
   @Override
   public void onClick(View v) {    
     Context context = v.getContext();
     Editable ed = imageUrl.getText();
     Drawable image = ImageOperations(context,ed.toString(),"image.jpg");
     ImageView imgView = new ImageView(context);
     imgView = (ImageView)findViewById(R.id.imageView);
     imgView.setImageDrawable(image);    
   }
  });
    }    
    private Drawable ImageOperations(Context ctx, String url, String saveFilename) {
  try {
   URL imageUrl = new URL(url);
   InputStream is = (InputStream) imageUrl.getContent();
   Drawable d = Drawable.createFromStream(is, "src");
   return d;
  } catch (MalformedURLException e) {
   e.printStackTrace();
   return null;
  } catch (IOException e) {
   e.printStackTrace();
   return null;
  }
 }
}

April 14, 2011

How To display a Custom Toast Notification in Android

     If you need to display a simple Toast use this tutorial but if you want to customize your Toast Notification read the post below.

  1. Create your own layout for the Toast. Add it to the res/layout directory ( file - customizedtoast.xml).
  2. 
        
        
    
    
  3. Create a new LayourInflater, then call the inflate() method passing the Layout of the custom Toast and the root id (id of the linearLayour in our case) .
  4. LayoutInflater li = getLayoutInflater();
    View layout = li.inflate(R.layout.customizedtoast, 
      (ViewGroup) findViewById(R.id.customToastLayout));
    
  5. Create new Toast and pass the root of the layout to the setView() method of the Toast. Call the show() method.
  6. Toast toast = new Toast(getApplicationContext());
    toast.setDuration(Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
    toast.setView(layout);
    toast.show();
    

Example:


Complete code :

main.java
package com.blog.customizedtoastnotification;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

public class main extends Activity {
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  Button btn = (Button) findViewById(R.id.button1);
  btn.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {

    LayoutInflater li = getLayoutInflater();
    View layout = li.inflate(R.layout.customizedtoast,
      (ViewGroup) findViewById(R.id.customToastLayout));

    Toast toast = new Toast(getApplicationContext());
    toast.setDuration(Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
    toast.setView(layout);
    toast.show();
   }
  });
 }
}
main.xml

 
 



April 13, 2011

How To display a simple Toast Notificatin in Android

To create a simple Toast Notification instantiate a Toast object passing the context, the text and the duration to its makeText() method, then call the show() method. The duration can be : Toast.LENGTH_LONG or Toast.LENGTH_SHORT.
Example:
Context context = getApplicationContext();
CharSequence text = "Write the toast message here";
int duration = Toast.LENGTH_SHORT;
Toast toastNodification = Toast.makeText(context, text, duration);
toastNodification.show();

You can also use the short (chained) version :
Toast.makeText(getApplicationContext(), "short version", Toast.LENGTH_SHORT).show();

Don't forget to add imports:
import android.content.Context;
import android.widget.Toast;

The result:


Complete code :

main.java

package com.blog.simpletoastnotification;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class main extends Activity {
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  Button simpleBtn = (Button) findViewById(R.id.button1);
  simpleBtn.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    Context context = getApplicationContext();
    CharSequence text = "Write the toast message here";
    int duration = Toast.LENGTH_SHORT;
    Toast toastNodification = Toast.makeText(context, text, duration);
    toastNodification.show();
    
    // short version
   // Toast.makeText(getApplicationContext(),
"short version Toast", Toast.LENGTH_SHORT).show();
   }
  });

 }
}

main.xml





How To display Alert Dialog in Android

After creating a new project,
  1. add new button on the layout:
<LinearLayout android:id="@+id/linearLayout1"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <Button android:text="Delete file" 
        android:id="@+id/button1"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"></Button>
</LinearLayout>
Modyfy your main activity as follow:
 2. Add imports:
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;



3. override the onCreateDialog method :
@Override
    protected Dialog onCreateDialog(int id) {
        Dialog dialog = null;
        switch (id) {
        case ALERT_DIALOG_ID:
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Delete file");
            builder.setMessage("Are you shure ?");
            builder.setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // perform action for Yes button
                        }
                    });
            builder.setNegativeButton("NO",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // perform action for No button
                        }
                    });
            builder.setNeutralButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // perform action for Cancel button
                        }
                    });
            dialog = builder.create();
            break;
        default:
            return null;            
        }               
        return dialog;
    }
4.  define the unique dialog ID into your Activity class:
final int ALERT_DIALOG_ID = 0;  
5. Modify the onCreate method :
  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener( new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                showDialog(ALERT_DIALOG_ID);
            }
        });
    }



April 11, 2011

Android market alternatives

,Are you looking for a place to sell your Android apps ?
Find below a big list of alternative markets :
  1. Google Android Market - https://market.android.com/
  2. AndAppStore - http://andappstore.com
  3. AppsLib - http://appslib.com/
  4. AndroidPIT - http://www.androidpit.com/
  5. AndroLib - http://www.androlib.com/
  6. AppBrain - http://www.appbrain.com/
  7. Applanet - http://www.applanet.net/
  8. appoke -  http://appoke.com/
  9. Appstoreconnect - http://appstoreconnect.com/publish/
  10. AppstoreHQ - http://www.appstorehq.com/
  11. Camangi - http://www.camangimarket.com/
  12. Handango - http://www.handango.com
  13. GetJar http://www.getjar.com/
  14. Insyde Market - http://www.insydemarket.com
  15. Mobango - http://www.mobango.com/
  16. Mobihand - http://www.mobihand.com/
  17. Phoload - http://www.phoload.com/
  18. PocketdGear -  http://www.pocketgear.com
  19. SlideME - http://slideme.org/
  20. KUQU - http://www.kuqu.com
  21. YAAM Market - http://yaam.mobi/
Feel free to write another markets or your experience with them.