Search This Blog

Tuesday 21 February 2012

Custom Color picker dialog in android

Here i wrote a code with help of AndroidDeveloper'sBestGuide. It is just concept of implement canvas with a dialog box.
We create different color by using Canvas. and then we select different color with the help of canvas.
With the help of this example ,you will also read how to create a custom diaolog

For more information about canvas you. Game Development using Surface View Part III , Game Development Using Canvas Part I

Lets do it step by step


1) Create One XML file in res/layout/main.xml


<?xml version="1.0" encoding="UTF-8"?>  
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="match_parent"  
   android:layout_height="wrap_content"  
   android:padding="20dip" android:id="@+id/main"  
   android:orientation="vertical">  
   <Button android:layout_width="wrap_content"     android:layout_height="wrap_content"  
     android:layout_gravity="center" android:text="Change Background"  
     android:id="@+id/change_color"/>  
 </LinearLayout>  

2) Create One activity and register in manifest file  

Never forget to register your activity into manifest. This activity has only one button. If you click button then it will pop up color picker. Then you can select any color by just touching it


public class ColorPicker extends Activity{  
   private LinearLayout ll;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.main);  
     Button btn=(Button) findViewById(R.id.change_color);  
     ll=(LinearLayout) findViewById(R.id.main);  
     btn.setOnClickListener(new OnClickListener() {  
       @Override  
       public void onClick(View v) {  
         ColorPickerDialog cpd=new ColorPickerDialog(ColorPicker.this, listener, 0);  
         cpd.show();  
       }  
     });  
    }  
    @Override  
   protected void onResume() {  
     super.onResume();  
     ll.setBackgroundColor(ColorAh);  
   }  
   OnColorChangedListener listener=new OnColorChangedListener() {  
       @Override  
       public void colorChanged(int color) {  
         Toast.makeText(ColorPicker.this, ""+color, Toast.LENGTH_LONG).show();  
         ColorAh=color;  
         ll.setBackgroundColor(ColorAh);  
       }  
     };  
   private int ColorAh=Color.BLACK;  
 }  

3)Now create a custom dialog

This is the main task. Here with the help of a canvas we will create surface with different color. If you touch any coordinate then it will give respective point color code. This all is a part of a custom dialog. When user touch any point we will select a color and dismiss dialog box.


