Monday, April 19, 2010

Create Cutomized Color Picker in android

Code snippet for customized color picker

1. Create a Customized Color picker dialog box
2. Call the ColorPicker Dialog



Create a Customized Color picker dialog box

copy the below code and place into your package.

public class ColorPickerDialog extends Dialog {

    public interface OnColorChangedListener {
        void colorChanged(int color);
    }

    private final OnColorChangedListener mListener;
    private final int mInitialColor;

    private static class ColorPickerView extends View {
        private final Paint mPaint;
        private final Paint mCenterPaint;
        private final int[] mColors;
        private final 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();
            }
        };

        LinearLayout layout = new LinearLayout(getContext());
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setGravity(Gravity.CENTER);
        layout.setPadding(10, 10, 10, 10);
        layout.addView(new ColorPickerView(getContext(), l, mInitialColor),
                new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT));

        setContentView(layout);
        setTitle("Pick a Color");
    }
}


Call the ColorPicker Dialog

public class MainActivity extends Activity implements
        ColorPickerDialog.OnColorChangedListener {
    /** Called when the activity is first created. */
    private static final String BRIGHTNESS_PREFERENCE_KEY = "brightness";
    private static final String COLOR_PREFERENCE_KEY = "color";
    TextView tv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) findViewById(R.id.TextView01);

        Button btn = (Button) findViewById(R.id.Button01);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int color = PreferenceManager.getDefaultSharedPreferences(
                        MainActivity.this).getInt(COLOR_PREFERENCE_KEY,
                        Color.WHITE);
                new ColorPickerDialog(MainActivity.this, MainActivity.this,
                        color).show();
            }
        });

    }

    @Override
    public void colorChanged(int color) {
        PreferenceManager.getDefaultSharedPreferences(this).edit().putInt(
                COLOR_PREFERENCE_KEY, color).commit();
        tv.setTextColor(color);

    }

}


main layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:id="@+id/mainview">
    <Button android:text="Select Color" android:id="@+id/Button01"
        android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
    <TextView android:text="@+id/TextView01" android:id="@+id/TextView01"
        android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
</LinearLayout>


Sample Apps to Control Screen Brightness

This will help us to create a brightness controller in andriod.

1. Create a Layout with seekbar
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">


    <Button android:text="Show Brightness Panel" android:id="@+id/Button01"
        android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>


    <LinearLayout android:id="@+id/panel" android:orientation="vertical"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" android:paddingTop="10dip"
        android:paddingBottom="30dip" android:paddingLeft="20dip"
        android:paddingRight="20dip" android:gravity="center_horizontal"
        android:visibility="gone">

        <TextView android:text="Brightness Level"
            android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:gravity="center" android:textAppearance="?android:attr/textAppearanceLarge" />

        <SeekBar android:id="@+id/seek" android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:max="100"
            android:progress="100" />

    </LinearLayout>

</LinearLayout>

2. Create an activity to control the brightness
public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    private static final String BRIGHTNESS_PREFERENCE_KEY = "brightness";
    private View brightnessPanel;
    private SeekBar brightnessControl;
    private int brightness = 50;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        brightnessPanel = findViewById(R.id.panel);
        brightnessControl = (SeekBar) findViewById(R.id.seek);

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

            }
        });

        brightnessControl
                .setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    public void onProgressChanged(SeekBar seekBar,
                            int progress, boolean fromUser) {
                        setBrightness(progress);
                    }

                    public void onStartTrackingTouch(SeekBar seekBar) {
                    }

                    public void onStopTrackingTouch(SeekBar seekBar) {
                        hideBrightnessPanel();
                    }
                });
    }

    private void showBrightnessPanel() {
        Animation animation = AnimationUtils.loadAnimation(this,
                android.R.anim.slide_in_left);
        brightnessControl.setProgress(this.brightness);
        brightnessPanel.setVisibility(View.VISIBLE);
        brightnessPanel.startAnimation(animation);
    }

    private void setBrightness(int value) {
        if (value < 10) {
            value = 10;
        } else if (value > 100) {
            value = 100;
        }
        brightness = value;
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.screenBrightness = (float) value / 100;       
        lp.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
        getWindow().setAttributes(lp);
    }

    private void hideBrightnessPanel() {
        Animation animation = AnimationUtils.loadAnimation(MainActivity.this,
                android.R.anim.slide_out_right);
        brightnessPanel.startAnimation(animation);
        brightnessPanel.setVisibility(View.GONE);
        PreferenceManager.getDefaultSharedPreferences(this).edit().putInt(
                BRIGHTNESS_PREFERENCE_KEY, brightnessControl.getProgress())
                .commit();
    }

}





