Monday, 15 October 2012

List View Example With Storing into the Database(SQLite) in Android


List View Example With Storing into the Database(SQLite) in Android


ListViews are Views which allow to display a list of elements. ListActivities  are specialized Activities which make the usage of ListViews easier. To work with databases and ListViews you can use the SimpleCursorAdapter. The SimpleCursorAdapter allows to set a layout for each row of the ListViews. You also define an array which contains the column names and another array which contains the IDs ofViews which should be filled with the data. The SimpleCursorAdapter class will map the columns to the Views based on the Cursor passed to it.


In this example, Store the data into the database and the stored data you can see in the list view. Here I used SQLite Database. The data will store into the SQLite database and after inserting the data you can see the value in list view.
Before going to program, I need to explain about the program. In this program , You can store a person’s name, location and his/her salary. After inserting the details, you can see the details in list view. The design of main.xml will look 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:text="Database Example" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Name">

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="location" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Salary"/>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Insert" />

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

</LinearLayout>


Database File :  MyDatabase.java

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MyDatabase
{
            public static final String MY_DB2 = "testdb3";
            MyHelper mh;
            Context myCon;
            SQLiteDatabase sdb;
            public MyDatabase(Context c)
            {
                        myCon = c;
                        mh = new MyHelper(myCon, MY_DB2, null, 1);
            }
            public void open()
            {
                        sdb = mh.getWritableDatabase();
            }
            public class MyHelper extends SQLiteOpenHelper
            {

                        public MyHelper(Context context, String name, CursorFactory factory,
                                                int version) {
                                    super(context, name, factory, version);
                                    // TODO Auto-generated constructor stub
                        }

                        @Override
                        public void onCreate(SQLiteDatabase db)
                        {
                                    db.execSQL("create table emp(_id integer primary key, ename text,elocation text,esal integer);");
                                    Log.d("1", "Table Created");
                        }

                        @Override
                        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                                    // TODO Auto-generated method stub
                                   
                        }
                       
            }
            public void empInsert(ContentValues cv)
            {
                        sdb.insert("emp", null, cv);
            }
            public Cursor getEmp()
            {
                        Cursor c = sdb.query("emp", null, null, null, null, null, null);
                        return c;
            }
}

Home.java
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class Home extends Activity
{
            MyDatabase mdb = new MyDatabase(this);
            Cursor c;
            public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        final ListView lv = (ListView)findViewById(R.id.listView1);
       
        final SimpleCursorAdapter sca;
        Button btn1 = (Button)findViewById(R.id.button1);
       
        final EditText name = (EditText)findViewById(R.id.editText1);
        final EditText location = (EditText)findViewById(R.id.editText2);
        final EditText salary = (EditText)findViewById(R.id.editText3);
        mdb.open();
        btn1.setOnClickListener(new OnClickListener()
        {
                                   
                                    public void onClick(View v)
                                    {
                                                String ename = name.getText().toString();
                                                String eloc = location.getText().toString();
                                                Integer esal = Integer.parseInt(salary.getText().toString());
                                                ContentValues cv = new ContentValues();
                                                cv.put("ename", ename);
                                                cv.put("elocation", eloc);
                                                cv.put("esal", esal);
                                                mdb.empInsert(cv);
                                                name.setText(" ");
                                                location.setText(" ");
                                                salary.setText(" ");
                                                c.requery(); 
                                    }
                        });
       
                        c = mdb.getEmp();
                        String []from = {"ename","elocation","esal"};
                        int []to = {R.id.textView1,R.id.textView3,R.id.textView2};
                        sca = new SimpleCursorAdapter(this, R.layout.row, c, from, to);
                        lv.setAdapter(sca);
                        sca.notifyDataSetChanged();
                        c.requery();             
                       
    }
}

Row.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" >

    <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="20dp"
            android:text="TextView" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_marginRight="54dp"
            android:text="TextView" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_marginRight="36dp"
            android:layout_toLeftOf="@+id/textView2"
            android:text="TextView" />

    </RelativeLayout>
   
</LinearLayout>

OutPut:




Thursday, 11 October 2012

ListView Example in Android With ArrayList


Simple List View Example in Android


In this program I will insert the data into the array list and delete the contains from the array list. Here I am inserting the data temporarily. This data will not store in the database. Let’s see the program coding:

In main.xml I taken two buttons, one is for insert and another is for delete and taken list view.

main.xml  will look 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="Enter Text" />

    <EditText
        android:id="@+id/et_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName" >

        <requestFocus />
    </EditText>

    <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/relativeLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/btn_add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:text="Add" />

        <Button
            android:id="@+id/btn_delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:text="Delete" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/relativeLayout3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <ListView
            android:id="@+id/lv_main"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_gravity="center" >
        </ListView>

    </LinearLayout>
</LinearLayout>


ListViewActivity.java

import java.util.ArrayList;
import java.util.Collections;

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

public class ListViewActivity  extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        final Button add_btn = (Button)findViewById(R.id.btn_add);
        final Button del_btn = (Button)findViewById(R.id.btn_delete);

        final ListView myListView = (ListView)findViewById(R.id.lv_main);
        final EditText et_main = (EditText)findViewById(R.id.et_main);
       
        final ArrayList<String> al = new ArrayList<String>();
        final ArrayAdapter<String> ad;
        ad = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,al);
        myListView.setAdapter(ad);
      
                
        add_btn.setOnClickListener(new OnClickListener()
        {
                                   
                                    public void onClick(View v)
                                    {
                              String str = et_main.getText().toString();
                              Integer cout = myListView.getCount()+ 1;
                              String str1 = cout.toString().concat("."+str);
                                      al.add(myListView.getCount(), str1);
                                      //Collections.sort(al);
                                      ad.notifyDataSetChanged();
                                      Toast.makeText(getApplicationContext(), "Data Saved", Toast.LENGTH_SHORT).show();
                                      et_main.setText(" ");
                                    }
                        });
     del_btn.setOnClickListener(new OnClickListener()
        {
                                   
                                    public void onClick(View v)
                                    {
                                                al.remove(al.size()-1);       
                                                ad.notifyDataSetChanged();
                                    }
                        });
    }
}


Result:

When you will click on Insert Button, the data insertion will be successfully. If you want to remove the data , just click on the delete button. It will remove from the last.

See here I am inserting the data , Putting Value(Name) : “Divya Bharati”. When you will click on the Add Button, it will insert into the list.



Check bellow, “Divya Bharati” added into the list.



See again bellow picture , after clicking on the delete button, “Divya Bharati” deleted as it was entered last.