Wednesday 17 April 2013

Select + copy text in a TextView?

 Generally we can copy / paste the value from EditText by long click. It is in-build functionality of Android. Now lets say you have requirement same thing in TextView. Then you have to use registerForContextMenu.


 Like  registerForContextMenu(yourtextview);

 and your TextView will be registered for receiving context menu events.

Then You have to override onCreateContextMenu() method. Following is entire code.


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

    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        // user has long pressed your TextView
        menu.add(0, v.getId(), 0,
                "Copy");

        // cast the received View to TextView so that you can get its text
        TextView yourTextView = (TextView) v;

        // place your TextView's text in clipboard
        ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        clipboard.setText(yourTextView.getText());
    }






 


Monday 15 April 2013

How to set background color with borders to perticular View dynamically in android


Hello, Today I will explain you how to set background color + borders to particular view in android.

Let's say You have one button and you have to set background color RED with border color gray, for that you have to use GradientDrawable.


 GradientDrawable drawable = new GradientDrawable();
  drawable.setShape(GradientDrawable.RECTANGLE);
  drawable.setCornerRadius(10);
  drawable.setStroke(2, Color.GRAY);
  drawable.setColor(Color.RED)); 
 
 btnBlackColor.setBackgroundDrawable(drawable);




Thursday 11 April 2013

How to put imageview on another imageview tranperent ?

Hello,

  Today I explain how to put ImageView on another ImageView as Transparent.

 Following is an xml file.

main.xml


<?xml version="1.0" encoding="utf-8"?>
 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

     <ImageView       
android:id="@+id/first"       
android:layout_width="fill_parent"       
android:layout_height="fill_parent"       
android:src="@drawable/ic_launcher" >   
</ImageView>   

<ImageView       
android:id="@+id/second"       
android:layout_width="fill_parent"       
android:layout_height="fill_parent"
         android:background="@android:color/transparent"         android:src="@drawable/bg4" />
</FrameLayout>


 Following is JAVA file.

TransperentViewOnAnotherViewActivity.java

public class TransperentViewOnAnotherViewActivity extends Activity {

    /** Called when the activity is first created. */
    ImageView first, second;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        first = (ImageView) findViewById(R.id.first);
        second = (ImageView) findViewById(R.id.second);
        second.setAlpha(127);
    }

}



Description : Using setAlpha() we can Sets the opacity of the view. You can get more information from developer site.

Output :

How to calculate difference between two dates in android ?


Following is code for get difference between two dates (date1 and date2). 

long difference = date2.getTime() - date1.getTime(); 
days = (int) (difference / (1000*60*60*24));  
hours = (int) ((difference - (1000*60*60*24*days)) / (1000*60*60)); 
min = (int) (difference - (1000*60*60*24*days) - (1000*60*60*hours)) / (1000*60);
 Visit : Visit My answer Here 

How to update price of an application on Google Play Store?

Now I want to share steps for update price of an application on google play store.

 Suppose you published paid application on google play store, Now you have to update price of an app then following are steps.


1.  Logging in to your google account

 >> Developer Login


2.  Selecting your application which you want to update.

3.  Selecting Pricing and Distribution

4.  Changing the current price to new one in the default price section

5.  Clicked on save and update.


Now wait for 2 to 3 hours your price will be updated on google play store.

Wednesday 3 April 2013

How to display image from URL in android ?

Now we have to explain how to display image from URL. ImageView is used to display image in android. Here we use AsyncTask for loading image from URL.  Now lets we explain it with Example.




Above is our final Screen shot  display image from URL.


 Create new Android Project AndroidAdvanceDisplayImageURL.
 Layout file main.xml looks like following.


 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        android:text />

    <ImageView
        android:id="@+id/my_image"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</LinearLayout>



 -> Here we take imageview to display image. Now coding part.


  AndroidAdvanceImageLoad.java

 public class AndroidAdvanceImageLoad extends Activity {

    ImageView my_img;
    Bitmap mybitmap;
    ProgressDialog pd;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        new DisplayImageFromURL((ImageView) findViewById(R.id.my_image))
                .execute("http://www.tmonews.com/wp-content/uploads/2012/10/androidfigure.jpg");

    }
    private class DisplayImageFromURL extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            pd = new ProgressDialog(AndroidAdvanceImageLoad.this);
            pd.setMessage("Loading...");
            pd.show();
        }
        public DisplayImageFromURL(ImageView bmImage) {
            this.bmImage = bmImage;
        }
        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }

            return mIcon11;

        }
        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
            pd.dismiss();
        }
    }
}


  -> Here we create DisplayImageFromURL class which loads image from URL and display it on imageview. It take 2 arguments one is image id and another is Image URL from which you display image. 

How to create Custom dialog in android ? How it useful for real world programming ?

Custom dialog created by using your layout file and that file you can bind your layout to dialog box.And it is useful when we have to integrate facebook,twitter and all other real word programming.

Steps To Create Custom Dialog
==========================

1. Create your layout which is shown in dialog.
2. Bind that layout file to dialog
3. Show your Dialog on any event.
4. Done