Create a Apps to Show Digital Time in Android

this blog helps to create a simple digital clock in andriod.

Create a Layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView android:id="@+id/countdown" android:layout_width="320dip"
        android:layout_height="120dip" android:text="00:00:00"
        android:textSize="15pt" android:textColor="#00C2FF"
        android:layout_centerInParent="true" />
</RelativeLayout>


Create Activty Class for show the Time

public class MainActivity extends Activity {
    private TextView countdown;
    private Timer timer;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView countdown = (TextView) findViewById(R.id.countdown);
    }

    @Override
    protected void onStart() {
        super.onStart();
        timer = new Timer("DigitalClock");
        Calendar calendar = Calendar.getInstance();

        // Get the Current Time
        final Runnable updateTask = new Runnable() {
            public void run() {
                countdown.setText(getCurrentTimeString()); // shows the current time of the day
//                countdown.setText(getReminingTime()); // shows the remaining time of the day
            }
        };

        // update the UI
        int msec = 999 - calendar.get(Calendar.MILLISECOND);
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(updateTask);
            }
        }, msec, 1000);
    }

    @Override
    protected void onStop() {
        super.onStop();
        timer.cancel();
        timer.purge();
        timer = null;
    }
   private String getReminingTime() {
        Calendar calendar = Calendar.getInstance();
        int hour = 23 - calendar.get(Calendar.HOUR_OF_DAY);
        int minute = 59 - calendar.get(Calendar.MINUTE);
        int second = 59 - calendar.get(Calendar.SECOND);
        return String.format("%02d:%02d:%02d", hour, minute, second);
    }



    private String getCurrentTimeString() {
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        return String.format("%02d:%02d:%02d %02d", hour, minute, second);
    }
}

Creating dynamic Customized List view.

This article shows to create a dynamic custom view as a list. i have created a custom adapter and explore to create a custom listview.
As a result i have created the below method. In this blog will help you to create a customized list view.

Create two layout
    1. main layout
    2. custom view layout.

MainLayout - which is used to define the scroll view.
    <?xml version="1.0" encoding="utf-8"?>
    <ScrollView android:id="@+id/ScrollView01"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_height="fill_parent" android:layout_width="fill_parent">
        <LinearLayout android:orientation="vertical"
            android:layout_width="fill_parent" android:id="@+id/mylayout1"
            android:layout_height="wrap_content">
        </LinearLayout>
    </ScrollView>


Custom Layout - Which Consists of actual design.
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout android:orientation="vertical"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        xmlns:android="http://schemas.android.com/apk/res/android">
        <TextView android:text="@+id/TextView01" android:id="@+id/TextView01"
            android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
        <Button android:text="@+id/Button01" android:id="@+id/Button01"
            android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
    </LinearLayout>




Create a Activity Class

