Tuesday, July 23, 2013

SQLite Android Example

Hello Friends,

Since Long time I was awaiting to write SQLite sample in my blogs, and finally here it is!

This is a simple example where in there are 2 screens, first one to add the entries of students name and subjects marks and then to view the entries in the next page.

There is a class 'DatabaseHandler' which extends 'SQLiteOpenHelper' where code to create database, tables, add new record, fetch records etc resides.

Data is displayed in ListView using ListView adapter.

Following code for the layout files and Java Files For App:

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Student Name" />
    <EditText
        android:id="@+id/etstdname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >
   </EditText>  
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Physic" />
    <EditText
        android:id="@+id/etphysics"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >
   </EditText> 
    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Biology" />
    <EditText
        android:id="@+id/etbiology"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >
   </EditText> 
    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Chemistry" />
    <EditText
        android:id="@+id/etchemistry"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >
   </EditText>
    <Button
        android:id="@+id/btnsave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save" />
    <Button
        android:id="@+id/btncheckdata"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Check Data" />
</LinearLayout>


listview_row.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/linearLayout1"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">  
    <TextView
        android:id="@+id/FirstText"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:text="First" android:gravity="center"
        android:background="@drawable/shape"
        android:layout_weight="1">
    </TextView>
    <TextView
        android:id="@+id/SecondText"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:text="Second" android:gravity="center"
        android:background="@drawable/shape"
        android:layout_weight="1">
    </TextView>      
    <TextView
        android:id="@+id/ThirdText"
        android:layout_width="0dp"
        android:layout_height="match_parent"      
        android:text="Third" android:gravity="center"
        android:background="@drawable/shape"
        android:layout_weight="1">
    </TextView>          
    <TextView
        android:id="@+id/FourthText"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:text="Fourth" android:gravity="center"
        android:background="@drawable/shape"
        android:layout_weight="1">
    </TextView>
</LinearLayout>

activity_display_data.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".DisplayData" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="Student Info"
        android:textAppearance="?android:attr/textAppearanceLarge" />
    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/button1"
        android:background="@android:color/white" />
    <Button
        android:id="@+id/button1"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="Back" />  
</RelativeLayout>

MainActivity.java

package com.example.sqlitedemo;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    EditText etname, etchemistry, etbiology, etphysics;
    Button save, display;
    String name, biology, physic, chemistry;
    DatabaseHandler db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);       
        etname = (EditText)findViewById(R.id.etstdname);
        etchemistry = (EditText)findViewById(R.id.etchemistry);
        etbiology = (EditText)findViewById(R.id.etbiology);
        etphysics = (EditText)findViewById(R.id.etphysics);       
        save = (Button)findViewById(R.id.btnsave);
        display = (Button)findViewById(R.id.btncheckdata);   
       
        save.setOnClickListener(new View.OnClickListener() {           
            @Override
            public void onClick(View v) {               
                name = etname.getText().toString();
                biology = etbiology.getText().toString();
                chemistry = etchemistry.getText().toString();
                physic = etphysics.getText().toString();               
                db = new DatabaseHandler(getApplicationContext());               
                db.addContact(new Student(name, biology, chemistry, physic));
                Toast.makeText(getApplicationContext(), "Value Added", Toast.LENGTH_SHORT).show();
            }
        });       
            display.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {                       
                Intent i = new Intent(MainActivity.this, DisplayData.class);
                startActivity(i);
            }
        });
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {       
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

Student.java

package com.example.sqlitedemo;

public class Student {
   
    int id;
    String name, biology, chemistry, phyics;
   
    public Student()
    {
       
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getBiology() {
        return biology;
    }

    public void setBiology(String biology) {
        this.biology = biology;
    }

    public String getChemistry() {
        return chemistry;
    }

    public void setChemistry(String chemistry) {
        this.chemistry = chemistry;
    }

    public String getPhyics() {
        return phyics;
    }

    public void setPhyics(String phyics) {
        this.phyics = phyics;
    }

    public Student(String name, String biology, String chemistry,
            String phyics) {
        super();   
        this.name = name;
        this.biology = biology;
        this.chemistry = chemistry;
        this.phyics = phyics;
    }   

}

DatabaseHandler.java

package com.example.sqlitedemo;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHandler extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "studentdetail";
    private static final String TABLE_STUDENTS = "students";
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_PHYSICS = "physics";
    private static final String KEY_CHEMISTRY = "chemistry";
    private static final String KEY_BIOLOGY = "biology";
           
    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
  
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_STUDENTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT, "
                + KEY_BIOLOGY + " TEXT, " + KEY_CHEMISTRY + " TEXT, " +
                   KEY_PHYSICS + " TEXT" + ")";       
        db.execSQL(CREATE_CONTACTS_TABLE);
        }
  
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {      
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_STUDENTS);      
        onCreate(db);
    }
    
    void addContact(Student student) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, student.getName());
        values.put(KEY_BIOLOGY, student.getBiology());
        values.put(KEY_CHEMISTRY, student.getChemistry());
        values.put(KEY_PHYSICS, student.getPhyics());       
        db.insert(TABLE_STUDENTS, null, values);
        db.close();
    }
     
    public List<Student> getAllDetails() {
        List<Student> studentList = new ArrayList<Student>();      
        String selectQuery = "SELECT  * FROM " + TABLE_STUDENTS;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
       if (cursor.moveToFirst()) {
            do {
                Student student = new Student();
                student.setId(Integer.parseInt(cursor.getString(0)));
                student.setName(cursor.getString(1));
                student.setBiology(cursor.getString(2));
                student.setChemistry(cursor.getString(3));                        
                student.setPhyics(cursor.getString(4));              
                studentList.add(student);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return studentList;
    }

}
listviewAdapter.java

package com.example.sqlitedemo;

import static com.example.sqlitedemo.Constant.STUD_NAME;
import static com.example.sqlitedemo.Constant.BIOLOGY;
import static com.example.sqlitedemo.Constant.PHYSICS;
import static com.example.sqlitedemo.Constant.CHEMISTRY;

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

import android.app.Activity;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
       

public class listviewAdapter extends BaseAdapter
{
    public ArrayList<HashMap> list;
    Activity activity;

    public listviewAdapter(Activity activity, ArrayList<HashMap> list) {
        super();
        this.activity = activity;
        this.list = list;
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }
    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return list.get(position);
    }
    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }
    private class ViewHolder {
       TextView txtFirst;
       TextView txtSecond;
       TextView txtThird;
       TextView txtFourth;    
      }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder holder;
                LayoutInflater inflater =  activity.getLayoutInflater();
                if (convertView == null){
                    convertView = inflater.inflate(R.layout.listview_row, null);
                    holder = new ViewHolder();
                    holder.txtFirst = (TextView) convertView.findViewById(R.id.FirstText);
                    holder.txtSecond = (TextView) convertView.findViewById(R.id.SecondText);
                    holder.txtThird = (TextView) convertView.findViewById(R.id.ThirdText);
                    holder.txtFourth = (TextView) convertView.findViewById(R.id.FourthText);
                    convertView.setTag(holder);
                } else {
                    holder = (ViewHolder) convertView.getTag();       
                }           
                HashMap map = list.get(position);
                holder.txtFirst.setText(""+map.get(STUD_NAME));
                holder.txtSecond.setText(""+map.get(BIOLOGY));
                holder.txtThird.setText(""+map.get(PHYSICS));
                holder.txtFourth.setText(""+map.get(CHEMISTRY));
                return convertView;
    }
}
class Constant {
    public static final String STUD_NAME = "First";
    public static final String BIOLOGY = "Second";
    public static final String PHYSICS = "Third";
    public static final String CHEMISTRY = "Fourth";

}


