Wednesday, 29 June 2011

About android3

Android Shell Commands

Here you can find the available command set in the shell by typing this at the android shell prompt:

dumpcrash, am, dumpstate, input, itr, monkey, pm, svc, ssltest,
debuggerd, dhcpcd, hostapd_cli, fillup, linker, logwrapper, telnetd, iftop, mkdosfs, mount,
mv, notify, netstat, printenv, reboot, ps, renice, rm, rmdir,rmmod, sendevent, schedtop,
ping, sh, hciattach, sdptool, logcat, servicemanager, dbus-daemon, debug_tool, flash_image, installd,
dvz, hostapd, htclogkernel, mountd, qemud, radiooptions, toolbox, hcid,
route, setprop, sleep, setconsole, smd, stop, top, start, umount,
vmstat, wipe, watchprops, sync, netcfg, Chmod, date, dd, cmp, cat, dmesg, df,
getevent, getprop, hd, id, ifconfig, insmod, ioctl, kill,
ln, log, lsmod, ls, mkdir, dumpsys, service, playmp3, sdutil,
rild, dalvikvm, dexopt, surfaceflinger, app_process, mediaserver, system_server,

Sunday, May 22, 2011

Combine two images in android java


In this blog we are combine two images and we have two images stored locally on an SD card or drawble folder in android.

Steps:

Read the image from Source
InputStream istream = context.getResources().openRawResource(R.drawable.img1);
try {
image1 = BitmapFactory.decodeStream(istream);
istream = context.getResources().openRawResource(R.drawable.img2);
image2 = BitmapFactory.decodeStream(istream);
} finally {
try {
istream.close();
} catch (IOException e) {
}
}

Define the Image property
int width = 0, height = 0;
if (c.getWidth() > s.getWidth()) {
width = c.getWidth();
height = c.getHeight() + s.getHeight();
} else {
width = s.getWidth();
height = c.getHeight() + s.getHeight();
}

Create your target Bitmap,
Bitmap combinedImages = Bitmap.createBitmap(width * 2, height, Bitmap.Config.ARGB_8888);

Create a Canvas for it,
Canvas comboImage = new Canvas(combinedImages);
Use Canvas.drawBitmap to blit each source bitmap into your target bitmap
comboImage.drawBitmap(image1, 0f, 0f, null);
comboImage.drawBitmap(image2, 0f, image1.getHeight()+1, null);

Example:
public Bitmap combineImages(Context context, int img1, int img2) {
// Bitmap[] mBitmap = new Bitmap[6];
Bitmap image1, image2;

InputStream istream = context.getResources().openRawResource(img1);
try {
image1 = BitmapFactory.decodeStream(istream);
istream = context.getResources().openRawResource(img2);
image2 = BitmapFactory.decodeStream(istream);
} finally {
try {
istream.close();
} catch (IOException e) {
}
}
int width = 0, height = 0;
if (c.getWidth() > s.getWidth()) {
width = c.getWidth();
height = c.getHeight() + s.getHeight();
} else {
width = s.getWidth();
height = c.getHeight() + s.getHeight();
}
Bitmap combinedImages = null;
combinedImages = Bitmap
.createBitmap(width * 2, height, Bitmap.Config.ARGB_8888);
Canvas comboImage = new Canvas(combinedImages);
comboImage.drawBitmap(c, 0f, 0f, null);
comboImage.drawBitmap(s, 0f, c.getHeight()+1, null);
return cs;
}

Sunday, May 15, 2011

Scrollable Text View in andriod -2


This article helps to making Scrollable TextView using TextView with dispatchKeyEvent

we can make a scrollable textview while implement the setMovementMethod and dispatchKeyEvent.

1. private TextView mTextView;

