Showing posts with label how to. Show all posts
Showing posts with label how to. Show all posts

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");   
  }
 }
}

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 13, 2011

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);
            }
        });
    }