public class ColorPickerDialog extends Dialog {  
   public interface OnColorChangedListener {  
     void colorChanged(int color);  
   }  
   private OnColorChangedListener mListener;  
   private int mInitialColor;  
   private static class ColorPickerView extends View {  
     private Paint mPaint;  
     private Paint mCenterPaint;  
     private final int[] mColors;  
     private OnColorChangedListener mListener;  
     ColorPickerView(Context c, OnColorChangedListener l, int color) {  
       super(c);  
       mListener = l;  
       mColors = new int[] {  
         0xFFFF0000, 0xFFFF00FF, 0xFF0000FF, 0xFF00FFFF, 0xFF00FF00,  
         0xFFFFFF00, 0xFFFF0000  
       };  
       Shader s = new SweepGradient(0, 0, mColors, null);  
       mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);  
       mPaint.setShader(s);  
       mPaint.setStyle(Paint.Style.STROKE);  
       mPaint.setStrokeWidth(32);  
       mCenterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);  
       mCenterPaint.setColor(color);  
       mCenterPaint.setStrokeWidth(5);  
     }  
     private boolean mTrackingCenter;  
     private boolean mHighlightCenter;  
     @Override  
     protected void onDraw(Canvas canvas) {  
       float r = CENTER_X - mPaint.getStrokeWidth()*0.5f;  
       canvas.translate(CENTER_X, CENTER_X);  
       canvas.drawOval(new RectF(-r, -r, r, r), mPaint);  
       canvas.drawCircle(0, 0, CENTER_RADIUS, mCenterPaint);  
       if (mTrackingCenter) {  
         int c = mCenterPaint.getColor();  
         mCenterPaint.setStyle(Paint.Style.STROKE);  
         if (mHighlightCenter) {  
           mCenterPaint.setAlpha(0xFF);  
         } else {  
           mCenterPaint.setAlpha(0x80);  
         }  
         canvas.drawCircle(0, 0,  
                  CENTER_RADIUS + mCenterPaint.getStrokeWidth(),  
                  mCenterPaint);  
         mCenterPaint.setStyle(Paint.Style.FILL);  
         mCenterPaint.setColor(c);  
       }  
     }  
     @Override  
     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
       setMeasuredDimension(CENTER_X*2, CENTER_Y*2);  
     }  
     private static final int CENTER_X = 100;  
     private static final int CENTER_Y = 100;  
     private static final int CENTER_RADIUS = 32;  
     private int floatToByte(float x) {  
       int n = java.lang.Math.round(x);  
       return n;  
     }  
     private int pinToByte(int n) {  
       if (n < 0) {  
         n = 0;  
       } else if (n > 255) {  
         n = 255;  
       }  
       return n;  
     }  
     private int ave(int s, int d, float p) {  
       return s + java.lang.Math.round(p * (d - s));  
     }  
     private int interpColor(int colors[], float unit) {  
       if (unit <= 0) {  
         return colors[0];  
       }  
       if (unit >= 1) {  
         return colors[colors.length - 1];  
       }  
       float p = unit * (colors.length - 1);  
       int i = (int)p;  
       p -= i;  
       // now p is just the fractional part [0...1) and i is the index  
       int c0 = colors[i];  
       int c1 = colors[i+1];  
       int a = ave(Color.alpha(c0), Color.alpha(c1), p);  
       int r = ave(Color.red(c0), Color.red(c1), p);  
       int g = ave(Color.green(c0), Color.green(c1), p);  
       int b = ave(Color.blue(c0), Color.blue(c1), p);  
       return Color.argb(a, r, g, b);  
     }  
     private int rotateColor(int color, float rad) {  
       float deg = rad * 180 / 3.1415927f;  
       int r = Color.red(color);  
       int g = Color.green(color);  
       int b = Color.blue(color);  
       ColorMatrix cm = new ColorMatrix();  
       ColorMatrix tmp = new ColorMatrix();  
       cm.setRGB2YUV();  
       tmp.setRotate(0, deg);  
       cm.postConcat(tmp);  
       tmp.setYUV2RGB();  
       cm.postConcat(tmp);  
       final float[] a = cm.getArray();  
       int ir = floatToByte(a[0] * r + a[1] * g + a[2] * b);  
       int ig = floatToByte(a[5] * r + a[6] * g + a[7] * b);  
       int ib = floatToByte(a[10] * r + a[11] * g + a[12] * b);  
       return Color.argb(Color.alpha(color), pinToByte(ir),  
                pinToByte(ig), pinToByte(ib));  
     }  
     private static final float PI = 3.1415926f;  
     @Override  
     public boolean onTouchEvent(MotionEvent event) {  
       float x = event.getX() - CENTER_X;  
       float y = event.getY() - CENTER_Y;  
       boolean inCenter = java.lang.Math.sqrt(x*x + y*y) <= CENTER_RADIUS;  
       switch (event.getAction()) {  
         case MotionEvent.ACTION_DOWN:  
           mTrackingCenter = inCenter;  
           if (inCenter) {  
             mHighlightCenter = true;  
             invalidate();  
             break;  
           }  
         case MotionEvent.ACTION_MOVE:  
           if (mTrackingCenter) {  
             if (mHighlightCenter != inCenter) {  
               mHighlightCenter = inCenter;  
               invalidate();  
             }  
           } else {  
             float angle = (float)java.lang.Math.atan2(y, x);  
             // need to turn angle [-PI ... PI] into unit [0....1]  
             float unit = angle/(2*PI);  
             if (unit < 0) {  
               unit += 1;  
             }  
             mCenterPaint.setColor(interpColor(mColors, unit));  
             invalidate();  
           }  
           break;  
         case MotionEvent.ACTION_UP:  
           if (mTrackingCenter) {  
             if (inCenter) {  
               mListener.colorChanged(mCenterPaint.getColor());  
             }  
             mTrackingCenter = false;  // so we draw w/o halo  
             invalidate();  
           }  
           break;  
       }  
       return true;  
     }  
   }  
   public ColorPickerDialog(Context context,  
                OnColorChangedListener listener,  
                int initialColor) {  
     super(context);  
     mListener = listener;  
     mInitialColor = initialColor;  
   }  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     OnColorChangedListener l = new OnColorChangedListener() {  
       public void colorChanged(int color) {  
         mListener.colorChanged(color);  
         dismiss();  
       }  
     };  
     setContentView(new ColorPickerView(getContext(), l, mInitialColor));  
     setTitle("Pick a Color");  
   }  
 }  

 Now screen shot will show our hard work into output :). See the screen shot. And Let me if you face any problem while implementing it.
                                               
Main Screen
      Click on button ? it immediately will pop up all your hard work in term of dialog


Android trainner color picker in android
Now Select color

After Selecting Color

Sunday 19 February 2012

Answer most voted on stack over flow By me

Question 1)     Best phone for android app development  ?

Answer: I write software for Android and iOS for a living; I wouldn't recommend a G1 for developing new Android apps; the last officially released firmware for that phone is Android 1.6, which accounts for less and less of the existing install base. They made a lot of substantial changes to the SDK between 1.6 and 2.x. For new applications, I don't think it's worth targeting anything less than 2.1.
If you're only going to use one phone for development, I would avoid non-official roms at all costs. Rooting is ok (and can help with debugging), but custom roms will totally throw off your ability to develop and debug for the general Android public. You'll want the environment on your sole development phone to be as boring and vanilla as possible.