2. Set the Required data in the TextView
mTextView = (TextView) findViewById(R.id.textView1);
mTextView.setText("this is for testing \nthis is for testing \nthis is for testing
\nthis is for testing \nthis is for testing \nthis is for testing \n");

3. mTextView.setMovementMethod(new ScrollingMovementMethod(){.....})

4. Override the methods in ScrollingMovementMethod

new ScrollingMovementMethod() {
public void onTakeFocus(TextView widget, Spannable text, int dir) {}
@Override
public boolean onKeyDown(TextView widget, Spannable buffer,
int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:
for (int i = 0, scrollAmount = getScrollAmount(widget); i < scrollAmount; i++) {
down(widget, buffer);
}
return true;
case KeyEvent.KEYCODE_DPAD_UP:
for (int i = 0, scrollAmount = getScrollAmount(widget); i < scrollAmount; i++) {
up(widget, buffer);
}
return true;
default:
return super.onKeyDown(widget, buffer, keyCode, event);
}
}

private int getScrollAmount(TextView widget) {
final int visibleLineCount = (int) ((1f * widget.getHeight()) / widget
.getLineHeight());
int scrollAmount = visibleLineCount - 1;
if (scrollAmount < 1) {
scrollAmount = 1;
}
return scrollAmount;
}
}


5. Call the dispatch method in your code
mTextView.dispatchKeyEvent(event);


SAMPLE

public class MainActivity extends Activity {
/** Called when the activity is first created. */

private TextView mTextView;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.textView1);
mTextView
.setText("this is for testing \nthis is for testing \nthis is for testing \nthis is for testing \nthis is for testing \nthis is for testing \n");

mTextView.setMovementMethod(new ScrollingMovementMethod() {
public void onTakeFocus(TextView widget, Spannable text, int dir) {

}

@Override
public boolean onKeyDown(TextView widget, Spannable buffer,
int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:
for (int i = 0, scrollAmount = getScrollAmount(widget); i < scrollAmount; i++) {
down(widget, buffer);
}
return true;
case KeyEvent.KEYCODE_DPAD_UP:
for (int i = 0, scrollAmount = getScrollAmount(widget); i < scrollAmount; i++) {
up(widget, buffer);
}
return true;
default:
return super.onKeyDown(widget, buffer, keyCode, event);
}
}
private int getScrollAmount(TextView widget) {
final int visibleLineCount = (int) ((1f * widget.getHeight()) / widget
.getLineHeight());
int scrollAmount = visibleLineCount - 1;
if (scrollAmount < 1) {
scrollAmount = 1;
}
return scrollAmount;
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:

return true;
case KeyEvent.KEYCODE_DPAD_UP:
mTextView.dispatchKeyEvent(event);
return true;
default:
return super.onKeyDown(keyCode, event);
}
}
}

Scrollable Text View in andriod


This article helps to making Scrollable TextView in Android.

We can do it two ways. 1.Create a TextView inside the ScrollView and 2. TextView with dispatch Events.


Create a TextView inside the ScrollView
< ScrollView android:layout_width="fill_parent" android:layout_height="wrap_content"
android:fillViewport="true">
< LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent">
< TextView android:text="@+id/TextView01"
android:id="@+id/mTextView"
android:layout_width="fill_parent"
android:layout_height="fill_parent">< / TextView>

< / LinearLayout>
< / ScrollView>

Activity Implementation
mTextView = (TextView) findViewById(R.id.logTextView);
mTextView .setText("");
mTextView .setMovementMethod(ScrollingMovementMethod.getInstance());

Thursday, May 12, 2011

How to Obfuscated Android Code

Obfuscated code is source or machine code that has been made difficult to understand for humans. Programmers may deliberately obfuscate code to conceal its purpose or its logic to prevent tampering, deter reverse engineering, or as a puzzle or recreational challenge for someone reading the source code.
Programs known as obfuscators transform readable code into obfuscated code using various techniques. Code obfuscation is different in essence from hardware obfuscation, where description and/or structure of a circuit is modified to hide its functionality.