1.Layout your android custom dialog in xml file. create new project in android and give name CustomDialog in that layout folder create file login.xml which is your dialog file and write above code.

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  android:layout_width="match_parent"     android:layout_height="wrap_content"    android:background="#ff00ff"   android:orientation="vertical">      <TextView          android:id="@+id/username_view"         android:layout_height="wrap_content"         android:layout_width="wrap_content"         android:layout_marginLeft="20dip"         android:layout_marginRight="20dip"         android:text="@string/username"         android:gravity="left"         android:textAppearance="?android:attr/textAppearanceMedium"       />                  <EditText        android:id="@+id/username_edit"        android:layout_height="wrap_content"        android:layout_width="match_parent"        android:layout_marginLeft="20dip"        android:layout_marginRight="20dip"        android:scrollHorizontally="true"        android:autoText="false"        android:singleLine="true"        android:capitalize="none"        android:gravity="fill_horizontal"        android:textAppearance="?android:attr/textAppearanceMedium" />     <TextView        android:id="@+id/password_view"        android:layout_height="wrap_content"        android:layout_width="wrap_content"        android:layout_marginLeft="20dip"        android:layout_marginRight="20dip"        android:text="@string/password"        android:gravity="left"        android:textAppearance="?android:attr/textAppearanceMedium"       />       <EditText         android:id="@+id/password_edit"       android:layout_height="wrap_content"       android:layout_width="match_parent"       android:layout_marginLeft="20dip"       android:layout_marginRight="20dip"       android:scrollHorizontally="true"       android:autoText="false"       android:singleLine="true"       android:capitalize="none"       android:gravity="fill_horizontal"       android:password="true"       android:textAppearance="?android:attr/textAppearanceMedium"       />  </LinearLayout>

2. Now create your second xml file call first.xml file in layout which is shown after login done

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"  android:orientation="vertical"  android:layout_width="match_parent"  android:layout_height="match_parent"        <TextView       android:layout_width="wrap_content"       android:layout_height="wrap_content"        android:text="Welcome to First Page"         android:textColor="#00ff00"     /> </LinearLayout>

Android project structure

Create new project "AndroidAdvanceHelloWorld"in eclipse.
After you create a new project in eclipse, you will see the following top-level folders in your project.



 Let we explain each step by step.



 (1) "src" folder

This folder will contain the Java source files that you will be creating. In the screenshot you can see the ‘activity’ files that were created for the sample project. The files inside this  folder will be organized according to the package structure. This is similar to the /src folder which is present in any normal Java project.

You can have more than one package in your Android application. Its always a good practice to break the source code of your application into different packages based on its core functionality.  All the source files of your Activities, Services etc. Goes into this folder. In the above screen, you can see the source file of the Activity that we created for our project.


 (2) "gen" folder
The gen directory in an Android project contains generated values. R.java is a generated class which contains references to certain resources of the project.

If you create a new resource, the corresponding reference is automatically created in R.java via the Eclipse ADT tools. These references are static integer values and define IDs for the resources.

The Android system provides methods to access the corresponding resource via these IDs.

For example to access a String with the R.string.yourString ID, you would use the getString(R.string.yourString)) method.

R.java is automatically created by the Eclipse development environment, manual changes are not necessary and will be overridden by the tooling.


 (3) "android-version number"
The android-version number folder, which will contain the libraries (jars/android.jar)  that are need for the project. In the screenshot, you can see that it contains the framework jar file. This is similar to the /lib folder which is present in any normal Java project.


 (4) "res" folder
This directory contains all the external resources (images, data files etc) that are used by the android application. These external resources (content) will be referenced in the android application.

 The "res" folder also contains sub-folders like following.

 -> /res/drawable                        -- Bitmap files / Nine-Patches (re-sizable bitmaps) / State lists / Shapes / Animation drawables / Other drawables
 -> /res/layout                             -- XML files that define a user interface layout.
 -> /res/values                            -- XML files that contain simple values, such as strings, integers, and colors.
                                      
                                                         arrays.xml for resource arrays (typed arrays).
                                                         colors.xml for color values
                                                         dimens.xml for dimension values.
                                                         strings.xml for string values.
                                                         styles.xml for styles.

 -> /res/drawable-hdpi               -- The hdpi qualifier indicates that the resources in that directory are for devices with a high-density screen.

 -> /res/drawable-ldpi                -- The ldpi qualifier indicates that the resources in that directory are for devices with a low-density screen.

 -> /res/drawable-mdpi              -- The mdpi qualifier indicates that the resources in that directory are for devices with a medium-density screen.

 -> /res/drawable-xhdpi            -- The xhdpi qualifier indicates that the resources in that directory are for devices with a extra Large-density screen.

 -> /res/anim                             -- XML files that define tween animations

 -> /res/color                             -- XML files that define a state list of colors.

 -> /res/menu                            -- XML files that define application menus, such as an Options Menu, Context Menu, or Sub Menu.

 -> /res/raw                               -- Arbitrary files to save in their raw form.

 (5) "assets" folder

This folder also contains external resources used in the application like the /res folder. But the main difference is that the resources are stored in raw format and can be read only programmatically.

 (6) AndroidManifest.xml

The components and settings of an Android application are described in the AndroidManifest.xml file. For example all Activities and Services of the application must be declared in this file. It must also contain the required permissions for the application.

Google Play requires that every Android application uses its own unique package. Therefore it is a good habit to use your reverse domain name as package name. This will avoid collisions with other Android applications. It contains information about various activities, views, services etc.

 I hope this tutorial helps you.

What is Listview in android and how to work with android Listview ?

