Wednesday, April 28, 2010

Multitasking the Android Way

[This post is by Dianne Hackborn, a Software Engineer who sits very near the exact center of everything Android. — Tim Bray]

Android is fairly unique in the ways it allows multiple applications to run at the same time. Developers coming from a different platform may find the way it operates surprising. Understanding its behavior is important for designing applications that will work well and integrate seamlessly with the rest of the Android platform. This article covers the reasons for Android's multitasking design, its impact on how applications work, and how you can best take advantage of Android's unique features.

Design considerations

Mobile devices have technical limitations and user experience requirements not present in desktop or web systems. Here are the four key constraints we were working under as we designed Android's multitasking:

  • We did not want to require that users close applications when "done" with them. Such a usage pattern does not work well in a mobile environment, where usage tends to involve repeated brief contact with a wide variety of applications throughout the day.

  • Mobile devices don't have the luxury of swap space, so have fairly hard limits on memory use. Robert Love has a very good article covering the topic.

  • Application switching on a mobile device is extremely critical; we target significantly less than 1 second to launch a new application. This is especially important when the user is switching between a few applications, such as switching to look at a new SMS message while watching a video, and then returning to that video. A noticeable wait in such situations will quickly make users hate you.

  • The available APIs must be sufficient for writing the built-in Google applications, as part of our "all applications are created equal" philosophy. This means background music playback, data syncing, GPS navigation, and application downloading must be implemented with the same APIs that are available to third party developers.

The first two requirements highlight an interesting conflict. We don't want users to worry about closing their apps, but rather make it appear that all of the applications are always running. At the same time, mobile devices have hard limits on memory use, so that a system will degrade or even start failing very quickly as it needs more RAM than is available; a desktop computer, with swap, in contrast will simply start slowing down as it needs to page RAM to its swap space. These competing constraints were a key motivation for Android's design.

When does an application "stop"?

A common misunderstanding about Android multitasking is the difference between a process and an application. In Android these are not tightly coupled entities: applications may seem present to the user without an actual process currently running the app; multiple applications may share processes, or one application may make use of multiple processes depending on its needs; the process(es) of an application may be kept around by Android even when that application is not actively doing something.

The fact that you can see an application's process "running" does not mean the application is running or doing anything. It may simply be there because Android needed it at some point, and has decided that it would be best to keep it around in case it needs it again. Likewise, you may leave an application for a little bit and return to it from where you left off, and during that time Android may have needed to get rid of the process for other things.

A key to how Android handles applications in this way is that processes don't shut down cleanly. When the user leaves an application, its process is kept around in the background, allowing it to continue working (for example downloading web pages) if needed, and come immediately to the foreground if the user returns to it. If a device never runs out of memory, then Android will keep all of these processes around, truly leaving all applications "running" all of the time.

Of course, there is a limited amount of memory, and to accommodate this Android must decide when to get rid of processes that are not needed. This leads to Android's process lifecycle, the rules it uses to decide how important each process is and thus the next one that should be dropped. These rules are based on both how important a process is for the user's current experience, as well as how long it has been since the process was last needed by the user.

Once Android determines that it needs to remove a process, it does this brutally, simply force-killing it. The kernel can then immediately reclaim all resources needed by the process, without relying on that application being well written and responsive to a polite request to exit. Allowing the kernel to immediately reclaim application resources makes it a lot easier to avoid serious out of memory situations.

If a user later returns to an application that's been killed, Android needs a way to re-launch it in the same state as it was last seen, to preserve the "all applications are running all of the time" experience. This is done by keeping track of the parts of the application the user is aware of (the Activities), and re-starting them with information about the last state they were seen in. This last state is generated each time the user leaves that part of the application, not when it is killed, so that the kernel can later freely kill it without depending on the application to respond correctly at that point.

In some ways, Android's process management can be seen as a form of swap space: application processes represent a certain amount of in-use memory; when memory is low, some processes can be killed (swapped out); when those processes are needed again, they can be re-started from their last saved state (swapped in).

Explicitly running in the background

So far, we have a way for applications to implicitly do work in the background, as long as the process doesn't get killed by Android as part of its regular memory management. This is fine for things like loading web pages in the background, but what about features with harder requirements? Background music playback, data synchronization, location tracking, alarm clocks, etc.

For these tasks, the application needs a way to tell Android "I would explicitly like to run at this point." There are two main facilities available to applications for this, represented by two kinds of components they can publish in their manifest: broadcast receivers and services.

Broadcast Receivers

A BroadcastReceiver allows an application to run, for a brief amount of time, in the background as a result of something else happening. It can be used in many ways to build higher-level facilities: for example the AlarmManager allows an application to have a broadcast sent at a certain time in the future, and the LocationManager can send a broadcast when it detects interesting changes in location. Because information about the receiver is part of an application's manifest, Android can find and launch the application even if it isn't running; of course if it already has its process available in the background, the broadcast can very efficiently be directly dispatched to it.

When handling a broadcast, the application is given a fixed set of time (currently 10 seconds) in which to do its work. If it doesn't complete in that time, the application is considered to be misbehaving, and its process immediately tossed into the background state to be killed for memory if needed.

Broadcast receivers are great for doing small pieces of work in response to an external stimulus, such as posting a notification to the user after being sent a new GPS location report. They are very lightweight, since the application's process only needs to be around while actively receiving the broadcast. Because they are active for a deterministic amount of time, fairly strong guarantees can be made about not killing their process while running. However they are not appropriate for anything of indeterminate length, such as networking.