The following steps to describe the android obfuscation


1) Setup the obfuscated environment Download the follwing file before you starts
ProGuard
ProGuard is a free Java class file shrinker, optimizer, obfuscator, and preverifier. It detects and removes unused classes, fields, methods, and attributes. It optimizes bytecode and removes unused instructions. It renames the remaining classes, fields, and methods using short meaningless names. Finally, it preverifies the processed code for Java 6 or for Java Micro Edition.

Download files from internet
  • add-proguard-release.xml
  • procfg.txt
1) To update an existing Android project, open a command-line and navigate to the tools/ directory of your SDK. Now run:
android update project --name --target --path
2) So, now you have a signed build from the command line, but still no obfuscated build.
To make things easy, you’re going to want to get two helper files:

add-proguard-release.xml and procfg.txt
Copy these files into your root directory (where the build.xml file found).
3) To add Proguard to your build, you first need to edit your local properties file to add the location of the directory that Proguard is installed in:

proguard.dir=/Directory/Proguard/Is/Installed/In
3) Finally... you need to add our script to your build file and have it override a few targets. To do this, we use the XML “entity” construct. At the top of your build.xml file, add an entity that references our script file:
]
>
4) By default ADT creates a proguard.cfg file with every new project, so if you have an existing project just copy it over from a new dummy project. The next step is to enable ProGuard, you do this by adding the following to your default.properties file:
proguard.config=proguard.cfg
(assuming proguard.cfg is the ProGuard configuration file created for you, or copied from a new project, into the project root folder.)

Thursday, April 28, 2011

Read Text From the Raw Content in Resource Folder.

You can store the raw content in the raw folder and read using the below method..
1. Create a file in and Raw content
2. Create Method called readTextResource() in the util class
3. Use the below code to read the data
StringBuffer strBuffer = new StringBuffer();
InputStream inputStream = null;
try {
inputStream = owner.getResources().openRawResource(resourceId);
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String str = br.readLine();
while (str != null) {
strBuffer.append(str);
str = br.readLine();
}
} catch (IOException e) {
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
}
}
4. Return the StringBuffer value.
5. If you need a html format, you can use the html util class
Html.fromHtml(text); - It returns Spanned instance.

Sample Code
---------->
public class MainActivity extends Activity {

private Spanned mText = null;
private TextView mTextView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.sampleText);
if (mText == null) {
String text = readTextResource(R.raw.license, this);
mText = Html.fromHtml(text);
}
mTextView.setText(mText);
}
public String readTextResource(int resourceId, Activity owner) {
StringBuffer strBuffer = new StringBuffer();
InputStream inputStream = null;
try {
inputStream = owner.getResources().openRawResource(resourceId);
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String str = br.readLine();
while (str != null) {
strBuffer.append(str);
str = br.readLine();
}
} catch (IOException e) {
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
}
}
return strBuffer.toString();
}
}

Monday, April 25, 2011

Android Tips - Using Layout Param

Layout Param is used to change the layout properties. You can create a layout instance and assign to required view.

LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

Sample Code

LinearLayout.LayoutParams mLayoutParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button mButton = new Button(this);
mButton.setLayoutParams(layoutParam);

The above code works fine but this is not a current solution. It should like the below code

Button mButton = new Button(this);
ViewGroup.LayoutParam mLayoutParam= mButton.getLayoutParams();
mLayoutParam.height = ViewGroup.LayoutParams.FILL_PARENT


Thanks to Ashok , I have done the mistake and corrected me

Android Window Leak

The WindowLeaked exception in the log usually happens when you have some sort of async task that is finishing after the activity that began it is destroyed.
Solution for the above issue, we can dismiss the progress dialog before finish the activity.


Issue :

Activity com.sample.ViewLeakIssueActivity has leaked window com.android.internal.policy.impl.TvWindow$DecorView@6bc30788 that was originally added here
E/WindowManager( 1687): at android.view.ViewRoot.(ViewRoot.java:230)
E/WindowManager( 1687): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
-----

