Apr 26, 2011

How to add a search to List View

Initially design a xml file as show below:


<?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"
    >
    <EditText android:id="@+id/EtBrandName" android:layout_height="wrap_content" 
    android:layout_width="fill_parent" android:hint="Search">
    </EditText>
    <ListView android:id="@+id/lvItems"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>

Then write the following code in your activity:-


import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

public class LSearch extends Activity {
private ListView lv1;
private EditText ed;
private String lv_arr[]={"Android","Cupcake","Donut","Eclairs","AndroidPeople","Froyo","Apple","Samsung","Storeage","Sony"};
private ArrayList<String> arr_sort= new ArrayList<String>();
int textlength=0;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        lv1=(ListView)findViewById(R.id.ListView01);
        ed=(EditText)findViewById(R.id.EditText01);
        // By using setAdpater method in listview we an add string array in list.
        lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));
        ed.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable s) {
        }

        public void beforeTextChanged(CharSequence s, int start, int count,
        int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before,
        int count) {

        textlength=ed.getText().length();
        arr_sort.clear();
        for(int i=0;i<lv_arr.length;i++)
        {
        if(textlength<=lv_arr[i].length())
        {
        if(ed.getText().toString().equalsIgnoreCase((String) lv_arr[i].subSequence(0, textlength)))
        {
        arr_sort.add(lv_arr[i]);
        }
        }
        }

        lv1.setAdapter(new ArrayAdapter<String>(LSearch.this,android.R.layout.simple_list_item_1 , arr_sort));

        }
        });
    }
}

your output will look as shown below:




Apr 25, 2011

Android App Development Spinner and GridView ,Specifying Number of Columns In GridView


 this tutorial we are going to cover a couple more Android selection controls: the Spinner and the GridView.

The Spinner

The Spinner control is similar to the ComboBox in C#. It displays a list to select from in a popup window so it may be a better choice over ListView if you have a lot items to display because it will save space.
It works in a similar way to that of the the ListView
<?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"
    >
    <Spinner
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/Spinner"
    />
</LinearLayout>

When you click on the spinner it popups like this:
The following code will handle the selected item:
final String [] items=new String[]{"Item1","Item2","Item3","Item4"};
        ArrayAdapter ad=new ArrayAdapter(this,android.R.layout.simple_spinner_item,items);
        ad.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        Spinner spin=(Spinner)findViewById(R.id.Spinner);
        spin.setAdapter(ad);
        spin.setOnItemSelectedListener(new OnItemSelectedListener()
        {

   public void onItemSelected(AdapterView arg0, View arg1,
     int arg2, long arg3) {
    TextView txt=(TextView)findViewById(R.id.txt);
    TextView temp=(TextView)arg1;
    txt.setText(temp.getText());

   }

   public void onNothingSelected(AdapterView arg0) {
    // TODO Auto-generated method stub

   }

        });
The above code displays the selected item text in the textview.
The parameters of the OnItemClick method are:
AdapterView Arg0: the Spinner, notice that it is of type AdapterView.
  • View Arg1: the view that represents the selected item, in this example it will be a TextView.
  • int Arg2: the position of the selected item.
  • long Arg3: the id of the selected item.
That is it for the Spinner control, we will now move on to the GridView.

GridView

The GridView is similar to ListView but it gives you the ability to control the look of the grid. You can specify the number of columns and columns width and spacing.
This example displays some items in a grid in a normal way:
<?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"
    >
    <GridView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/grid"

    />
</LinearLayout>
final String [] items=new String[]{"Item1","Item2","Item3","Item4"};
        ArrayAdapter ad=new ArrayAdapter(this,android.R.layout.simple_list_item_1,items);
        GridView grid=(GridView)findViewById(R.id.grid);
        grid.setAdapter(ad);

This is a simple grid, similar to a ListView.
We can specify the number of columns that the grid has by specifying the android:numColumns property:
<GridView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/grid"
    android:numColumns="2"
    />
Or by using the code:
grid.setNumColumns(2);
The grid will be like this:

If we specified the number of columns to be three, it will be like this:

And so on, you get the idea.
We can also set the android:numColumns property to “auto_fit” so that the grid autommatically sets the number of columns according to the available space. We can control the vertical spacing between columns using android:verticalSpacing property:
<GridView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/grid"
    android:numColumns="2"
    android:verticalSpacing="100px"
    />
Or by using this code:
grid.setVerticalSpacing(150);

We can also control the horizontal spacing between columns using android:horizontalSpacing property:
<GridView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/grid"
    android:numColumns="2"
    android:horizontalSpacing="100px"    />
Or by using this code:
grid.setHorizontalSpacing(150);

and that was it for the GridView.
Today we covered two more controls for Android, Spinner and Gridview. Check back next week for a new Android app development tutorial and feel free to ask any questions in the comments.

Apr 19, 2011

Custom Layout Checkbox, ImageView, TextView and saving Check Box State in Android

 We started the series off with the most basic loading of hard coded arraylist in a ListView.