Android provides the ListView class which is capable of displaying a scrollable list of items. These items can be of any type.

 Now lets take one example of ListView. We can understand ListView step by step.

 Step 1 :- Create one project give it name ListViewDemo. now in main.xml file we take one ListView like following.

  main.xml

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:text="Android Advance Listview Demo"
        android:textColor="#ff9966"
        android:textSize="20dp"
        android:text />
    <ListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
    </ListView>
</LinearLayout>

 step 2 :- Now we create one java file which items in a list and handle events.

 ListVIewDemoActivity.java

  public class ListVIewDemoActivity extends Activity implements OnClickListener {
    ListView listview;   
    ArrayList<String> listviewitems = new ArrayList<String>();

    // listviewitems is array which display items in a list

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Now get id of ListView 
        listview = (ListView) findViewById(R.id.listview);
         
    }
  @Override
    protected void onResume() {
        super.onResume();
    
        we need to clear listviewitems every time becase when this activity resumes it add elements to the list so first clear listview and after we add elements to listviewitems.

        listviewitems.clear();
        listviewitems.add("Animals");
        listviewitems.add("Birds");
        listviewitems.add("Fruits");
        listviewitems.add("Computer Parts");
        listviewitems.add("Electronic Products");

    A ListView receives its data via an adapter. The adapter also defines how each row is the ListView is displayed.  The adapter is assigned to the list via the setAdapter method on the ListView object.   An adapter extend the BaseAdapter class. Android provides several standard adapters; the most important are ArrayAdapter and CursorAdapter. Here we use BaseAdapter.

        listview.setAdapter(new ListAdapter(this, this));
    }

  Now we have to create our own ListAdapter for listview adapter.

  private class ListAdapter extends BaseAdapter {
        LayoutInflater inflater;

       we have to create one inner class ViewHolder for storing child views.
        ViewHolder viewHolder;
        Activity activity;


      constructor of ListAdapter
    public ListAdapter(Context context, Activity act) {
            inflater = LayoutInflater.from(context);
            this.activity = act;
        }


   getCount() display total numbers of items in a list
  public int getCount() {
            return listviewitems.size();
        }

  public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(final int position, View convertView,
                ViewGroup parent) {
            if (convertView == null) {

                convertView = inflater.inflate(R.layout.list_row, null);
                viewHolder = new ViewHolder();

                viewHolder.pname = (TextView) convertView
                        .findViewById(R.id.txtname);

                convertView.setTag(viewHolder);

            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            viewHolder.pname.setText(listviewitems.get(position));

        To react to selections in the list set an OnItemClickListener to your ListView.

            convertView.setOnClickListener(new OnItemClickListener(position));
            return convertView;

        }
    }
  Within the getView() method you would inflate an XML based layout and then set the values of the individual Views in the layout. For inflating an XML layout you can use the system service LayoutInflator. This service can get accessed via the Activity or via the context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) method call.

  private class ViewHolder {
        TextView pname;
    }

  Now we create our own listener for the listview item click.

  private class OnItemClickListener implements OnClickListener {
        private int mPosition;

        OnItemClickListener(int position) {
            mPosition = position;
        }

        public void onClick(View v) {

            Toast.makeText(ListVIewDemoActivity.this,
                    "" + listviewitems.get(mPosition), Toast.LENGTH_LONG)
                    .show();

      we pass position which is clicked in listview to next activity by passing intent to ListItemDetail.java.
            Intent i = new Intent(ListVIewDemoActivity.this,
                    ListItemDetail.class);
            i.putExtra("position", "" + mPosition);
            startActivity(i);
        }

    }
  step 3 :-  we need to create list_row.xml file for list row display so create new xml file like following.

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
        <TextView
            android:id="@+id/txtname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="20dp"
            android:text="Product Name"
            android:textColor="#FF9900"
            android:textSize="22dp"
            android:text />
    </LinearLayout>
</LinearLayout>

  Step 4 :- Now for dispay item which is clicked we have to create new class name it to ListItemDetail.java. We display image corresponding to item click on listview so create one xml file which display image.


  listitemdetail.xml

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <ImageView
        android:id="@+id/imageview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</LinearLayout>

  ListItemDetail.java
   public class ListItemDetail extends Activity {
    
       we get position and store it to variable.
      int position;
      ImageView image;
     
    int[] images = { R.drawable.animals, R.drawable.birds, R.drawable.fruits,
            R.drawable.pcparts, R.drawable.electronics };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listitemdetail);
        Bundle extras = getIntent().getExtras();
        if (extras != null) {

              now get position which is passed from first activity. Here we pass from first activity using putExtra() so we must covert it in integer by using Integer.valueOf() method by using following.

            position = Integer.valueOf(extras.getString("position"));
            image = (ImageView) findViewById(R.id.imageview);

            We set image on imageview by using  setBackgroundResource() method.
            image.setBackgroundResource(images[position]);
        }
    }
}


How to send SMS in android ?

In android you can send SMS by using SmsManager API. Now we have to describe how send SMS in android pragmatically.

  step 1 :- Create new project give name it to SendSMSDemo. Now we need two TextViews (one for enter phone number and one for message) and one Button for handling event of sending SMS.  Your xml looks like this.

 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="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Android Advance SEND SMS "
        android:textSize="23dp" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:orientation="vertical" >

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Enter Phone Number"
            android:textSize="16dp"
            android:text />

        <EditText
            android:id="@+id/txtnumbers"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:input />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:orientation="vertical" >

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Enter Your Message"
            android:textSize="16dp"
            android:text />

        <EditText
            android:id="@+id/txtnotes"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp" />
    </LinearLayout>

    <Button
        android:id="@+id/btnsend"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="Send Message" />

