Search This Blog

Monday, November 20, 2017

How to use SQLite in Android |Complete Code CREATE | INSERT | UPDATE | DELETE.

SQLite CREATE | INSERT | UPDATE | DELETE.

simple and easy to understand. SQLite storage of Android.we use SQLite for store temporary data.like username,password and profile pic etc.below simple example for SQLite.

Create New Project:

MainActivity.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="15dp"  
   android:orientation="vertical"  
   tools:context="com.example.aaru.sqldatabase.MainActivity">  
   <TextView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="SQLDatabase"  
     android:textSize="35dp"  
     android:layout_gravity="center"  
     />  
   <EditText  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:id="@+id/edtUname"  
     android:hint="UserName"  
     />  
   <EditText  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:id="@+id/edtPass"  
     android:hint="Password"  
     />  
   <Button  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:id="@+id/btnSubmit"  
     android:text="Submit"  
     android:layout_marginTop="10dp"  
     />  
   <Button  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:id="@+id/btnView"  
     android:text="View"  
     />  
 </LinearLayout>  

Create A Java file name is DBHelper.

DBHelper.java


 package com.example.aaru.sqldatabase;  
 import android.content.ContentValues;  
 import android.content.Context;  
 import android.database.Cursor;  
 import android.database.sqlite.SQLiteDatabase;  
 import android.database.sqlite.SQLiteOpenHelper;  
 import java.util.ArrayList;  
 /**  
  * Created by Aaru on 11/16/2017.  
  */  
 public class DBHelper extends SQLiteOpenHelper {  
   public static final String DBNAME="mydata.db"; //Database name  
   public static final String TABLE="User";//TABLE name  
   public static final String UNAME="UNAME"; //column name  
   public static final String UPASS="UPASS"; //column name  
   public static final String ID="ID";//id is unique this is column name  
   public DBHelper(Context context) {//we need only context  
     super(context, DBNAME, null, 1);  
     //name=database name  
     //version is 1(my new project and version is 1)  
     //factory always null  
     //database created when we create a object  
   }  
   @Override  
   public void onCreate(SQLiteDatabase sqLiteDatabase) {  
     //in onCreate create a table using sqLiteDatabse object  
     sqLiteDatabase.execSQL("CREATE TABLE "+TABLE+"("+ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"+UNAME+" TEXT,"+UPASS+" TEXT)");  
   }  
   @Override  
   public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {  
     sqLiteDatabase.execSQL("DROP TABLE IF EXISTS "+TABLE+"");//if table is already check and drop table  
     onCreate(sqLiteDatabase);  
   }  
   //create a method for insert data  
   public long insertData(String name, String pass){  
     //create SqLiteDatabase object  
     SQLiteDatabase db=this.getWritableDatabase();//for write data  
     //use contentvalue object for store data  
     ContentValues values=new ContentValues();  
     values.put(UNAME,name);  
     values.put(UPASS,pass);  
     return db.insert(TABLE,null,values); //return a long value  
   }  
   public ArrayList<Model> getAllData(){  
     //create arraylist for store value  
     ArrayList<Model>alName= new ArrayList<>();  
     //create database object  
     SQLiteDatabase dbR=this.getReadableDatabase(); //for read data only  
     Cursor res= dbR.rawQuery("Select*From "+TABLE+"",null);  
     res.moveToFirst();  
     while (res.isAfterLast()==false){  
       Model m=new Model();  
       m.setID(res.getString(res.getColumnIndex(ID)));  
       m.setUNAME(res.getString(res.getColumnIndex(UNAME)));  
       m.setUPASS(res.getString(res.getColumnIndex(UPASS)));  
       alName.add(m);  
       res.moveToNext();  
     }  
     return alName;  
     //it's done!!  
   }  
   //for delete user  
   public int deleteUser(String id){  
     //create sqlitedatabase object  
     SQLiteDatabase dbDelete=this.getWritableDatabase();  
     return dbDelete.delete(TABLE,"id=?",new String[]{id});  
     //delete user using id  
   }  
   public boolean updateUser(String id, String username, String password){  
     //Create database object  
     SQLiteDatabase dbupdate=this.getWritableDatabase();//for write database  
     //use contentvalue object  
     ContentValues values=new ContentValues();  
     values.put(UNAME,username);  
     values.put(UPASS,password);  
      dbupdate.update(TABLE,values,"id=?",new String[]{id});  
      return true;  
     //update is done  
     //use both method in UserList  
   }  
 }  

In MainActovity.java(Insert data )

MainActivity.Java


 <pre style="font-family:arial;font-size:12px;border:1px dashed #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;;background-image:URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjcwAy69ZcVBuibf34RNj7EZRxw1YNkOUp1v82nE0Pq7THFj23OZW3fnMOAEWVQ7tJBMmCFRCs8YAlHGOQYSIO7-wePdeqCirNzgB9D91H_KphBnTXwB3gHUY1UXiLBtSIa4vP9fHjIhDli/s320/codebg.gif);padding:0px;color:#000000;text-align:left;line-height:20px;"><code style="color:#000000;word-wrap:normal;"> package com.example.aaru.sqldatabase;   
  import android.content.Intent;   
  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 {   
   EditText edtName,edtPass;   
   Button btnSubmit,btnView;   
   DBHelper dbHelper;   
   @Override   
   protected void onCreate(Bundle savedInstanceState)   
   {   
    super.onCreate(savedInstanceState);   
    setContentView(R.layout.activity_main);   
    edtName=findViewById(R.id.edtUname);   
    edtPass=findViewById(R.id.edtPass);   
    btnSubmit=findViewById(R.id.btnSubmit);   
    btnView=findViewById(R.id.btnView);   
    btnView.setOnClickListener(new View.OnClickListener() {   
     @Override   
     public void onClick(View view) {   
      Intent i2=new Intent(MainActivity.this,UserList.class);   
      startActivity(i2);   
     }   
    });   
    dbHelper=new DBHelper(this);   
    btnSubmit.setOnClickListener(new View.OnClickListener() {   
     @Override   
     public void onClick(View view) {   
      if (dbHelper.insertData(edtName.getText().toString(),edtPass.getText().toString())!=-1){   
       //if data not insert we get -1   
       Toast.makeText(MainActivity.this, "INSERT SUCCESS", Toast.LENGTH_SHORT).show();   
       //let's run   
      }   
     }   
    });   
   }   
  }   
 </code></pre>  