public class DynamicListActivity extends Activity {
    /**
     * @see android.app.Activity#onCreate(Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listviewmain);
    LinearLayout l = (LinearLayout) findViewById(R.id.mylayout1);
    LayoutInflater linflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    for (int i = 0; i < 5; i++) {
        View customView = linflater.inflate(R.layout.customlistviewitem,
            null);
        TextView tv = (TextView) customView.findViewById(R.id.TextView01);
        Button btn = (Button) customView.findViewById(R.id.Button01);
        tv.setId(i);
        btn.setId(i);
        tv.setText("Location:" + i);
        btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(DynamicListActivity.this, v.getId() + "",
                Toast.LENGTH_LONG).show();
        }
        });
        l.addView(customView);
    }
    }
}


UtilMethod For Android - I

I have collected some Utility method from my code.

/** Return a specific file contents as a String value. */
public static String getFileString(File file) throws Exception {
    String result = null;
    InputStream is = null;
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        is = new FileInputStream(file);
        int bytesRead;
        byte[] buffer = new byte[1024];
        while ((bytesRead = is.read(buffer)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.flush();
        result = new String(os.toByteArray());
    } catch(Exception e) {
        throw new Exception("Problem while reading file", e);
    } finally {
        try {
            os.close();
            is.close();
        } catch(Exception e) {
        }
    }
    return result;
}

/** Return a specific url contents as a String value. */

public static String getUrlString(String remoteUrl) throws Exception {
    String result = null;
    InputStream is = null;
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        URL url = new URL(remoteUrl);
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        connection.connect();
        is = connection.getInputStream();
        int bytesRead;
        byte[] buffer = new byte[1024];
        while ((bytesRead = is.read(buffer)) != -1) {
            os.write(buffer, 0, bytesRead);
        }

        os.flush();
        result = new String(os.toByteArray());
    } catch(Exception e) {
        throw new Exception("Problem while reading targeted url", e);
    } finally {
        try {
            os.close();
            is.close();
        } catch(Exception e) {
        }
    }
    return result;
}

/** Create Thumbnail Image
* Param1 : Image,
* Param2 : Required Size */


public static Drawable createIconThumbnail(Drawable icon, int size) {
    int sourceWidth = icon.getIntrinsicWidth(),
    sourceHeight = icon.getIntrinsicHeight();
   
    int destWidth = size, destHeight = size;
   
    // only resize if actually needed
    if(sourceWidth != destWidth || sourceHeight != destHeight) {
        float ratio = (float) sourceWidth / sourceHeight;
        if(sourceWidth > sourceHeight) {
            destHeight = (int) (destWidth / ratio);
        } else if (sourceHeight > sourceWidth) {
            destWidth = (int) (destHeight * ratio);
        }

        final Bitmap thumb = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(thumb);

        icon.setBounds((size - destWidth) / 2, (size - destHeight) / 2, destWidth, destHeight);
        icon.draw(canvas);
        icon = new BitmapDrawable(thumb);
    }
    return icon;
}

/** Return a current time a String value. */
 private String getCurrentTimeString() {
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        return String.format("%02d:%02d:%02d ", hour, minute, second);
    }

Sunday, April 18, 2010

Create a Apps to Show Digital Time in Android

this blog helps to create a simple digital clock in andriod.

Create a Layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView android:id="@+id/countdown" android:layout_width="320dip"
        android:layout_height="120dip" android:text="00:00:00"
        android:textSize="15pt" android:textColor="#00C2FF"
        android:layout_centerInParent="true" />
</RelativeLayout>


Create Activty Class for show the Time

public class MainActivity extends Activity {
    private TextView countdown;
    private Timer timer;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView countdown = (TextView) findViewById(R.id.countdown);
    }

    @Override
    protected void onStart() {
        super.onStart();
        timer = new Timer("DigitalClock");
        Calendar calendar = Calendar.getInstance();

        // Get the Current Time
        final Runnable updateTask = new Runnable() {
            public void run() {
                countdown.setText(getCurrentTimeString());
            }
        };

        // update the UI
        int msec = 999 - calendar.get(Calendar.MILLISECOND);
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(updateTask);
            }
        }, msec, 1000);
    }

    @Override
    protected void onStop() {
        super.onStop();
        timer.cancel();
        timer.purge();
        timer = null;
    }

    private String getCurrentTimeString() {
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        return String.format("%02d:%02d:%02d %02d", hour, minute, second);
    }
}

Friday, April 16, 2010

UI component Snippets

In this article having the set of android sinppets used to set the value and listener action.

Spinner Control

      String selectedState  ="";
    String[] stateList = new String[] { "Select State", "MA", "NY" }; // Dropdown values
    Spinner sprState = (Spinner) findViewById(R.id.sprstate);


    // Set the value using the ArrayAdapter
    ArrayAdapter<String> stateListAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,stateList);
    stateListAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    stateListAdapter.setAdapter(stateList);


    // Listener
    sprState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent,View view, int position, long id) {
        selectedState = String.valueOf(sprState.getSelectedItem());
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });



ListView Control

    ArrayList<String> tempListViewData = new ArrayList<String>();
   tempListViewData.add("One");
   tempListViewData.add("two");

   ListView l = (ListView) findViewById(R.id.ListView01);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, tempListViewData);
    l.setAdapter(adapter);

    l.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) {
        Log.d("Position", arg2 + "");       
        }
    });


Button
Button btnFindStore = (Button) findViewById(R.id.btnhomego);
    private class FindStoreListener implements
            android.view.View.OnClickListener {
        @Override
        public void onClick(View v) {
       }
    }