Services

A Service allows an application to implement longer-running background operations. There are actually a lot of other functions that services provide, but for the discussion here their fundamental purpose is for an application to say "hey I would like to continue running even while in the background, until I say I am done." An application controls when its service runs by explicitly starting and stopping the service.

While services do provide a rich client-server model, its use is optional. Upon starting an application's services, Android simply instantiates the component in the application's process to provide its context. How it is used after that is up to the application: it can put all of the needed code inside of the service itself without interacting with other parts of the application, make calls on other singleton objects shared with other parts of the app, directly retrieve the Service instance from elsewhere if needed, or run it in another process and do a full-blown RPC protocol if that is desired.

Process management for services is different than broadcast receivers, because an unbounded number of services can ask to be running for an unknown amount of time. There may not be enough RAM to have all of the requesting services run, so as a result no strong guarantees are made about being able to keep them running.

If there is too little RAM, processes hosting services will be immediately killed like background processes are. However, if appropriate, Android will remember that these services wish to remain running, and restart their process at a later time when more RAM is available. For example, if the user goes to a web page that requires large amounts of RAM, Android may kill background service processes like sync until the browser's memory needs go down.

Services can further negotiate this behavior by requesting they be considered "foreground." This places the service in a "please don't kill" state, but requires that it include a notification to the user about it actively running. This is useful for services such as background music playback or car navigation, which the user is actively aware of; when you're playing music and using the browser, you can always see the music-playing glyph in the status bar. Android won't try to kill these services, but as a trade-off, ensures the user knows about them and is able to explicitly stop them when desired.

The value of generic components

Android's generic broadcast receiver and service components allow developers to create a wide variety of efficient background operations, including things that were never originally considered. In Android 1.0 they were used to implement nearly all of the background behavior that the built-in and proprietary Google apps provided:

  • Music playback runs in a service to allow it to continue operating after the user leaves the music application.

  • The alarm clock schedules a broadcast receiver with the alarm manager, to go off at the next set alarm time.

  • The calendar application likewise schedules an alarm to display or update its notification at the appropriate time for the next calendar event.

  • Background file download is implemented a service that runs when there are any downloads to process.

  • The e-mail application schedules an alarm to wake up a service at regular intervals that looks for and retrieves any new mail.

  • The Google applications maintain a service to receive push notifications from the network; it in turn sends broadcasts to individual apps when it is told that they need to do things like synchronize contacts.

As the platform has evolved, these same basic components have been used to implement many of the major new developer features:

  • Input methods are implemented by developers as a Service component that Android manages and works with to display as the current IME.

  • Application widgets are broadcast receivers that Android sends broadcasts to when it needs to interact with them. This allows app widgets to be quite lightweight, by not needing their application's process remain running.

  • Accessibility features are implemented as services that Android keeps running while in use and sends appropriate information to about user interactions.

  • Sync adapters introduced in Android 2.0 are services that are run in the background when a particular data sync needs to be performed.

  • Live wallpapers are a service started by Android when selected by the user.

More Blogginess

Hello everyone, and welcome to a rare (in this space) blog about blogging. My name is Tim Bray, and I’m the new editor of this Android Developers’ Blog. I am only a student of Android, but I’m a veteran blogger, I’m part of the Android team, and they’ve given me a pretty free hand to find and publish the interesting stories. I’m expecting to enjoy this and hope you will too.

The work on Android is done at various places around the world, but in Mountain View, California there’s a building on the Google campus with an Android statue in front of it, positioned among dessert-themed sculptures that illustrate the major platform releases to date.

As of now, this blog has a header image taken from where some of the Android work happens, behind the statuary looking out. There are a ton of places on the Internet where you can read people’s opinions about what’s happening next with Android, and a lot of them are good. The one you’re reading now is the one that’s written from the inside looking out.

History

This space has been used mostly in a just-the-facts press-release-flavored way and, while that’s been useful, I thought it could be livelier. Because, even after only a few weeks’ exposure to what’s going on here, I’ve discovered that there are a ton of interesting Android stories, and while some of them probably have to be secrets, there are more than enough we can tell to crank up the interest level here.

I offered this opinion internally, loudly and repeatedly, and Android management surprised me by coming back with “OK, it’s your problem now.”

Future

I’m not going to write everything here; I’m going to track down the people who actually do the creative Android-building work and get them to tell their own stories. I will bend over backward to make sure the articles have the voices of the people who write them.

We will go on being a source for hard opinion-free just-the-facts Android news. But I’d like to surround each burst of that with a cluster of reportage about what it means and how we think it will affect the Android communities.

The immediate future is going to be pretty intense, because we’re only a few weeks away from Google I/O, and I don’t think that I’m telling any secrets when I say that there will be Android-related announcements at that event. So the problems that come with the new job probably won’t include scaring up content.

The first new-flavor post is going to be on a currently-hot subject, multitasking and background processing, written by an engineer at the center of the Android universe.

Wish me luck, and stay tuned!

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




 
© 2011 collection of android application | Except as noted, this content is licensed under Creative Commons Attribution 2.5.
For details and restrictions, see the Content License | Recode by Ardhiansyam | Based on Android Developers Blog