Model.java


 package com.example.aaru.sqldatabase;  
 /**  
  * Created by Aaru on 11/17/2017.  
  */  
 public class Model {  
   String ID;  
   String UNAME;  
   public String getID() {  
     return ID;  
   }  
   public void setID(String ID) {  
     this.ID = ID;  
   }  
   public String getUNAME() {  
     return UNAME;  
   }  
   public void setUNAME(String UNAME) {  
     this.UNAME = UNAME;  
   }  
   public String getUPASS() {  
     return UPASS;  
   }  
   public void setUPASS(String UPASS) {  
     this.UPASS = UPASS;  
   }  
   String UPASS;  
   //use getter setter method  
 }  


View database in UserList using simple array list

UserList(ListView)


 package com.example.aaru.sqldatabase;  
 import android.content.DialogInterface;  
 import android.content.Intent;  
 import android.support.v7.app.AlertDialog;  
 import android.support.v7.app.AppCompatActivity;  
 import android.os.Bundle;  
 import android.view.LayoutInflater;  
 import android.view.View;  
 import android.widget.AdapterView;  
 import android.widget.ArrayAdapter;  
 import android.widget.EditText;  
 import android.widget.ListView;  
 import android.widget.Toast;  
 import java.util.ArrayList;  
 public class UserList extends AppCompatActivity {  
   //create simple listview  
   ListView listView;  
   ArrayList<String>alName=new ArrayList<>();  
   ArrayList<Model>allModel=new ArrayList<>();  
 DBHelper dbHelper;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_user_list);  
     listView=findViewById(R.id.listView);  
     dbHelper=new DBHelper(this);  
     //call getData method  
      allModel=dbHelper.getAllData();  
     //this sore multiple data in almodel  
     //get Uname from alModel  
     for (int i=0;i<allModel.size();i++){  
       alName.add(allModel.get(i).getUNAME());  
       //username store in alNames  
     }  
     ArrayAdapter adapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,alName);  
     listView.setAdapter(adapter);  
     listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {  
       @Override  
       public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {  
         Toast.makeText(UserList.this, alName.get(i), Toast.LENGTH_SHORT).show();  
         //lets run app  
         //create view Button in Main Activity  
       }  
     });  
     listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {  
       @Override  
       public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int userposition, long l) {  
         //Create layout xml for custom Dialog  
         AlertDialog.Builder dialogInterface=new AlertDialog.Builder(UserList.this);  
         LayoutInflater inflater=UserList.this.getLayoutInflater();  
         final View dialogView=inflater.inflate(R.layout.customdialog,null);  
         dialogInterface.setView(dialogView);//view is set  
         //get id  
         final EditText username=dialogView.findViewById(R.id.dialog_UserName);  
         final EditText password=dialogView.findViewById(R.id.dialog_Password);  
         username.setText(allModel.get(userposition).getUNAME());  
         password.setText(allModel.get(userposition).getUPASS());  
         dialogInterface.setTitle("UPDATE | DELETE");  
         dialogInterface.setMessage("Are you sure you went UPDATE |DELETE :"+allModel.get(userposition).getUNAME());  
         dialogInterface.setPositiveButton("UPDATE", new DialogInterface.OnClickListener() {  
           @Override  
           public void onClick(DialogInterface dialogInterface, int i) {  
           //Update  
             dbHelper.updateUser(allModel.get(userposition).getID(),username.getText().toString(),password.getText().toString());  
             Toast.makeText(UserList.this, "Update Success", Toast.LENGTH_SHORT).show();  
             finish();  
             startActivity(getIntent());//refresh activity  
           }  
         });  
         dialogInterface.setNegativeButton("DELETE", new DialogInterface.OnClickListener() {  
           @Override  
           public void onClick(DialogInterface dialogInterface, int i) {  
             //DELETE  
            dbHelper.deleteUser(allModel.get(userposition).getID());  
             Toast.makeText(UserList.this, "DELETED", Toast.LENGTH_SHORT).show();  
             finish();  
             startActivity(getIntent());//refresh activity  
             //Run App  
           }  
         });  
         AlertDialog b= dialogInterface.create();  
         b.show();  
         //dialog is created  
         return false;  
       }  
     });  
   }  
 }  

Use ListView widgets in UserList.xml

UserList_Activity.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"  
   android:padding="15dp"  
   tools:context="com.example.aaru.sqldatabase.UserList">  
   <ListView  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:id="@+id/listView"  
     ></ListView>  
 </LinearLayout>  

Create custom layout xml for custom dialog.

CustomDialog.xml


 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:orientation="vertical"  
   android:padding="15dp"  
   >  
   <EditText  
   android:layout_width="match_parent"  
   android:layout_height="wrap_content"  
   android:hint="Username"  
   android:id="@+id/dialog_UserName"  
   />  
   <EditText  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:hint="Password"  
     android:id="@+id/dialog_Password"  
     />  
 </LinearLayout>  




>>>>>>>>>>END!!<<<<<<<<<<<
>>>>>>>>>>Enjoy Code<<<<<<<<<<<









No comments:

Post a Comment