Thursday 16 February 2012

XML parsing tutorial using Sax Parser in android

Parsing is an important phase in android application development. Storing data on android device is not feasible  in large amount of data. So we store data on server and return data in xml format and then we parse data and show data on android device.

You can create a InputStream either from online URL or from local file.I stored a xml file into assets and make an InputStream and  parse it.

XML to parse

<main>
 <student>
  <name> Tofeeq Ahmad</name>
  <address> 142, Karol Bag, Delhi </address>
  <qua> MCA</qua>
 </student>
 <student>
  <name> Sameer Ahmad</name>
  <address> 142, Karol Bag,New  Delhi </address>
  <qua> BCA </qua>
 </student>
 <student>
  <name> Adams Cinclear</name>
  <address>123, Street Road Las Vegas </address>
  <qua> B Tech</qua>
 </student>
 <student>
  <name> Mike Hussy</name>
  <address> Sydney Australia </address>
  <qua> B.Com </qua>
 </student>
 <student>
  <name> Sameer Ahmad</name>
  <address> 142, Karol Bag,New  Delhi </address>
  <qua> BCA </qua>
 </student>
 <student>
  <name> Kushal Pal Singh</name>
  <address> 142, Karol Bag,New  Delhi </address>
  <qua> M Tech </qua>
 </student>
</main>

Now we will create a an application with ListView that will parse data and display it on ListView'row.

Step 1) Create two Layout  One main screen that contain one ListView and other to display data inside a row

 Layout for Main Screen

<?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" >
    <ListView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/listview"
        android:cacheColorHint="@android:color/transparent"
        android:dividerHeight="2dp"
        />
</LinearLayout>

Layout for listview row
<?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="wrap_content"
    android:orientation="vertical"
    android:paddingLeft="10dp" >

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sameer Ahmad"
        android:textColor="#fff"
        android:textSize="18dp" />

    <TextView
        android:id="@+id/address"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sameer Ahmad"
        android:textColor="#fff"
        android:textSize="18dp" />

    <TextView
        android:id="@+id/quali"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sameer Ahmad"
        android:textColor="#fff"
        android:textSize="18dp" />

</LinearLayout>

Step 2) Now we will parse data using default handler that is part of Sax Parser. In this class we have three method startElement , endElement , character. These called when tag start , tag end and read its values. We will save these values inside corresponding values


package com.ahmad;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ParsingClass extends DefaultHandler {

 ArrayList<String> name = new ArrayList<String>();
 ArrayList<String> address = new ArrayList<String>();
 ArrayList<String> qua = new ArrayList<String>();

 @Override
 public void startElement(String uri, String localName, String qName,
   Attributes attributes) throws SAXException {
  super.startElement(uri, localName, qName, attributes);
  if (localName.equalsIgnoreCase("name")) {
   tempStore = "";
  } else if (localName.equalsIgnoreCase("address")) {
   tempStore = "";
  } else if (localName.equalsIgnoreCase("qua")) {
   tempStore = "";
  }else{
   tempStore = "";
  }
 }

 @Override
 public void endElement(String uri, String localName, String qName)
   throws SAXException {
  super.endElement(uri, localName, qName);
  if (localName.equalsIgnoreCase("name")) {
   name.add(tempStore);
  } else if (localName.equalsIgnoreCase("address")) {
   address.add(tempStore);
  } else if (localName.equalsIgnoreCase("qua")) {
   qua.add(tempStore);
  }
  tempStore = "";
 }

 private String tempStore = "";

 @Override
 public void characters(char[] ch, int start, int length)
   throws SAXException {
  super.characters(ch, start, length);
  tempStore += new String(ch, start, length);
 }
}

Step 3) Now we need one Activity to create core component of parsing and Setting InputStream from assets. and Finally when data will parse we will add or bind all data to listview

Activity class with core parsing code

package com.ahmad;

import java.io.InputStream;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

public class XmlParsingActivity extends Activity {
 /** Called when the activity is first created. */
 private ListView listView;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  listView = (ListView) findViewById(R.id.listview);
  bindDataToListing();
 }

 private void bindDataToListing() {
  try {
   SAXParserFactory saxparser = SAXParserFactory.newInstance();
   SAXParser parser = saxparser.newSAXParser();
   XMLReader xmlReader = parser.getXMLReader();
   ParsingClass pc = new ParsingClass();
   xmlReader.setContentHandler(pc);
   InputStream is = getAssets().open("xmldocument.xml");
   xmlReader.parse(new InputSource(is));
   BindingData bindingData = new BindingData(this, pc.name,
     pc.address, pc.qua);
   listView.setAdapter(bindingData);
  } catch (Exception e) {
   e.getMessage();
  }
 }
}

