info@thistimebd.com

Thursday 21st of November 07:22:41pm

SQLite list data android app source code

DatabaseHelper.java

========================


package com.sam.web.sqlitelistview;


import android.content.ContentValues;

import android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

import android.widget.Toast;


/**

 * Created by maudud on 2/5/18.

 */



public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "student.db";

    private static final String TABLE_NAME = "student_details";

    private static final String ID = "id";

    private static final String NAME = "Name";


    private static final int VERSION_NUMBER = 1;


    private Context context;

    private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME+" ("+ID+" INTEGER PRIMARY KEY,"+NAME+" VARCHAR(30));";


    public DatabaseHelper(Context context) {

        super(context, DATABASE_NAME, null, VERSION_NUMBER);

        this.context=context;

    }


    @Override

    public void onCreate(SQLiteDatabase sqLiteDatabase) {


        try {

            sqLiteDatabase.execSQL(CREATE_TABLE);

            Toast.makeText(context,"onCreate is called : ",Toast.LENGTH_LONG).show();



        }catch (Exception e){

            Toast.makeText(context,"Exception : "+e,Toast.LENGTH_LONG).show();




        }


    }


    @Override

    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {

        try {

            Toast.makeText(context,"onUpgrade is called",Toast.LENGTH_LONG).show();

            sqLiteDatabase.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);

            onCreate(sqLiteDatabase);


        }catch (Exception e){

            Toast.makeText(context,"Exception : "+e,Toast.LENGTH_LONG).show();




        }


    }

    public long saveData(String id, String name){

        SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();

        ContentValues contentValues=new ContentValues();

        contentValues.put(ID,id);

        contentValues.put(NAME,name);


        long rowNumber=sqLiteDatabase.insert(TABLE_NAME,null,contentValues);

        return rowNumber;




    }

    public Cursor showAllData(){



        SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();

        Cursor cursor=sqLiteDatabase.rawQuery("SELECT * FROM "+TABLE_NAME,null);

        return cursor;

    }


    public Boolean updateData(String id,String name){


        SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();

        ContentValues contentValues=new ContentValues();

        contentValues.put(ID,id);

        contentValues.put(NAME,name);

        sqLiteDatabase.update(TABLE_NAME,contentValues,ID+" = ?",new String[] {id});

        return true;

    }

    public int deleteData(String id){


        SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();

        int value=sqLiteDatabase.delete(TABLE_NAME,ID+" = ?",new String[] {id});

        return value;

    }

}


============================================================================================

ListDataActivity.java

========================

package com.sam.web.sqlitelistview;


import android.database.Cursor;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.AdapterView;

import android.widget.ArrayAdapter;

import android.widget.ListView;

import android.widget.Toast;


import java.util.ArrayList;


public class ListDataActivity extends AppCompatActivity {

    private ListView listView;

    private DatabaseHelper databaseHelper;


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_list_data);


        listView=(ListView) findViewById(R.id.listViewId);

        databaseHelper=new DatabaseHelper(this);

        loadData();

    }


    public void loadData(){



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

        Cursor cursor=databaseHelper.showAllData();

        if(cursor.getCount()==0){


            Toast.makeText(getApplicationContext(),"No data is available in database",Toast.LENGTH_LONG).show();

        }

        else {


            while (cursor.moveToNext()){


                listData.add(cursor.getString(0)+" "+cursor.getString(1));

            }

        }


        final ArrayAdapter<String>adapter=new ArrayAdapter<String>(this,R.layout.list_item,R.id.textViewId,listData);

        listView.setAdapter(adapter);


       listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

           @Override

           public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

               String selectedValue=adapterView.getItemAtPosition(i).toString();

               Toast.makeText(getApplicationContext(),"Selected value :"+selectedValue,Toast.LENGTH_LONG).show();

           }

       });

    }

}

=============================================================================================================

MainActivity.java

====================

package com.sam.web.sqlitelistview;


import android.content.Intent;