btnCityStateOption.setOnClickListener(new FindStoreListener());

EditText
    EditText etUserInput = (EditText) findViewById(R.id.etuserinput);
    String.valueOf(etUserInput.getText()).trim();

   

Thursday, April 15, 2010

Find Current Location in Android - GPS Sample

This article will show you how to programmatically access the data returned by your built-in GPS receiver.

In Android, location-based services are provided by the LocationManager class located in the android.location package.

Using the LocationManager class, we can obtain periodic updates of the device's geographical locations as well as fire an intent when it enters the proximity of a certain location.


1. Obtain a reference to the LocationManager class using the getSystemService() method.

    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);


2. Create a LocationListener Class for notify the location changes.
Our MyLocationListener class should implements the LocationListener abstract class. There are four methods that you need to override in this implementation:
    * onLocationChanged(Location location): This method is called when the location has changed.
    * onProviderDisabled(String provider): This method is called when the provider is disabled by the user.
    * onProviderEnabled(String provider): This method is called when the provider is enabled by the user.
    * onStatusChanged(String provider, int status, Bundle extras): This method is called when the provider status changes.


3. To be notified whenever there is a change in location, you need to register for a request for changes in locations so that your program can be notified periodically. This is done via the requestLocationUpdates() method (see Listing 1).

This method takes in four parameters:
    * provider: The name of the provider with which you register
    * minTime: The minimum time interval for notifications, in milliseconds.
    * minDistance: The minimum distance interval for notifications, in meters.
    * listener: An object whose onLocationChanged() method will be called for each location update.

4. Set the following User-Permission  in androidmanifest.xml

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>


Sample Code :
MainActivity.java
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    LocationListener ll = new mylocationlistener();
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
    }

    private class mylocationlistener implements LocationListener {
    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
        Log.d("LOCATION CHANGED", location.getLatitude() + "");
        Log.d("LOCATION CHANGED", location.getLongitude() + "");
        Toast.makeText(MainActivity.this,
            location.getLatitude() + "" + location.getLongitude(),
            Toast.LENGTH_LONG).show();
        }
    }
    @Override
    public void onProviderDisabled(String provider) {
    }
    @Override
    public void onProviderEnabled(String provider) {
    }
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
    }
}


Wednesday, April 7, 2010

Steps to implement ExpandableListView in android

3 Steps to implement the Expandable ListView  in android

Step 1 : Initilize the ExpandableListView and ExpandableListAdapter in a onCreate()

    ExpandableListAdapter mAdapter;
    ExpandableListView epView = (ExpandableListView) findViewById(R.id.ExpandableListView01);
    mAdapter = new MyExpandableListAdapter();
    epView.setAdapter(mAdapter);

Step 2 : Create a custom BaseApdapter Class
 /**
     * A simple adapter which maintains an ArrayList of photo resource Ids. Each
     * photo is displayed as an image. This adapter supports clearing the list
     * of photos and adding a new photo.
     *
     */
    public class MyExpandableListAdapter extends BaseExpandableListAdapter {
    // Sample data set. children[i] contains the children (String[]) for
    // groups[i].
    private String[] groups = { "Parent1", "Parent2",
        "Parent3" };
    private String[][] children = { { "Child1" },{ "Child2" }, { "Child3" },{ "Child4" }, { "Child5" } };

    public Object getChild(int groupPosition, int childPosition) {
        return children[groupPosition][childPosition];
    }

    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    public int getChildrenCount(int groupPosition) {
        int i = 0;
        try {
        i = children[groupPosition].length;

        } catch (Exception e) {
        }

        return i;
    }

    public TextView getGenericView() {
        // Layout parameters for the ExpandableListView
        AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
            ViewGroup.LayoutParams.FILL_PARENT, 64);

        TextView textView = new TextView(MainActivity.this);
        textView.setLayoutParams(lp);
        // Center the text vertically
        textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
        textView.setTextColor(R.color.marcyred);
        // Set the text starting position
        textView.setPadding(36, 0, 0, 0);
        return textView;
    }

    public View getChildView(int groupPosition, int childPosition,
        boolean isLastChild, View convertView, ViewGroup parent) {
        TextView textView = getGenericView();
        textView.setText(getChild(groupPosition, childPosition).toString());
        return textView;
    }

    public Object getGroup(int groupPosition) {
        return groups[groupPosition];
    }

    public int getGroupCount() {
        return groups.length;
    }

    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    public View getGroupView(int groupPosition, boolean isExpanded,
        View convertView, ViewGroup parent) {
        TextView textView = getGenericView();
        textView.setText(getGroup(groupPosition).toString());
        return textView;
    }

    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    public boolean hasStableIds() {
        return true;
    }

    }
   