DisplayData.java

package com.example.sqlitedemo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.example.sqlitedemo.Constant.STUD_NAME;
import static com.example.sqlitedemo.Constant.BIOLOGY;
import static com.example.sqlitedemo.Constant.PHYSICS;
import static com.example.sqlitedemo.Constant.CHEMISTRY;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

public class DisplayData extends Activity {
    private ArrayList<HashMap> list;
    Button home;       
    String[] problemgrid = null;
    List<String>getnumbers =null;   
    ListView lview;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);      
        setContentView(R.layout.activity_display_data);       
        lview = (ListView) findViewById(R.id.listview);
        populateList();
        listviewAdapter adapter = new listviewAdapter(this, list);   
        lview.setAdapter(adapter);       
        home = (Button)findViewById(R.id.button1);
        home.setOnClickListener(new View.OnClickListener() {           
            @Override   
            public void onClick(View v) {       
                Intent i = new Intent(DisplayData.this, MainActivity.class);                       
                finish();
                startActivity(i);
            }
        });     
   }       
    private void populateList() {
        list = new ArrayList<HashMap>();
        HashMap temp1 = new HashMap();
        temp1.put(STUD_NAME, "Stud Name");
        temp1.put(BIOLOGY, "Biology");
        temp1.put(PHYSICS, "Physics");
        temp1.put(CHEMISTRY, "Chemistry");
        list.add(temp1);       
     DatabaseHandler dbresult = new DatabaseHandler(getApplicationContext());       
     List<Student> recdata = dbresult.getAllDetails();   
         for (Student cn : recdata) {          
             String name = cn.getName();
            String biology = cn.getBiology();
            String physics = cn.getPhyics();
            String chemistry = cn.getChemistry();           
                HashMap temp = new HashMap();
                temp.put(STUD_NAME, name);
                temp.put(BIOLOGY, biology);
                temp.put(PHYSICS, physics);
                temp.put(CHEMISTRY, chemistry);       
                list.add(temp);
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {   
        getMenuInflater().inflate(R.menu.display_data, menu);
        return true;
    }
}

The Screenshots of the Application is as Follows,






To Verify the Data in database, Go To File Explorer Window for Eumlator, In your IDE, browse to the data/data/<package name> /databases/ , here you will see the database file created as follows,


 Pull this file from the emulator and view the file in SQLite database browser you can fire the query and verify your table structure and data as follows,


 
That is all from my end from now.

Happy Coding!

~Mayuri


Best Car pool Android Application Best Car Pool Application Source Code Download Here



Best Social Network Cordova Ionic Application Best Social Networking Source Code Cordova Ioinc Application Download Here



5 comments:

Unknown said...

Awesome post,
I'm a beginner in android development and I must say this helped. Thumps UP :D

Unknown said...

how to search a element based on key value in hash map...can u plz post source code

Unknown said...
This comment has been removed by the author.
Unknown said...

can u plz post me a source code to sravanipractice@gmail.com

Kotta.Harsha said...

Hi,Am also plan learn Mobile App with phonegap can you post some basic examples regarding that.

Animated Container in Flutter

Please check this flutter video tutorial for detailed example and implementation of Animated Container in Flutter.