In this post we will take it one step further and bind the ListView with a custom layout for single row. The single row layout will have a Checkbox, a TextView and an ImageView  to demonstrate how these three can be repeated on each row. We will still load the data ( images & information )from String arrays 

In this Section Simply i am using base Adapter Class  in that i override getView method for List View .

listdemo.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">
    <ImageView android:id="@+id/imgView" android:layout_width="150dip"
        android:layout_height="100dip" />
    <TextView android:id="@+id/txt" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="@string/hello"
        android:layout_toRightOf="@+id/imgView" />
    <CheckBox android:id="@+id/chk" android:layout_width="wrap_content"
   
        android:layout_height="wrap_content" android:layout_toRightOf="@+id/txt" />
</RelativeLayout>

for listview Components for each row



main.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">
    <Button android:id="@+id/btnSave" android:text="SAVE"
        android:layout_width="wrap_content" android:layout_height="wrap_content">
    </Button>

    <Button android:id="@+id/btnclear" android:text="clear"
        android:layout_toRightOf="@+id/btnSave" android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </Button>

    <ListView android:layout_below="@+id/btnSave" android:id="@+id/listView"
        android:layout_width="fill_parent" android:layout_height="wrap_content"></ListView>

</RelativeLayout>
it contains listview with 2 buttons ( only for visible for other operations )


LAdapter.java customized adapter class for listview )

package sra.che;
import java.util.HashMap;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class LAdapter extends BaseAdapter {
    static HashMap<Integer, Boolean> cartItems = new HashMap<Integer, Boolean>();
    Context mContext;
    Integer images[];   // to load images
    String data[];  // for data
    LayoutInflater mLayoutInflater;

    public LAdapter(Context context, Integer images[], String data[],
            LayoutInflater layoutInflater) {
        mContext = context;
        this.images = images;
        this.data = data;
        mLayoutInflater = layoutInflater;
    }

    @Override
    public int getCount() {

        return images.length;  // images array length
    }

    @Override
    public Object getItem(int arg0) {

        return null;
    }

    @Override
    public long getItemId(int arg0) {

        return 0;
    }

    int count = 0;
// customized Listview
    @Override
    public View getView(int position, View arg1, ViewGroup arg2) {

        View v;
        final int pos = position;
        v = mLayoutInflater.inflate(R.layout.listdemo, null);
        ImageView img = (ImageView) v.findViewById(R.id.imgView);
        img.setImageResource(images[position]);
        TextView tv = (TextView) v.findViewById(R.id.txt);
        tv.setText(data[position]);
// saving check box state  at the time of raloading
        CheckBox ch = (CheckBox) v.findViewById(R.id.chk);
        try {
            if (count != 0) {
                boolean b = cartItems.get(pos);
                if (b == false)
                    ch.setChecked(false);
                else
                    ch.setChecked(true);
            }
        } catch (NullPointerException e) {

        }
        ch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                cartItems.put(pos, arg1);
                count++; 

            }
        });
        return v;
    }

    public static HashMap<Integer, Boolean> getcartItems() {
        return cartItems;
    }

}

Main.java
----------------
package sra.che;

import java.util.HashMap;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class Mainlist extends Activity implements OnClickListener {
    ListView lv;
    Button btnSave, btnClear;
    HashMap<Integer, Boolean> mCartItems = new HashMap<Integer, Boolean>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
// GETTING IMAGES AS STRING FROM RAW folder
        Integer images[] = {
                getResources().getIdentifier("im1", "raw", getPackageName()),
                getResources().getIdentifier("im2", "raw", getPackageName()),
                getResources().getIdentifier("im3", "raw", getPackageName()),
                getResources().getIdentifier("im4", "raw", getPackageName()),
                getResources().getIdentifier("im5", "raw", getPackageName()),
                getResources().getIdentifier("im6", "raw", getPackageName()),
                getResources().getIdentifier("im7", "raw", getPackageName()),
                getResources().getIdentifier("im8", "raw", getPackageName()),
                getResources().getIdentifier("im9", "raw", getPackageName()) };
        String data[] = { "image1", "image2", "image3", "image4", "image5",
                "image6", "image7", "image8", "image9", "image10" };
        lv = (ListView) findViewById(R.id.listView);
        btnSave = (Button) findViewById(R.id.btnSave);
        btnClear = (Button) findViewById(R.id.btnclear);
        btnSave.setOnClickListener(this);
        btnClear.setOnClickListener(this);
        lv.setCacheColorHint(0);
        LayoutInflater mLInflater = getLayoutInflater();
        final LAdapter adapter = new LAdapter(getApplicationContext(), images,
                data, mLInflater);
        lv.setAdapter(adapter);
    }

    @Override
    public void onClick(View v) {
        if (v == btnSave) {
            Toast
                    .makeText(getApplicationContext(), " save",
                            Toast.LENGTH_SHORT).show();
        }
        if (v == btnClear) {
            Toast.makeText(getApplicationContext(), " clear",
                    Toast.LENGTH_SHORT).show();
        }
    }
}


note : here i save images in raw folder
------
for creating raw folder right click on res folder  choose folder option give name (raw ) press enter