3. Listeners
    epView.setOnGroupClickListener(new OnGroupClickListener() {
        @Override
        public boolean onGroupClick(ExpandableListView arg0, View arg1,
            int groupPosition, long arg3) {
        if (groupPosition == 5) {               

        }
        return false;
        }
        });

    epView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
    @Override
    public boolean onChildClick(ExpandableListView parent,
            View v, int groupPosition, int childPosition,
            long id) {
        if (groupPosition == 0 && childPosition == 0) {
           
        }
        return false;
    }
    });

Tuesday, April 6, 2010

Utility Calss - ImageMangerHelper

The Following Code snippets used to fetching the image from targeted image URL

/**
 * ImageManager is used to fetch the image from the targeted url. It is a
 * immutable pattern.
 *
 * @author ganesan_sh
 *
 */
public final class ImageManager {

    static ImageManager imageManager = null;
    private static long updatedTime = 0;
    private static long resetPeriod = 4320000;
    private static Bitmap bmImg;

    private ImageManager() {
    }

    public static ImageManager getImageManagerInstance(String imageURL) {
    long currTime = System.currentTimeMillis();
    if (((currTime - updatedTime) > resetPeriod) || imageManager == null) {
        imageManager = new ImageManager();
        fetchAdvBannerImage(imageURL);
    }
    return imageManager;
    }

    static void fetchAdvBannerImage(String fileUrl) {
    URL myFileUrl = null;
    try {
        myFileUrl = new URL(fileUrl);
    } catch (MalformedURLException e) {
    }
    try {
        HttpURLConnection conn = (HttpURLConnection) myFileUrl
            .openConnection();
        conn.setDoInput(true);
        conn.connect();
        int length = conn.getContentLength();
        InputStream is = conn.getInputStream();
        bmImg = BitmapFactory.decodeStream(is);

    } catch (IOException e) {
    }
    }

    public Bitmap getBannerImage() {
    return bmImg;
    }
}


Monday, April 5, 2010

Retrieve Application Names

Here the following code snippet used to retrieve the installed package in your device

  ListView programsList;
   PackageManager mPackageManager;
 

   programsList = (ListView) findViewById(R.id.ListView01);
    programsList.setTextFilterEnabled(true);
    mPackageManager = getPackageManager();
    List<String> packageName = new ArrayList<String>(); 
    List<ResolveInfo> list = mPackageManager.queryIntentActivities(
        new Intent(Intent.ACTION_MAIN), 0);
    for (ResolveInfo r : list) {
        packageName.add(r.loadLabel(mPackageManager).toString());
    }

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,  
    packageName);
    programsList.setAdapter(adapter);



Thursday, April 1, 2010

Content Provider Example - 3

Sample Code - MainActivity.java
public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        Button btn1 = (Button) findViewById(R.id.Button01);
        Button btn2 = (Button) findViewById(R.id.Button02);
       
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ContentValues values = new ContentValues();
                values.put(UserInfo.isactive, "Y");
                Uri uri = getContentResolver().insert(MyContentProvider.CONTENT_URI, values);
                Toast.makeText(MainActivity.this, "Item Added",Toast.LENGTH_LONG).show();
            }
        });

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String resultStr = "";
                Uri allTitles = Uri.parse("content://"+ MyContentProvider.PROVIDER_NAME + "/"+ UserInfo.DATABASE_TABLE);
                Cursor c = managedQuery(allTitles, null, null, null, "");
                if (c.moveToFirst()) {
                    do {
                        resultStr = c.getString(c.getColumnIndex(UserInfo._ID))+ ", "+ c.getString(c.getColumnIndex(UserInfo.isactive));
                        Toast.makeText(MainActivity.this, resultStr,Toast.LENGTH_LONG).show();
                    } while (c.moveToNext());
                }
            }
        });
    }

    public void readContact() {

        ArrayList<String> contactList;
        contactList = new ArrayList<String>();

        String[] columns = new String[] { People.NAME, People.NUMBER };
        Uri mContacts = People.CONTENT_URI;
        Cursor mCur = managedQuery(mContacts, columns, null, null, People.NAME+ " ASC ");
        if (mCur.moveToFirst()) {
            do {
                contactList.add(mCur.getString(mCur.getColumnIndex(People.NAME)));
            } while (mCur.moveToNext());
        }
        Toast.makeText(this, contactList.size() + "", Toast.LENGTH_LONG).show();
    }
}