</LinearLayout>

  Step 2 :- Now corresponding to this you need to handle event of send SMS. Now when button clicked we have to check phone number field is    empty or not. If Phone Number field is empty then we display Toast message to user that enter phone number.


  SendSMSDemoActivity.java

package com.androidadvance.screen;

import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SendSMSDemoActivity extends Activity implements OnClickListener {
    EditText txtnotes, txtnumber;
    Button btnsend;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        txtnotes = (EditText) findViewById(R.id.txtnotes);
        txtnumber = (EditText) findViewById(R.id.txtnumbers);

        btnsend = (Button) findViewById(R.id.btnsend);
        btnsend.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.btnsend:

       Here we have to check for input.

            if (txtnumber.getText().toString().equals(""))
                Toast.makeText(SendSMSDemoActivity.this,
                        "Please enter number..", Toast.LENGTH_LONG).show();
            else {
                try {

             Manages SMS operations such as sending data, text, and pdu SMS messages. Get this object by calling the static method SmsManager.getDefault().

                    SmsManager smsManager = SmsManager.getDefault();
                    smsManager.sendTextMessage(txtnumber.getText().toString()
                            .trim(), null, txtnotes.getText().toString(), null,
                            null);
                    Toast.makeText(getApplicationContext(), "SMS Sent!",
                            Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(),
                            "SMS faild, please try again later!",
                            Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
            }
            break;

        default:
            break;
        }
    }
}

 Also not forget to give permission in AndroidManifest.xml

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

What is Intent in android ? How to pass data using Intent ?

In android to pass data between activity Intent is used. You can use Intent.putExtras() in sender activity and Intent.getExtras() in receiving activity.


 Following Example explain intent in android.


 For this example we create two xml files main.xml and receiver.xml and we create two corresponding java files AndroidIntentExampleActivity.java and ReceiverActivity.java.

 Following are step by step explanation for this.



 step 1 :-  Create main.xml file. we create two TextView and one EditText and one Button.

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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:gravity="center"
        android:text="@string/hello" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="@string/enterdata"
        android:text />

    <EditText
        android:id="@+id/enteryourdata"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:hint="Enter data"
        android:padding="5dp" />

    <Button
        android:id="@+id/btnok"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_marginRight="15dp"
        android:text="Next" />

</LinearLayout>





  step 2 :-  Now corresponding to main.xml create one java file AndroidIntentExampleActivity.java which handles events.

  public class AndroidIntentExampleActivity extends Activity implements
        OnClickListener {

    EditText txtdata;
    Button btnok;
    String datatopass;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        txtdata = (EditText) findViewById(R.id.enteryourdata);
        btnok = (Button) findViewById(R.id.btnok);
        datatopass = txtdata.getText().toString();
        btnok.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent intent = new Intent(AndroidIntentExampleActivity.this,ReceiverActivity.class);
        Bundle b = new Bundle();
        b.putString("data", txtdata.getText().toString());
        intent.putExtras(b);
        startActivity(intent);

    }
}


 Step 3 :- Now for receive data you need to create one xml file and one Java file. First create one xml file receiver.xml which display data passed  from first activity.

  receiver.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:background="@android:color/white"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/displaytext"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Text" android:gravity="center"
        android:textColor="@android:color/black"
        android:textSize="20dp"
        android:text />

</LinearLayout>
 
  Here TextView display the text which is passed from first activity. Now for handling events create java file ReceiverActivity.java



 step 4 :- Create ReceiverActivity.java

public class ReceiverActivity extends Activity {
    TextView txtdata;
    String value;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.receiver);
        txtdata = (TextView) findViewById(R.id.displaytext);
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            value = String.valueOf(extras.getString("data"));
            Toast.makeText(ReceiverActivity.this, "" + value, Toast.LENGTH_LONG)
                    .show();
            txtdata.setText(value);
        }
    }
}

Tuesday 2 April 2013

Android SQLite Tutorial


 => Just like iOS android have in build sqlite database. In this tutorial, you learn how SQLite databases are designed and manipulated.

 => SQLite is a lightweight relational database engine. Instead of the heavyweight server-based databases, each SQLite database is stored within a single file on disk.

  => Android applications can choose to store private application data in a SQLite database.

  => In SQLite data are stored in table format. A table has columns with different data types. Each row in a table represents a data record.  
        
  => Lets take one example, Let’s say we have a product database with a table called Products.


  =>The Products  table might have 3 typed columns:

                          1) ProductID (number)
                          2) ProductName (string)
                          3) Pproductprice (string)

    => We could then add a record to the data base for an Product named computer.
    => We can do following operation on Products table :

                          1) ADD (INSERT query)
                          2) MODIFIED (UPDATE query)
                          3) DELETE (DELETE query)      

     => Now we perform create, modify and delete operation with Products table.
      

       (1) Create table

                                             
                    CREATE TABLE Products (id INTEGER PRIMARY KEY AUTOINCREMENT,                        
 Productname TEXT NOT NULL, Productprice TEXT NOT NULL );



       (2) INSERT into table       

                                
                     INSERT into Products(Productname, Productprice)
                       VALUES('Computer', '50000'); 

       (3) UPDATE table


           SQLiteDatabase db;
           db.update("Products", values, whereClause, whereArgs);



  Now we explain with example. We have to achieve following.












