How To Create Database In Android Studio ?? (Database)

Just Simple 

Create New DbHelper Java File and paste below code this code do all create, modify, read and delete (CRUD) operations



package com.devduos.encryptedpassword;

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

import androidx.annotation.Nullable;

public class DBHelper extends SQLiteOpenHelper {
public DBHelper(@Nullable Context context) {
super(context, "userdetails.db", null,1);
}

@Override
public void onCreate(SQLiteDatabase DB) {
DB.execSQL("create Table userdetails(id Text ,name Text,password Text)");
}

@Override
public void onUpgrade(SQLiteDatabase DB, int i, int i1) {
DB.execSQL("drop Table if exists userdetails");
}

public boolean insertuserdata(String id,String name,String password){
SQLiteDatabase DB=this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("id",id);
contentValues.put("name",name);
contentValues.put("password",password);
long result=DB.insert("userdetails",null,contentValues);
if(result==-1){
return false;
}else{
return true;
}
}

public boolean updateuserdata(String id,String name,String password){
SQLiteDatabase DB=this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("name",name);
contentValues.put("password",password);
Cursor cursor=DB.rawQuery("Select * from userdetails where id=?",new String[]{id});

if(cursor.getCount()>0){
long result=DB.update("userdetails",contentValues,"id=?",new String[] {id});
if(result==-1){
return false;
}else{
return true;
}
}else{
return false;
}
}

public boolean deleteuserdata(String id){
SQLiteDatabase DB=this.getWritableDatabase();
Cursor cursor=DB.rawQuery("Select * from userdetails where id=?",new String[]{id});

if(cursor.getCount()>0){
long result=DB.delete("userdetails","id=?",new String[] {id});
if(result==-1){
return false;
}else{
return true;
}
}else{
return false;
}
}

public Cursor getuserdata(){
SQLiteDatabase DB=this.getWritableDatabase();
Cursor cursor=DB.rawQuery("Select * from userdetails",null);
return cursor;
}
}

Comments

Popular posts from this blog

How to add layout inflator (Layout Inflators)

Creating RecyclerView and adjusting its margins