Sample Leak Issue
public class ViewLeakIssueActivity extends Activity {
volatile ProgressDialog pd;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pd = ProgressDialog.show(ViewLeakIssueActivity.this, "", "test...", true);

new Thread() {
public void run() {
try {
sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("@@@@@@@@@@@"+ViewLeakIssueActivity.this+pd.isShowing());

pd.dismiss();
}
}.start();

finish();

}

}

Solution for the above issue, we can dismiss the progress dialog before finish the activity.

@Override
public void finish() {
if(pd.isShowing()){
pd.dismiss();
}
super.finish();
}


Thursday, March 31, 2011

Android Versions...

Sample rating bar & sample handler

Sample Handler Implementation

Handler is a verry useful and powerful component in Android. Some special features of Handler are,

     If handler is created without any parameter, then it will be created in the same thread itself.
     We can pass data to handler using message

I have created the below sample application, which is using handler efficiently. Increment the count for one second.

So if we need to create a seperate thread for handler, first we need to create a thread and create the handler inside it.

MainActivity
public class MainActivity extends Activity {
    TextView tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) findViewById(R.id.TextView01);
        new Thread() {
            public void run() {
                int i = 0;
                while (i <= 100) {
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    messageHandler.sendMessage(Message
                            .obtain(messageHandler, i));
                    i++;
                }
            }
        }.start();
    }
    private Handler messageHandler = new Handler() {
        public void handleMessage(Message msg) {
            tv.setText(msg.what + "");
        }
    };
}


Main.xml
<?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">
<TextView android:text="@+id/TextView01" android:id="@+id/TextView01"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:textSize="25dip" android:layout_gravity="center"
    android:layout_marginTop="150dip"></TextView>
</LinearLayout>



Tuesday, June 8, 2010

Sample Rating Bar Implementation

A RatingBar is an extension of SeekBar and ProgressBar that shows a rating in stars.

The user can touch/drag or use arrow keys to set the rating when using the default size RatingBar.

The smaller RatingBar style and
the larger indicator-only style do not support user interaction and should only be used as indicators.


larger indicator-only    -    style="?android:attr/ratingBarStyleIndicator"
smaller RatingBar     -    style="?android:attr/ratingBarStyleSmall"
Default            -    style="?android:attr/ratingBarStyle"

create circle in android

Create a Circle in Andrind

In this Ariticle helps to create a circle in andriod using

Create a Customized View Class
public class Ball extends View {}

Override the onDraw()
protected void onDraw(Canvas canvas) { }

Create Paint Object for draw the circle
mPaints1 = new Paint();
        mPaints2 = new Paint();
        mPaints1.setAntiAlias(true);
        mPaints1.setStyle(Paint.Style.FILL);

        mPaints2 = new Paint(mPaints1);
        mPaints2.setColor(Color.BLUE);
        mBigOval = new RectF(40, 10, 280, 250);

Draw Circle using drawArc
canvas.drawArc(oval, mStart, mSweep, useCenter, paint);


SourceCode

public class Ball extends View {

    private Paint mPaints2;
    private Paint mPaints1;
    private RectF mBigOval;
    private float mStart, mSweep;
    private int mBigIndex;

    public Ball(Context context) {
        super(context);

        mPaints1 = new Paint();
        mPaints2 = new Paint();
        mPaints1.setAntiAlias(true);
        mPaints1.setStyle(Paint.Style.FILL);

        mPaints2 = new Paint(mPaints1);
        mPaints2.setColor(Color.BLUE);
        mBigOval = new RectF(40, 10, 280, 250);
    }