- create new android project AndroidAdvanceSqlite.


  - create class AndroidAdvanceSqliteActivity.java, this class describe two options add record and view record from sqlite database. For this we have to create main.xml like following.


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="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="15dp"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:text="Android Advance SQLite Tutorial"
        android:textSize="18dp"
        android:text />

    <Button
        android:id="@+id/btn_add"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:text="Add Products"
        android:text />

    <Button
        android:id="@+id/btn_view"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:text="View Products"
        android:text />

 <Button
        android:id="@+id/btn_contact"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:onClick="contactMe"
        android:text="Contact me for query"
        android:textStyle="bold" />

</LinearLayout>




  - We have to create two buttons for database operation.

AndroidAdvanceSqliteActivity.java


public class AndroidAdvanceSqliteActivity extends Activity implements
        OnClickListener {

    private Button btn_add, btn_view, btn_search;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn_add = (Button) findViewById(R.id.btn_add);
        btn_view = (Button) findViewById(R.id.btn_view);
         btn_search = (Button) findViewById(R.id.btn_search);
        btn_search.setOnClickListener(this);
        btn_add.setOnClickListener(this);
        btn_view.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.btn_add:
            Intent addintent = new Intent(AndroidAdvanceSqliteActivity.this,
                    AddRecord.class);
            startActivity(addintent);
            break;

        case R.id.btn_view:
            Intent viewintent = new Intent(AndroidAdvanceSqliteActivity.this,
                    ViewRecord.class);
            startActivity(viewintent);
            break;

            case R.id.btn_search:
            Intent searchintent = new Intent(AndroidAdvanceSqliteActivity.this,
                    SearchProduct.class);
            startActivity(searchintent);
            break;
        default:
            break;
        }

    }

       public void contactMe(View v) {

        final Intent emailIntent = new Intent(
                android.content.Intent.ACTION_SEND);
        emailIntent.setType("plain/text");
        emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                new String[] { "androiddevelopmentworld@gmail.com" });
        emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                "Android sqlite tutorial");
        emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
                "Android sqlite tutorial contact Me");
        startActivity(Intent.createChooser(emailIntent, "Send mail..."));

    }
}



- We are passing intents to AddRecord.java and ViewRecord.java classes for operation. Now first we have to create AddRecord.java class and for that we have to  create xml file as following.


  -create new addrecord.xml file


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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="15dp"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:text="ADD Record"
        android:textSize="18dp"
        android:text />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:text="Product ID" />

    <EditText
        android:id="@+id/txtpid"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:hint="product ID" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:text="Enter Product Name" />

    <EditText
        android:id="@+id/txtpname"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:hint="product name" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:text="Enter Product Price" />

    <EditText
        android:id="@+id/txtpprice"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:hint="product price" />

    <Button
        android:id="@+id/btn_addrecord"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Save" />

</LinearLayout>


  - Now we have to create AddRecord.java  like following. When user click on save button we need to add that record in our database for that we have to fire query which add record in our database.


public class AddRecord extends Activity implements OnClickListener {

    private Button btn_addrecord;
    private EditText txtpname, txtpprice, txtpid;
    DatabaseHelper db;
    ProductModel pm;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addrecord);

        txtpname = (EditText) findViewById(R.id.txtpname);
        txtpprice = (EditText) findViewById(R.id.txtpprice);
        btn_addrecord = (Button) findViewById(R.id.btn_addrecord);

        txtpid = (EditText) findViewById(R.id.txtpid);
        btn_addrecord.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.btn_addrecord:

            if (txtpname.getText().toString().equals("")
                    || txtpprice.getText().toString().equals("")) {
                Toast.makeText(AddRecord.this, "Please add values..",
                        Toast.LENGTH_LONG).show();
            } else {

                db = new DatabaseHelper(getApplicationContext());
                db.getWritableDatabase();
                pm = new ProductModel();
                pm.idno = (txtpid.getText().toString());
                pm.productname = txtpname.getText().toString();
                pm.productprice = txtpprice.getText().toString();

                Log.i("idno,productname,productprice", "" + pm.idno + ""
                        + pm.productname + "" + pm.productprice);
                   db.addProduct(pm);
                Toast.makeText(AddRecord.this, "Record Added successfully.",
                        Toast.LENGTH_LONG).show();
                finish();
            }
            break;

        default:
            break;
        }

    }
}


- Here we add record using db.addProduct() method. Which we have to create in our DatabaseHelper.java class.

 - our DatabaseHelper.java looks like..


public class DatabaseHelper extends SQLiteOpenHelper {

    public static String DATABASENAME = "androidadvancesqlite";  // our database Name

    public static String PRODUCTTABLE = "products";                    //table name

    private ArrayList<ProductModel> cartList = new ArrayList<ProductModel>();
    Context c;


  //constructor
    public DatabaseHelper(Context context) {
        super(context, DATABASENAME, null, 33);
        c = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE if not exists producttable(id INTEGER PRIMARY KEY AUTOINCREMENT,"
                + "productidno"
                + " TEXT ,"
                + "productname"
                + " TEXT,"
                + "productprice" + " TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS" + PRODUCTTABLE);
        onCreate(db);
    }

