May 11, 2011

How to use the Light sensor on Android

If your android device has a Light Sensor you can use it in your applications. It provide the value in lux units as described here. More about lux find here.

main.xml





main.java
package com.blog.lightsensor;

import java.util.Date;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;

public class main extends Activity implements SensorEventListener {
 private  SensorManager sensorManager = null;
 private  Sensor currentSensor = null; 
 
 @Override
 public void onResume(){
  super.onResume();
  if(currentSensor != null)sensorManager.registerListener(this, currentSensor, SensorManager.SENSOR_DELAY_FASTEST);
 }
 
 @Override
 public void onPause(){
  super.onPause();
  sensorManager.unregisterListener(this);
 } 
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     sensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);
  currentSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT );
  if(currentSensor != null){
   sensorManager.registerListener(this, currentSensor, SensorManager.SENSOR_DELAY_FASTEST);
  }else{
   ((TextView) findViewById(R.id.textView1)).setText("Can't initialize the LIGHT sensor.");   
  } 
    }

 @Override
 public void onAccuracyChanged(Sensor sensor, int accuracy) {
  // TODO Auto-generated method stub
 }

 @Override
 public void onSensorChanged(SensorEvent event) {
  // TODO Auto-generated method stub
  
  if (event.sensor.getType() == Sensor.TYPE_LIGHT){   
   TextView tv = (TextView) findViewById(R.id.textView1);
   tv.setText( tv.getText()+ "value: " +event.values[0] + " lux , time: " + new Date() + "\n");   
  }
 }
}

List of available sensors on Android

You can obtain the list of available sensors on your device by calling sensonManager.getSensorList() and providing the type Sensor.TYPE_ALL as a parameter. Find below a full example.




main.xml


    

main.java
package com.blog.sensorslist;

import java.util.List;

import android.app.ListActivity;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class main extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // setContentView(R.layout.main);
        
        // create new SensorManager
        SensorManager sensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);
        // get all sensors of all types
        List sensorList = sensorManager.getSensorList(Sensor.TYPE_ALL);
        // list of all sensor types
        String[] sensorTypes = new String[]{"","ACCELEROMETER", "MAGNETIC_FIELD", 
          "ORIENTATION", "GYROSCOPE", "LIGHT", "PRESSURE","TEMPERATURE", 
          "PROXIMITY", "GRAVITY", "LINEAR_ACCELERATION", "ROTATION_VECTOR"};
        
        // array for ListAdapter
        String[] infoList = new String[sensorList.size()];
        
        for (int i =0; i < sensorList.size(); i++){
         Sensor currentSensor = sensorList.get(i);
         infoList[i] = "Sensor Name: "+ currentSensor.getName() +"\n" +
             "Vendor: "+ currentSensor.getVendor() + "\n" +
             "Version: "+ currentSensor.getVersion()+ "\n"+
             "Type: "+ currentSensor.getType() + " - "+sensorTypes[currentSensor.getType()]+ "\n"+
             "Maximum Range: "+ currentSensor.getMaximumRange()+ "\n"+
             "Power (mA):"+ currentSensor.getPower()+ "\n"+
             "Resolution: "+ currentSensor.getResolution();              
        }
        // setting the ListAddapter
        setListAdapter(new ArrayAdapter(this, R.layout.main, infoList));
    }
}

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.

March 29, 2011

Best books for Android development

I started learning Android development from the official sources : Dev Guide -  http://developer.android.com/guide/index.html and I recommend them for beginners. I also created a list of books for learning, you can find them on Amazon (or for free in other places like this):
  • Professional Android Application Development (Wrox Programmer to Programmer) (Amazon);
  • Professional Android 2 Application Development (Wrox Programmer to Programmer) (Amazon); 
  • Pro Android (Amazon);
  • Hello, Android: Introducing Google's Mobile Development Platform (Pragmatic Programmers) (Amazon);
  • Android Wireless Application Development (Amazon);
  • Unlocking Android: A Developer's Guide (Amazon);
  • Beginning Android (Amazon);
  • Beginning Android 2 (Amazon);
  • Android Programming Tutorials (Amazon);
  • The Busy Coder's Guide to Advanced Android Development (Amazon); 
  • Android Application Development: Programming with the Google SDK (Amazon). 
The best book is the book that you read ;)
Feel free to suggest in comments other books or the book which you consider the best.