    private void drawArcs(Canvas canvas, RectF oval, boolean useCenter,
            Paint paint) {
        canvas.drawArc(oval, mStart, mSweep, useCenter, paint);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawColor(Color.WHITE);
        drawArcs(canvas, mBigOval, true, mPaints2);
        mSweep += 2;
        if (mSweep > 360) {
            mStart += 10;
            if (mStart >= 360) {
                mStart -= 360;
            }
            mBigIndex = (mBigIndex + 1);
        }
        invalidate();
    }
}


Monday, May 10, 2010

Steps to create Andriod Widget

In this article will help us to create customized Widget.

1. Create a Layout for Widget
2. Create Widget Class
3. Adding the Widget Provider Info Metadata
4. Register the Widget in Androidmanifest.xml
5. Add the Widget in your homepage


Create a Layout for Widget
<?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:background="@drawable/widget_bg">
    <Button android:text="Click" android:id="@+id/Button01"
        android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>

    <TextView android:id="@+id/text" android:layout_width="fill_parent"
        android:layout_height="fill_parent" android:text="@string/hello"
        android:gravity="center" android:textColor="@android:color/black" />
</LinearLayout>

Create Widget Class
public class Widget extends AppWidgetProvider {
    private SimpleDateFormat formatter = new SimpleDateFormat(
            "EEE, d MMM yyyy\nHH:mm:ss.SSS");

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {
       
        String now = formatter.format(new Date());

        Intent intent = new Intent(context, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,intent, 0);

        RemoteViews updateViews = new RemoteViews(context.getPackageName(),R.layout.main);
        updateViews.setTextViewText(R.id.text, now);
        appWidgetManager.updateAppWidget(appWidgetIds, updateViews);

       
        RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.main);
        views.setOnClickPendingIntent(R.id.Button01, pendingIntent);
        appWidgetManager.updateAppWidget(appWidgetIds, views);

        super.onUpdate(context, appWidgetManager, appWidgetIds);

    }
}

Adding the Widget Provider Info Metadata

    <?xml version="1.0" encoding="utf-8"?>
    <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
        android:minWidth="166dip" android:minHeight="72dip" android:updatePeriodMillis="60000" android:initialLayout="@layout/main" />


Register the Widget in Androidmanifest.xml

    <receiver android:label="@string/widget_name" android:name=".Widget">       
        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
        </intent-filter>       
        <meta-data android:name="android.appwidget.provider" android:resource="@xml/widget" />       
    </receiver>

Add the Widget in your homepage
    Click Menu -> Add -> Widget -> YOUR WIDGET





Sunday, May 9, 2010

Andriond Interview Question -1

Brief about the Android?
Andriod is a Operating System for device
It was initially developed by Android Inc., a firm later purchased by Google, and lately by the Open Handset Alliance.
It allows developers to write managed code in the Java language, controlling the device via Google-developed Java libraries.

Architecture of Android :
1. Linux Kernal [ 2.6 Kernal - security, memory management, process management, network stack, and driver model]
2. Native Libraries [SQLite, WEBKit, OpenGL,..]
3. Runtime + Dalvik VM [.dex format, Lightweight VM, Efficient Dalvik Bytecode]
4. Application Framework [Activity Manager, Content Manager, Location Manager, ]
5. Application [ System Apps and Your Apps]

Refer : http://about-android.blogspot.com/2009/11/architecture-of-android-1.html


What are the basic Components in Android?
Activities - An activity presents a visual user interface for one focused endeavor the user can undertake.
Services - A service doesn't have a visual user interface, but rather runs in the background for an indefinite period of time.
Broadcast receivers - A broadcast receiver is a component that does nothing but receive and react to broadcast announcements.
Content providers - A content provider makes a specific set of the application's data available to other applications.

http://about-android.blogspot.com/2009/11/application-fundamentals.html