Adapter Class For Binding data to ListView..if you are new to this see article ListView with adapter 

package com.ahmad;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class BindingData extends BaseAdapter {
 ArrayList<String> name;
 ArrayList<String> address;
 ArrayList<String> qua;
 LayoutInflater inflater;

 public BindingData() {

 }

 public BindingData(Activity act, ArrayList<String> name,
   ArrayList<String> add, ArrayList<String> qua) {
  this.name = name;
  this.address = add;
  this.qua = qua;
  inflater = (LayoutInflater) act
    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 }

 @Override
 public int getCount() {
  return name.size();
 }

 @Override
 public Object getItem(int position) {
  return null;
 }

 @Override
 public long getItemId(int position) {
  return 0;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  Holder holder;
  if (convertView == null) {
   holder = new Holder();
   convertView = inflater.inflate(R.layout.listrow, null);
   holder.txtName = (TextView) convertView.findViewById(R.id.name);
   holder.txtAddress = (TextView) convertView
     .findViewById(R.id.address);
   holder.txtQua = (TextView) convertView.findViewById(R.id.quali);
   convertView.setTag(holder);
  } else {
   holder = (Holder) convertView.getTag();
  }
  holder.txtName.setText(Html.fromHtml("" + name.get(position)));
  holder.txtAddress.setText(Html.fromHtml("<b>Address : </b>"
    + address.get(position)));
  holder.txtQua.setText(Html.fromHtml("<b>Qualification : </b>"
    + qua.get(position)));

  return convertView;
 }

 private class Holder {
  TextView txtName, txtAddress, txtQua;
 }
}

Finally you hard work will bring output like this


Download Source Code

Saturday 4 February 2012

Action List


Action List In android

A string naming the action to be performed — or, in the case of broadcast intents, the action that took place and is being reported. The Intent class defines a number of action constants, including these:
ConstantTarget componentAction
ACTION_CALLactivityInitiate a phone call.
ACTION_EDITactivityDisplay data for the user to edit.
ACTION_MAINactivityStart up as the initial activity of a task, with no data input and no returned output.
ACTION_SYNCactivitySynchronize data on a server with data on the mobile device.
ACTION_BATTERY_LOWbroadcast receiverA warning that the battery is low.
ACTION_HEADSET_PLUGbroadcast receiverA headset has been plugged into the device, or unplugged from it.
ACTION_SCREEN_ONbroadcast receiverThe screen has been turned on.
ACTION_TIMEZONE_CHANGEDbroadcast receiverThe setting for the time zone has changed.

Broadcast Receiver example in Android

I know there are lots of tutorial present on BroadcastReceiver . But still not best for the who is beginning in android application development. As we know there are four basic component in android

  • Content Provider
  • Activity
  • Service
  • Broadcast Receiver

In this article i am going to explain about broad cast receiver

What exactly a BroadCastReceiver  is?

Definition: Broadcast is way of telling someone that now you have to that this is right time to do this.So do this.

Ex..There is teacher in class.If he broadcast a message while teaching and he does not specify any specific audience then all receiver(Student and will act).But if specify any action to particular student then he will act.
See in the pic.Only student having name Tofeeq will act
Using Broadcast receiver in android:There are two ways to use broad cast receiver in android --

  • One is using  dynamically in activity
  • Second to register through manifest

In first way register receiver when you feel, now you have to send broad cast message and then unregistered when task completed(As its very battery consuming process)

In second declare in Manifest file and then no need to register. In that case life cycle of receiver will be from when your application is installed and until your application uninstalled

Step by step procedure: Let consider second way to use BroadCastReceiver through Manifest file


Step 1) Take a class and extends Broadcast receiver class in this. 


public class OurCustomReceiver extends BroadcastReceiver{

 @Override
 public void onReceive(Context arg0, Intent arg1) {
  Log.i("My Rceiver ", arg1.getAction());
 }

}

Step 2) Register Receiver inside manifest file and specifying one action - Notable thing is that Receiver will be the part of application. In below code, two action has been specified for our receiver. so it will called whenever android device perform any of them


        <receiver android:name=".OurCustomReceiver">
            <intent-filter>
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

Step 3) Running application and catching action - Now just run your application it will catch both action. And onReceive() method will call for each.

Step 4) Handling multiple action by BroadCastReceiver - This application is handling two action, either device Wifi state changed or Device is restarted onReceive() method will call. So we have to check to perform desired action. Now class OurCustomReceiver's onReceive() method will like


 Log.i("My Rceiver ", arg1.getAction());
 if(arg1.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)){
  // Do something 
 }else{
  // Do something
 }

Android News and source code