  //Add record
    public void addProduct(ProductModel productitem) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("productidno", productitem.idno);
        contentValues.put("productname", productitem.productname);
        contentValues.put("productprice", productitem.productprice);
        db.insert("producttable", null, contentValues);
        db.close();
    }

 //update record
    public void updateProduct(ProductModel productList) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("productname", productList.productname);

        contentValues.put("productprice", productList.productprice);
        db.update("producttable", contentValues, "productidno="
                + productList.idno, null);
        db.close();
    }

  // delete entire data from table
    public void emptyProduct() {
        try {
            SQLiteDatabase db = this.getWritableDatabase();
            db.execSQL("delete from producttable");
            db.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

  // remove specific record from table
    public void removeProduct(String productid, String pname, String pprice) {
        try {
            String[] args = { productid };
            getWritableDatabase().delete("producttable", "productidno=?", args);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

  // get all products from database
    public ArrayList<ProductModel> getProudcts() {

        cartList.clear();

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from producttable", null);
        if (cursor.getCount() != 0) {
            if (cursor.moveToFirst()) {
                do {
                    ProductModel item = new ProductModel();

                    item.idno = cursor.getString(cursor
                            .getColumnIndex("productidno"));

                    item.productname = cursor.getString(cursor
                            .getColumnIndex("productname"));

                    item.productprice = cursor.getString(cursor
                            .getColumnIndex("productprice"));

                    cartList.add(item);

                } while (cursor.moveToNext());
            }
        }
        cursor.close();
        db.close();
        return cartList;
    }


   public ArrayList<ProductModel> getProudcts(String record) {

        cartList.clear();

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.query(true, "producttable", new String[] {
                "productidno", "productname", "productprice" }, "productname"
                + "=?", new String[] { record }, null, null, null, null);

        if (cursor.getCount() != 0) {
            if (cursor.moveToFirst()) {
                do {
                    ProductModel item = new ProductModel();

                    item.idno = cursor.getString(cursor
                            .getColumnIndex("productidno"));

                    item.productname = cursor.getString(cursor
                            .getColumnIndex("productname"));

                    item.productprice = cursor.getString(cursor
                            .getColumnIndex("productprice"));

                    cartList.add(item);

                } while (cursor.moveToNext());
            }
        }
        cursor.close();
        db.close();
        return cartList;
    }
}



- Here we have to specify ProductModel class which is our POJO(Plain Old Java Object) which will help us to populate all values.




 - Create new class ProductModel.java which looks like following. It have three variables idno,productname,productprice and also we have to declare   setter and getter methods for that.

 ProductModel.java

public class ProductModel {

   public String idno="", productname="", productprice="";

    public String getProductname() {
        return productname;
    }

    public void setProductname(String productname) {
        this.productname = productname;
    }

    public String getProductprice() {
        return productprice;
    }

    public void setProductprice(String productprice) {
        this.productprice = productprice;
    }

   

    public String getIdno() {
        return idno;
    }

    public void setIdno(String idno) {
        this.idno = idno;
    }

}


- Now for delete,update  and view records from products table we have to create new class ViewRecord.java. Here we desplay all records from database table and delete or update specific record from list.


 - create new viewrecord.xml file. We display all records in a listview.


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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="15dp"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:text="View Record"
        android:textSize="18dp"
        android:text />

    <TextView
        android:id="@+id/totalrecords"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="15dp"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:textSize="18dp"
        android:text />

    <ListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>


 - Now for handling events and display data we have to create ViewRecord.java like following.


ViewRecord.java

public class ViewRecord extends Activity {

    private ListView listview;
    TextView totalrecords;
    DatabaseHelper db;
    public ArrayList<ProductModel> _productlist = new ArrayList<ProductModel>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.viewrecord);
        totalrecords = (TextView) findViewById(R.id.totalrecords);
        listview = (ListView) findViewById(R.id.listview);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

        _productlist.clear();

        db = new DatabaseHelper(getApplicationContext());
        db.getWritableDatabase();
        ArrayList<ProductModel> product_list = db.getProudcts();

        for (int i = 0; i < product_list.size(); i++) {

            String tidno = product_list.get(i).getIdno();

            String tname = product_list.get(i).getProductname();
            String tprice = product_list.get(i).getProductprice();

            ProductModel _ProductModel = new ProductModel();

            _ProductModel.setIdno(tidno);
            _ProductModel.setProductname(tname);
            _ProductModel.setProductprice(tprice);

            _productlist.add(_ProductModel);
        }
        totalrecords.setText("Total Records :-" + _productlist.size());
        listview.setAdapter(new ListAdapter(this));
        db.close();

    }

    private class ListAdapter extends BaseAdapter {
        LayoutInflater inflater;
        ViewHolder viewHolder;

        public ListAdapter(Context context) {
            // TODO Auto-generated constructor stub
            inflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return _productlist.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            if (convertView == null) {

                convertView = inflater.inflate(R.layout.listview_row, null);
                viewHolder = new ViewHolder();

                viewHolder.txt_pname = (TextView) convertView
                        .findViewById(R.id.txtdisplaypname);
                viewHolder.txt_pprice = (TextView) convertView
                        .findViewById(R.id.txtdisplaypprice);

                viewHolder.txtidno = (TextView) convertView
                        .findViewById(R.id.txtdisplaypid);
                convertView.setTag(viewHolder);

            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            viewHolder.txt_pname.setText(_productlist.get(position)
                    .getProductname().trim());
            viewHolder.txt_pprice.setText(_productlist.get(position)
                    .getProductprice().trim());

            viewHolder.txtidno.setText(_productlist.get(position).getIdno()
                    .trim());

            final int temp = position;
            (convertView.findViewById(R.id.btn_update))
                    .setOnClickListener(new OnClickListener() {

                        public void onClick(View arg0) {

                            String _productid = String.valueOf(_productlist
                                    .get(temp).getIdno());
                            String _productname = _productlist.get(temp)
                                    .getProductname();
                            String _productprice = _productlist.get(temp)
                                    .getProductprice();

                            Intent intent = new Intent(ViewRecord.this,
                                    AddUpdateValues.class);

                            Bundle bundle = new Bundle();
                            bundle.putString("id", _productid);
                            bundle.putString("name", _productname);
                            bundle.putString("price", _productprice);
                            intent.putExtras(bundle);
                            startActivity(intent);

                        }
                    });



  - for delete record we no need to create class we just call removeProduct() method of DatabaseHelper like following.



            (convertView.findViewById(R.id.btn_delete))
                    .setOnClickListener(new OnClickListener() {

                        public void onClick(View arg0) {

                            AlertDialog.Builder alertbox = new AlertDialog.Builder(
                                    ViewRecord.this);
                            alertbox.setCancelable(true);
                            alertbox.setMessage("Are you sure you want to delete ?");
                            alertbox.setPositiveButton("Yes",
                                    new DialogInterface.OnClickListener() {

                                        public void onClick(
                                                DialogInterface arg0, int arg1) {

                                            db.removeProduct(
                                                    _productlist.get(temp)
                                                            .getIdno().trim(),
                                                    "", "");

                                            ViewRecord.this.onResume();

                                            Toast.makeText(
                                                    getApplicationContext(),
                                                    "Record Deleted...",
                                                    Toast.LENGTH_SHORT).show();

                                        }

                                    });
                            alertbox.setNegativeButton("No",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(
                                                DialogInterface arg0, int arg1) {

                                        }
                                    });
                            alertbox.show();
                        }
                    });
            return convertView;

        }
    }

    private class ViewHolder {
        TextView txt_pname;
        TextView txt_pprice;
        TextView txtidno;

    }

}


 - Here we have to give two buttons with each record in a list that is update and delete. When user click on Update button we have to pass intent to new activity that is AddUpdateValues.java and we have to also pass id,product name and product price of perticular record using Bundle.



 - For update record we create AddUpdateValues.java class. Which will update your record.


- create new addupdatevalues.xml file.


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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:text="Enter Product Name" />

    <EditText
        android:id="@+id/txt_udatepname"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:hint="product name" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:text="Enter Product Price" />

    <EditText
        android:id="@+id/txt_udatepprice"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:hint="product price" />

    <Button
        android:id="@+id/btn_updaterecord"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Save" />

</LinearLayout>

 - Here user enter new values for product name and product price so we declare two edittext.

 - Now create new class AddUpdateValues.java for update records.


public class AddUpdateValues extends Activity implements OnClickListener {
    private Button btn_updaterecord;
    private EditText txtpname, txtpprice;
    DatabaseHelper db;
    ProductModel pm;
    Intent i;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addupdatevalues);
        i = getIntent();
        txtpname = (EditText) findViewById(R.id.txt_udatepname);
        txtpprice = (EditText) findViewById(R.id.txt_udatepprice);

  - Here we get string from intent and sets it to perticular field.

        txtpname.setText(i.getExtras().getString("name"));
        txtpprice.setText(i.getExtras().getString("price"));
        btn_updaterecord = (Button) findViewById(R.id.btn_updaterecord);
        btn_updaterecord.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.btn_updaterecord:
            if (txtpname.getText().toString().equals("")
                    || txtpprice.getText().toString().equals("")) {
                Toast.makeText(AddUpdateValues.this, "Please add values..",
                        Toast.LENGTH_LONG).show();
            } else {

                db = new DatabaseHelper(getApplicationContext());
                db.getWritableDatabase();
                pm = new ProductModel();
                pm.productname = txtpname.getText().toString();
                pm.productprice = txtpprice.getText().toString();
                pm.idno = i.getExtras().getString("id");
                db.updateProduct(pm);
                Toast.makeText(AddUpdateValues.this,
                        "Record Update successfully.", Toast.LENGTH_LONG)
                        .show();
                db.close();
                super.onResume();
                finish();
            }
            break;
        }
    }
}


