Anroid SQlite Database Example

contact_row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:padding="1dp"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/textname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/textemail"
        android:layout_marginLeft="5dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/textstreet"
        android:layout_marginLeft="5dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.kuldeep.table.MainActivity">


    <EditText
        android:id="@+id/nametxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:hint="@string/name" />

    <EditText
        android:id="@+id/emailtxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textEmailAddress"
        android:hint="@string/email" />

    <EditText
        android:id="@+id/streettxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:hint="@string/street" />

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/btninsert"/>

    <ListView
        android:id="@+id/listview"
        android:padding="3dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

MainActivity.java

package com.example.kuldeep.table;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{
    EditText nametxt1,emailtxt1,streettxt1;
    String name,email,street;
    View btninsert;
    DbHelper dbHelper;
    ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        nametxt1= (EditText) findViewById(R.id.nametxt);
        emailtxt1= (EditText) findViewById(R.id.emailtxt);
        streettxt1= (EditText) findViewById(R.id.streettxt);
        listView=(ListView) findViewById(R.id.listview);
        dbHelper=new DbHelper(getApplicationContext());
        List<Contact> contacts=dbHelper.getContacts();
        ContactAdapter adapter= new ContactAdapter(this, contacts);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
        btninsert=(Button)findViewById(R.id.button);
        btninsert.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View view) {
                name=nametxt1.getText().toString();
                email=emailtxt1.getText().toString();
                street=streettxt1.getText().toString();
                dbHelper.insertContact(name,email,street);
                ArrayList<String>contactnames=dbHelper.getAllContacts();
                String conts=contactnames.toString();
              // Toast.makeText(getApplicationContext(), "name "+name+" email"+email+" Street "+street, Toast.LENGTH_SHORT).show();
                Toast.makeText(getApplicationContext(), ""+conts, Toast.LENGTH_LONG).show();

            }
        });

    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        //open new activity here
    }
}


contact.java

package com.example.kuldeep.table;

/**
 * Created by kuldeep on 30/10/17.
 */

public class Contact {

   String  name,email,street;
    public Contact(){

    }

    public Contact(String name, String email, String street) {
        this.name = name;
        this.email = email;
        this.street = street;
    }

    public String getName() {
        return name;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }
}


DbHelper.java
package com.example.kuldeep.table;

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

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

/**
 * Created by kuldeep on 30/10/17.
 */

public class DbHelper extends SQLiteOpenHelper {
    public static final  String DATABASE_NAME="Mycontacts.db";
    public DbHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL("create table contacts(id integer primary key,name text,email text,street text)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    }
    public boolean insertContact(String name,String email,String street){
        SQLiteDatabase database=this.getWritableDatabase();
        ContentValues values=new ContentValues();
        values.put("name",name);
        values.put("email",email);
        values.put("street",street);
        database.insert("contacts",null,values);
        Log.d("SQL","inserted sucessfully");
        return true;
    }
    public ArrayList<String>getAllContacts(){
        ArrayList<String> arrayList=new ArrayList<String>();
        SQLiteDatabase database=this.getReadableDatabase();
        Cursor res=database.rawQuery("select * from contacts",null);
        res.moveToFirst();
        while(res.isAfterLast()==false) {
            arrayList.add(res.getString(res.getColumnIndex("name")));
            res.moveToNext();
        }
        return arrayList;
    }
    public List<Contact>getContacts(){
        List<Contact> contactList=new ArrayList<Contact>();
        SQLiteDatabase database=this.getReadableDatabase();
        Cursor res=database.rawQuery("select * from contacts",null);
        res.moveToFirst();
        while(res.isAfterLast()==false) {
            Contact contact=new Contact();
            contact.setName(res.getString(res.getColumnIndex("name")));
            contact.setEmail(res.getString(res.getColumnIndex("email")));
            contact.setStreet(res.getString(res.getColumnIndex("street")));
            contactList.add(contact);

            res.moveToNext();
        }
        return contactList;
    }
}

ContactAdapter.java

package com.example.kuldeep.table;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

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

/**
 * Created by kuldeep on 6/11/17.
 */

public class ContactAdapter extends BaseAdapter {
    private static LayoutInflater inflater;
    //Resources resources;
    Context context;
    List<Contact>  contacts;
    public ContactAdapter(Context context, List<Contact> contacts) {
        //this.resources=resource;
        this.contacts=contacts;
        this.context=context;
        inflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public int getCount() {
        return contacts.size();
    }

    @Override
    public Object getItem(int i) {
        return contacts.get(i);
    }

    @Override
    public long getItemId(int i) {
        return contacts.indexOf(i);
    }
private class ViewHolder{
TextView nameview,emailview,streetview;
}
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder holder;
if(view==null){
    holder=new ViewHolder();
view=inflater.inflate(R.layout.contact_row,null);
    holder.nameview=view.findViewById(R.id.textname);
    holder.emailview=view.findViewById(R.id.textemail);
    holder.streetview=view.findViewById(R.id.textstreet);
    Contact contact=contacts.get(i);
    holder.nameview.setText(contact.getName());
    holder.emailview.setText(contact.getEmail());
    holder.streetview.setText(contact.getStreet());
view.setTag(holder);

}else{
    holder=(ViewHolder) view.getTag();
}
        return view;
    }
}

Comments