what are the versions are avilable in android?
Version : 1.5 - Cupecake
Linux Version : 2.6.27
Offical release On : April 30th 2009
Main Feature :
* Ability to record and watch videos with the camcorder mode
* Uploading videos to YouTube and pictures to Picasa directly from the phone
* A new soft keyboard with an "Autocomplete" feature
* Bluetooth A2DP support and ability to automatically connect to a Bluetooth headset within a certain distance
* New widgets and folders that can populate the Home screens
* Animations between screens
* Expanded ability of Copy and paste to include web pages

Version : 1.6 - Donut
Linux Version : 2.6.29
Offical release On : April 30th 2009
Main Features :
* An improved Android Market experience.
* An integrated camera, camcorder, and gallery interface.
* Gallery now enables users to select multiple photos for deletion.
* Updated Voice Search, with faster response and deeper integration with native applications, including the ability to dial contacts.
* Updated search experience to allow searching bookmarks, history, contacts, and the web from the home screen.
* Updated Technology support for CDMA/EVDO, 802.1x, VPN, Gestures, and a Text-to-speech engine.
* Support for WVGA resolutions.
* Speed improvements for searching & the camera.[35]

Version : 2.0 & 2.1- Eclair
Linux Version : 2.6.29
Offical release On : October 26th 2009
Main Features :
* Optimized hardware speed
* Support for more screen sizes and resolutions
* Revamped UI
* New browser UI and HTML5 support
* New contact lists
* Better white/black ratio for backgrounds
* Improved Google Maps 3.1.2
* Microsoft Exchange support
* Built in flash support for Camera
* Digital Zoom
* MotionEvent class enhanced to track multi-touch events[41]
* Improved virtual keyboard
* Bluetooth 2.1
* Live Wallpapers

what is the folder structure of android?
1. src - It contain the java code
2. Resource - It contain the all resource with different floder
drawable - Icon
raw - Sounds
menu - Menu
values - Project Properties
layout - User interface Screens
3. gen - It contains the R.java file. You could not edit R.java manually. This have been generated automatically by understanding resource files etc.
4. AndroidManifest -It contains the Project properties
5. Android lib.

Refer :
http://about-android.blogspot.com/2009/11/application-fundamentals.html

what are the api available in the Android?
Activity Manager, WindowManager, Location Manager, View System, Notification Manager, Telephonic Manager, Package Manager,
Resource Manager,

Friday, May 7, 2010

Create Dynamic View Group

In this Aricle help us to create a dynamic view group.

public class MainActivity extends Activity {
    Button btn, btn1;
    LayoutInflater linflater;
    LinearLayout l;
    static int pos = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn = (Button) findViewById(R.id.Button01);
        btn1 = (Button) findViewById(R.id.Button02);
        l = (LinearLayout) findViewById(R.id.LinearLayout01);
        linflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        btn.setOnClickListener(new myListener());
        btn1.setOnClickListener(new myListener1());
    }

    class myListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            View myView = linflater.inflate(R.layout.dynamicoption, null);
            myView.setId(pos);
            pos++;
            l.addView(myView);
        }
    }

    class myListener1 implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if (pos != 0) {
                pos--;
                View myView = l.findViewById(pos);
                l.removeView(myView);
            }
        }
    }
}

main.xml
<?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="horizontal">

    <Button android:id="@+id/Button01" android:background="@drawable/plus"
        android:layout_height="45dip" android:layout_width="45dip"></Button>

    <Button android:id="@+id/Button02" android:background="@drawable/minus"
        android:layout_height="45dip" android:layout_width="45dip"></Button>

    <LinearLayout android:id="@+id/LinearLayout01"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:orientation="vertical"></LinearLayout>
</LinearLayout>

dynamicoption.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:orientation="horizontal">
    <EditText android:text="@+id/EditText01" android:id="@+id/EditText01"
        android:layout_width="wrap_content" android:layout_height="wrap_content"></EditText>
    <Button android:text="@+id/Button01" android:id="@+id/Button01"
        android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>

Icons
http://jmez.net/el/images/Minus.png
http://www.workingwithrails.com/images/plus.png?1213632569

About android 2

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