As per many user's request, I have create search functionality in this example.

Create searchproduct.xml file.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/searchlinear"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="15dp"
            android:layout_marginTop="10dp"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Search Record"
            android:textSize="18dp"
            android:textStyle="bold" />

        <ProgressBar
            android:id="@+id/showprogress"
            style="?android:attr/progressBarStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:paddingRight="10dp"
            android:visibility="gone" />
    </LinearLayout>

    <EditText
        android:id="@+id/txtsearchproduct"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="search"
        android:lines="1"
        android:paddingLeft="25dp"
        android:visibility="visible" >
    </EditText>

    <AutoCompleteTextView
        android:id="@+id/myautocomplete"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:completionThreshold="1"
        android:hint="search"
        android:lines="1"
        android:visibility="gone" />

    <ListView
        android:id="@+id/searchlistview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>


Now for display searched items, we need to create xml file for display single searched item.

Create product_list.xml for display single searched item.


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/category_list_id"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:paddingBottom="1dp" >

    <LinearLayout
        android:id="@+id/ll_place_name_use"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:orientation="vertical"
        android:paddingRight="8dp" >

        <TextView
            android:id="@+id/txt_title_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:maxLines="3"
            android:padding="2dp"
            android:text="aaa"
            android:textColor="@android:color/black"
            android:textSize="16sp"
            android:textStyle="bold" >
        </TextView>

        <TextView
            android:id="@+id/txt_price"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:padding="2dp"
            android:text="1000"
            android:textColor="@android:color/black"
            android:textSize="14sp"
            android:visibility="visible" >
        </TextView>
    </LinearLayout>