-------------
MyContentProvider.java
public class MyContentProvider extends ContentProvider {
    public static final String PROVIDER_NAME = "com.contentproviderexample.mycontentprovider";
    public static final Uri CONTENT_URI = Uri.parse("content://"+ PROVIDER_NAME + "/demodb");   
    private static final UriMatcher uriMatcher;
    private SQLiteDatabase demoDB;   

    public static final class UserInfo implements BaseColumns {
        public static final String DATABASE_TABLE = "userinfo";
        public static final int USERINFO = 1;
        public static final int USERINFO_ID = 2;
        public static final Uri CONTENT_URI = Uri.parse("content://"+ PROVIDER_NAME + "/userinfo");
        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.contentproviderexample.userinfo";
        public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.contentproviderexample.userinfo";
        public static final String _ID = "_id";
        public static final String isactive = "isactive";
    }

    static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(PROVIDER_NAME, UserInfo.DATABASE_TABLE,UserInfo.USERINFO);       
        uriMatcher.addURI(PROVIDER_NAME, UserInfo.DATABASE_TABLE + "/#",UserInfo.USERINFO);
    }

    @Override
    public boolean onCreate() {
        Context context = getContext();
        SQLiteConnectionManager dbHelper = new SQLiteConnectionManager(context);
        demoDB = dbHelper.getWritableDatabase();
        return (demoDB == null) ? false : true;
    }

    @Override
    public String getType(Uri uri) {
        switch (uriMatcher.match(uri)) {
        case UserInfo.USERINFO:
            return UserInfo.CONTENT_TYPE;
        case UserInfo.USERINFO_ID:
            return UserInfo.CONTENT_ITEM_TYPE;
        default:
            throw new IllegalArgumentException("Unsupported URI: " + uri);
        }
    }
    @Override
    public Uri insert(Uri uri, ContentValues values) {

        long rowID = demoDB.insert(UserInfo.DATABASE_TABLE, "", values);
        if (rowID > 0) {
            Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
            getContext().getContentResolver().notifyChange(_uri, null);
            return _uri;
        }
        throw new SQLException("Failed to insert row into " + uri);
    }
    @Override
    public Cursor query(Uri uri, String[] projection, String selection,String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
        sqlBuilder.setTables(UserInfo.DATABASE_TABLE);
        if (uriMatcher.match(uri) == UserInfo.USERINFO_ID)
            sqlBuilder.appendWhere(UserInfo._ID + " = "+ uri.getPathSegments().get(1));
        Cursor c = sqlBuilder.query(demoDB, projection, selection,selectionArgs, null, null, sortOrder);
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    }
    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int count = 0;
        switch (uriMatcher.match(uri)) {
        case UserInfo.USERINFO:
            count = demoDB.delete(UserInfo.DATABASE_TABLE, selection,selectionArgs);
            break;

        case UserInfo.USERINFO_ID:
            String id = uri.getPathSegments().get(1);
            count = demoDB.delete(UserInfo.DATABASE_TABLE, UserInfo._ID+ " = "+ id+ (!TextUtils.isEmpty(selection) ? " AND (" + selection
                            + ')' : ""), selectionArgs);
            break;
           
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);

        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }
    @Override
    public int update(Uri uri, ContentValues values, String selection,String[] selectionArgs) {
        int count = 0;
        switch (uriMatcher.match(uri)) {
        case UserInfo.USERINFO:
            count = demoDB.update(UserInfo.DATABASE_TABLE, values, selection,selectionArgs);
            break;
        case UserInfo.USERINFO_ID:
            count = demoDB.update(UserInfo.DATABASE_TABLE, values, UserInfo._ID+ " = "+ uri.getPathSegments().get(1)
                    + (!TextUtils.isEmpty(selection) ? " AND (" + selection+ ')' : ""), selectionArgs);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }
}
--------
SQLiteConnectionManager .java
public class SQLiteConnectionManager extends SQLiteOpenHelper {