import android.database.sqlite.SQLiteDatabase;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private DatabaseHelper databaseHelper;

    private EditText nameEditText,idEditText;

    private Button saveButton,showButton,updateButton,deleteButton;


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        databaseHelper=new DatabaseHelper(this);

        SQLiteDatabase sqLiteDatabase=databaseHelper.getWritableDatabase();


        nameEditText=(EditText) findViewById(R.id.namEditText);

        idEditText=(EditText) findViewById(R.id.idEditText);


        saveButton=(Button) findViewById(R.id.saveButtonId);

        showButton=(Button) findViewById(R.id.showButtonId);

        updateButton=(Button) findViewById(R.id.updateButtonId);

        deleteButton=(Button) findViewById(R.id.deleteButtonId);



        saveButton.setOnClickListener(this);

        showButton.setOnClickListener(this);

        updateButton.setOnClickListener(this);

        deleteButton.setOnClickListener(this);

    }


    @Override

    public void onClick(View view) {


        String id=idEditText.getText().toString();

        String name=nameEditText.getText().toString();

        if(view.getId()==R.id.saveButtonId)

        {

            if(id.equals("") && name.equals("")){



                Toast.makeText(getApplicationContext(),"Please Enter all the data",Toast.LENGTH_LONG).show();

            }else {

                long rowNumber=databaseHelper.saveData(id,name);


                if(rowNumber > -1){

                    Toast.makeText(getApplicationContext(),"Data is inserted successfully",Toast.LENGTH_LONG).show();

                            idEditText.setText("");

                            nameEditText.setText("");





                }else {


                    Toast.makeText(getApplicationContext(),"Data is not inserted successfully",Toast.LENGTH_LONG).show();


                }





            }




        } else if(view.getId()==R.id.showButtonId){

            Intent intent=new Intent(MainActivity.this,ListDataActivity.class);

            startActivity(intent);




        } else if(view.getId()==R.id.updateButtonId){

            Boolean isUpdated=databaseHelper.updateData(id,name);

            if(isUpdated==true){

                Toast.makeText(getApplicationContext(),"data is updated",Toast.LENGTH_LONG).show();




            }else {

                Toast.makeText(getApplicationContext(),"data is not updated",Toast.LENGTH_LONG).show();



            }




        } else if(view.getId()==R.id.deleteButtonId){

            int value=databaseHelper.deleteData(id);

            if(value<0){


                Toast.makeText(getApplicationContext(),"data is not deleted",Toast.LENGTH_LONG).show();


            }else {


                Toast.makeText(getApplicationContext(),"data is deleted",Toast.LENGTH_LONG).show();


            }




        }


    }

}

==========================================================================================================

==========================================================================================================

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

    tools:context="com.sam.web.sqlitelistview.ListDataActivity">


    <ListView

        android:dividerHeight="1dp"

        android:divider="#228dff"

        android:listSelector="#cfc5ec"

        android:id="@+id/listViewId"

        android:layout_width="match_parent"

        android:layout_height="match_parent"></ListView>


</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:padding="10dp"

    android:orientation="vertical"

    android:background="#22ffe5"

    tools:context="com.sam.web.sqlitelistview.MainActivity">


<EditText

    android:hint="Enter ID"

    android:id="@+id/idEditText"

    android:layout_width="match_parent"

    android:layout_height="wrap_content" />


    <EditText

    android:layout_marginTop="10dp"

    android:hint="Enter Name"

    android:id="@+id/namEditText"

    android:layout_width="match_parent"

    android:layout_height="wrap_content" />

    

    <Button

        android:layout_marginTop="15dp"

        style="@style/Base.Widget.AppCompat.Button.Colored"

        android:text="Save"

        android:id="@+id/saveButtonId"

        android:layout_width="match_parent"

        android:layout_height="wrap_content" />

    <Button

        android:layout_marginTop="15dp"

        style="@style/Base.Widget.AppCompat.Button.Colored"

        android:text="Show"

        android:id="@+id/showButtonId"

        android:layout_width="match_parent"

        android:layout_height="wrap_content" />

    <Button

        android:layout_marginTop="15dp"

        style="@style/Base.Widget.AppCompat.Button.Colored"

        android:text="Update"

        android:id="@+id/updateButtonId"

        android:layout_width="match_parent"

        android:layout_height="wrap_content" />

    <Button

        android:layout_marginTop="15dp"

        style="@style/Base.Widget.AppCompat.Button.Colored"

        android:text="Delete"

        android:id="@+id/deleteButtonId"

        android:layout_width="match_parent"

        android:layout_height="wrap_content" />


</LinearLayout>

================================================================================================

list_item.xml

=================

<?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:padding="10dp"

        android:textStyle="bold"

        android:textSize="17sp"

        android:text="Hellow this is a sample text"

        android:id="@+id/textViewId"

        android:layout_width="match_parent"

        android:layout_height="wrap_content" />


</LinearLayout>