</RelativeLayout>


Now last but not least create java file for searching.

Create SearchProduct.java


package com.androidadvance.screen;

import java.util.ArrayList;
import java.util.List;

import com.androidadvance.db.DatabaseHelper;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SearchProduct extends Activity implements TextWatcher {
    EditText _searchbox;
    private ProgressBar showprogress;
    searchtask dotask;
    private ArrayList<ProductModel> _productList;
    ListView _listview;
    DatabaseHelper db;
    public AutoCompleteTextView myAutoComplete;
    private ArrayList<ProductModel> _productList_Temp;
    String query = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.searchproduct);
        _searchbox = (EditText) findViewById(R.id.txtsearchproduct);
        showprogress = (ProgressBar) findViewById(R.id.showprogress);
        _listview = (ListView) findViewById(R.id.searchlistview);
        _searchbox.addTextChangedListener(textwatcher);

    }

    Runnable runn = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            handlersearch.sendEmptyMessage(0);
        }
    };
    TextWatcher textwatcher = new TextWatcher() {

        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            Log.i("---onTextChanged ----", "---------onTextChanged ----");

            if (_searchbox.getText().toString().length() > 2) {
                query = _searchbox.getText().toString().replace(" ", "%20");

                handlersearch.removeCallbacks(runn);
                handlersearch.post(runn);

            } else {
                showprogress.setVisibility(View.GONE);

                if (dotask != null) {
                    if (dotask.getStatus().equals(AsyncTask.Status.RUNNING)) {
                        dotask.cancel(true);
                    }
                }

                handlersearch.removeCallbacks(runn);

                _productList = new ArrayList<ProductModel>();
                _productList.clear();
                _listview.setAdapter(new CustomBaseAdapter(SearchProduct.this,
                        _productList));
            }

        }

        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    };

    Handler handlersearch = new Handler() {

        public void handleMessage(android.os.Message msg) {
            dotask = new searchtask();
            dotask.execute();
        };
    };

    private class searchtask extends AsyncTask<Void, Void, Void> {

        protected void onPreExecute() {

            showprogress.setVisibility(View.VISIBLE);
        };

        protected void onPostExecute(Void param) {
            // animation.dismiss();
            showprogress.setVisibility(View.GONE);
            if (_productList == null)
                return;

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

            for (int i = 0; i < _productList.size(); i++) {
                item.add(_productList.get(i).productname);
            }

            myAutoComplete = (AutoCompleteTextView) findViewById(R.id.myautocomplete);

            myAutoComplete.addTextChangedListener(SearchProduct.this);

            myAutoComplete.setAdapter(new ArrayAdapter<String>(
                    SearchProduct.this,
                    android.R.layout.simple_dropdown_item_1line, item));

            _productList_Temp = new ArrayList<ProductModel>();

            for (int i = 0; i < _productList.size(); i++) {

                _productList_Temp.add(_productList.get(i));

            }

            _listview.setAdapter(new CustomBaseAdapter(SearchProduct.this,
                    _productList_Temp));

        }

        @Override
        protected Void doInBackground(Void... params) {

            db = new DatabaseHelper(getApplicationContext());
            db.getWritableDatabase();
            ArrayList<ProductModel> product_list = db.getProudcts(query);

            for (int i = 0; i < product_list.size(); i++) {

                String tidno = product_list.get(i).getIdno();

                System.out.println("tidno>>>>>" + tidno);
                String tname = product_list.get(i).getProductname();
                String tprice = product_list.get(i).getProductprice();

                ProductModel _ProductModel = new ProductModel();

                _ProductModel.setIdno(tidno);
                _ProductModel.setProductname(tname);
                _ProductModel.setProductprice(tprice);

                _productList.add(_ProductModel);
            }
            // _productList = _parser.getProductList();

            return null;
        }

    }

    private class CustomBaseAdapter extends BaseAdapter {
        LayoutInflater _inflater;

        List<ProductModel> productList;

        public CustomBaseAdapter(Context context, List<ProductModel> productList) {
            _inflater = LayoutInflater.from(context);
            this.productList = productList;

        }

        public int getCount() {
            // TODO Auto-generated method stub
            return productList.size();
        }

        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder _holder;
            if (convertView == null) {

                convertView = _inflater.inflate(R.layout.product_list, null);
                _holder = new ViewHolder();

                _holder.title = (TextView) convertView
                        .findViewById(R.id.txt_title_text);
                _holder.price = (TextView) convertView
                        .findViewById(R.id.txt_price);

                convertView.setTag(_holder);
            } else {
                _holder = (ViewHolder) convertView.getTag();
            }

            _holder.title.setText(productList.get(position).productname.trim());

            _holder.price.setText(productList.get(position).productprice);

            return convertView;
        }

        private class ViewHolder {
            TextView title;
            TextView price;
        }
    }

    @Override
    public void afterTextChanged(Editable arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // TODO Auto-generated method stub

    }

    //
}



Download Source code