    private static final String DATABASENAME = "DEMODB";
    private static final int DATABASE_VERSION = 1;
    private static final String CREATE_USERINFO = "CREATE TABLE userinfo(_id INTEGER NOT NULL CONSTRAINT USER_PK PRIMARY KEY AUTOINCREMENT,isactive TEXT DEFAULT 'Y')";
    public SQLiteConnectionManager(Context context) {
        super(context, DATABASENAME, null, DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_USERINFO);
        Log.d("@G SQLConnectionFactory", " CREATE_LEADSOURCE Table ");
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}


Content Provider Example - 2

Implement the business login in the override methods.
   
    Using the onCreate Method we can initilze the Database
        @Override
        public boolean onCreate() {
            Context context = getContext();
            SQLiteConnectionManager dbHelper = new SQLiteConnectionManager(context);
            demoDB = dbHelper.getWritableDatabase();
            return (demoDB == null) ? false : true;
        }

    getType method is used to validate the input url
        @Override
        public String getType(Uri uri) {
            switch (uriMatcher.match(uri)) {
            case UserInfo.USERINFO:
                return UserInfo.CONTENT_TYPE;
            case UserInfo.USERINFO_ID:
                return UserInfo.CONTENT_ITEM_TYPE;
            default:
                throw new IllegalArgumentException("Unsupported URI: " + uri);
            }
        }


    CRUD Operation

    Create - insert()
        long rowID = demoDB.insert(UserInfo.DATABASE_TABLE, "", values);
        if (rowID > 0) {
            Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
            getContext().getContentResolver().notifyChange(_uri, null);
            return _uri;
        }

    Retrive - query()

        SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
        sqlBuilder.setTables(UserInfo.DATABASE_TABLE);
        if (uriMatcher.match(uri) == UserInfo.USERINFO_ID)
            sqlBuilder.appendWhere(UserInfo._ID + " = "+ uri.getPathSegments().get(1));
        Cursor c = sqlBuilder.query(demoDB, projection, selection,selectionArgs, null, null, sortOrder);
        c.setNotificationUri(getContext().getContentResolver(), uri);



    Update - update()
        int count = 0;
        switch (uriMatcher.match(uri)) {
        case UserInfo.USERINFO:
            count = demoDB.update(UserInfo.DATABASE_TABLE, values, selection,selectionArgs);
            break;

        case UserInfo.USERINFO_ID:
            count = demoDB.update(UserInfo.DATABASE_TABLE, values, UserInfo._ID+ " = "+ uri.getPathSegments().get(1)
                    + (!TextUtils.isEmpty(selection) ? " AND (" + selection+ ')' : ""), selectionArgs);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);



  Delete - delete()   
    int count = 0;
    switch (uriMatcher.match(uri)) {
        case UserInfo.USERINFO:
            count = demoDB.delete(UserInfo.DATABASE_TABLE, selection,selectionArgs);
            break;
        case UserInfo.USERINFO_ID:
            String id = uri.getPathSegments().get(1);
            count = demoDB.delete(UserInfo.DATABASE_TABLE, UserInfo._ID+ " = "+ id+ (!TextUtils.isEmpty(selection) ? " AND (" + selection+ ')' : ""), selectionArgs);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);

Create a Database Helper to Create database Schema
Refer : http://about-android.blogspot.com/2009/12/android-hello-world-activity-sample.html

Accessing Our Content Provider
    Create or Insert
        ContentValues values = new ContentValues();
        values.put(UserInfo.isactive, "Y");
        Uri uri = getContentResolver().insert(MyContentProvider.CONTENT_URI, values);

    Retrieve
        String resultStr = "";
        Uri allTitles = Uri.parse("content://"+ MyContentProvider.PROVIDER_NAME + "/"+ UserInfo.DATABASE_TABLE);

        Cursor c = managedQuery(allTitles, null, null, null, "");
        if (c.moveToFirst()) {
            do {
                resultStr = c.getString(c.getColumnIndex(UserInfo._ID))+ ", "+ c.getString(c.getColumnIndex(UserInfo.isactive));
                Toast.makeText(MainActivity.this, resultStr,Toast.LENGTH_LONG).show();
            } while (c.moveToNext());
        }

Content Provider Example - 1

In Android, a content provider is a specialized type of data store that exposes standardized ways to retrieve and manipulate the stored data.

You wish to share data between applications, you need to use the content provider model as recommended in Android. This article presents the basics of content providers and how you can implement one.

We are going to discuss following item here
  1. Using a Content Provider
  2. Create a Custom Content Provider

Using a Content Provider
Here are some of Android's most useful built-in content providers
Content Provider     Intended Data
Contacts                Contact details
Browser                 Browser bookmarks, browser history, etc.
CallLog                   Missed calls, call details, etc.
MediaStore             Media files such as audio, video and images
Settings                 Device settings and preferences

Here are the sample method for accessing the Contacts Content Provider.

public void readContact() {   
        ArrayList<String> contactList;
        contactList = new ArrayList<String>();

        String[] columns = new String[] { People.NAME, People.NUMBER };
        Uri mContacts = People.CONTENT_URI;
        Cursor mCur = managedQuery(mContacts, columns, null, null, People.NAME+ " ASC ");
        if (mCur.moveToFirst()) {
            do {
                contactList.add(mCur.getString(mCur.getColumnIndex(People.NAME)));
            } while (mCur.moveToNext());
        }
        Toast.makeText(this, contactList.size() + "", Toast.LENGTH_LONG).show();
    }



Create a Custom Content Provider
1. Create a Content Provier Class
2. Override the Following Methods
3. Declare the Constant Content Provider Values.
4. Implement the business login in the override methods.
5. Create a Database Helper to Create database Schema
6. Accessing Our Content Provider

Create a Content Provier Class
    Create a customized class which extend the ContentProvider Class. ContentProvider is an abstract Class, so we need to override the method in the content provider class.
        public class MyContentProvider extends ContentProvider{}

Override the Following Methods

    * onCreate(): Called when the provider is being started.
    * getType(): Returns the MIME type of the data at the given URI.       

    CRUD Operation
    * insert(): Inserts a new record into the content provider.
    * query(): Receives a request from a client. The result is returned as a Cursor object.
    * update(): Updates an existing record from the content provider.
    * delete(): Deletes an existing record from the content provider.          

   
   
Declare the Constant Content Provider Values.

1. Provider Name - Which is used to access the content provider.
        1. Standard prefix indicating that the data is controlled by a content provider. IT'S NEVER MODIFIED.
        2.The authority part of the URI; it identifies the content provider. For third-party applications, this should be a fully-qualified class name (reduced to lowercase) to ensure uniqueness. The authority is declared in the <provider> element's authorities attribute:
            <provider name=".TransportationProvider" authorities="com.example.transportationprovider"  . .  >
        3. The path that the content provider uses to determine what kind of data is being requested. This can be zero or more segments long. If the content provider exposes only one type of data (only trains, for example), it can be absent. If the provider exposes several types, including subtypes, it can be several segments long for example, "land/bus", "land/train", "sea/ship", and "sea/submarine" to give four possibilities.
        4. The ID of the specific record being requested, if any. This is the _ID value of the requested record. If the request is not limited to a single record, this segment and the trailing slash are omitted:

Example
         public static final String PROVIDER_NAME = "com.contentproviderexample.mycontentprovider"; // Same as Androidmanifest.xml entry
         public static final Uri CONTENT_URI = Uri.parse("content://"+ PROVIDER_NAME + "/demodb"); // URI for access the Content Provider


 2. Create a VO for Table with some content Provider Value
        For example i have create a table userinfo which contains the two column [id and isalive]. i have created the following VO class

 public static final class UserInfo implements BaseColumns {
            public static final String DATABASE_TABLE = "userinfo";
            public static final int USERINFO = 1;
            public static final int USERINFO_ID = 2;

            public static final Uri CONTENT_URI = Uri.parse("content://"
                    + PROVIDER_NAME + "/userinfo");
            public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.contentproviderexample.userinfo";
            public static fin
al String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.contentproviderexample.userinfo";

            public static final String _ID = "_id";
            public static final String isactive = "isactive";
        }


 3.Create  a object for UriMatcher. and add the our URL with UriMatcher

        static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(PROVIDER_NAME, UserInfo.DATABASE_TABLE,UserInfo.USERINFO);
        uriMatcher.addURI(PROVIDER_NAME, UserInfo.DATABASE_TABLE + "/#",UserInfo.USERINFO);
        }