Advertisement
iNoobAvicena

DatabaseHelper

Nov 18th, 2021
64
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package com.example.tugassqlfirebase;
  2.  
  3. import android.content.ContentValues;
  4. import android.content.Context;
  5. import android.database.Cursor;
  6. import android.database.sqlite.SQLiteDatabase;
  7. import android.database.sqlite.SQLiteOpenHelper;
  8.  
  9. import androidx.annotation.Nullable;
  10.  
  11. public class DatabaseHelper extends SQLiteOpenHelper {
  12.  
  13. Context context;
  14. static final String DATABASE_NAME = "User.db";
  15. static final int DATABASE_VERSION = 1;
  16.  
  17. static final String TABLE_NAME = "user";
  18. static final String COLUMN_ID = "_id";
  19. static final String COLUMN_NAME = "fullname";
  20. static final String COLUMN_USERNAME = "username";
  21. static final String COLUMN_AGE = "age";
  22. static final String COLUMN_STATUS = "status";
  23.  
  24. DatabaseHelper(@Nullable Context context) {
  25. super(context, DATABASE_NAME, null, DATABASE_VERSION);
  26. this.context = context;
  27. }
  28.  
  29. @Override
  30. public void onCreate(SQLiteDatabase db) {
  31. String query = " CREATE TABLE " + TABLE_NAME +
  32. " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
  33. COLUMN_NAME + " TEXT, " +
  34. COLUMN_USERNAME + " TEXT, " +
  35. COLUMN_AGE + " TEXT, " +
  36. COLUMN_STATUS + " TEXT); ";
  37. db.execSQL(query);
  38.  
  39. String insert = " INSERT INTO " + TABLE_NAME + " VALUES ( 1, 'Herza Avicena', 'Apicendol', '21', 'Available' )";
  40.  
  41. db.execSQL(insert);
  42. }
  43.  
  44. @Override
  45. public void onUpgrade(SQLiteDatabase db, int i, int i1) {
  46. db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
  47. onCreate(db);
  48. }
  49.  
  50. void updateData (String id, String fullname, String username, String age, String status) {
  51. SQLiteDatabase db = this.getWritableDatabase();
  52. ContentValues cv = new ContentValues();
  53. cv.put(COLUMN_NAME, fullname);
  54. cv.put(COLUMN_USERNAME, username);
  55. cv.put(COLUMN_AGE, age);
  56. cv.put(COLUMN_STATUS, status);
  57.  
  58. db.update("user", cv, "_id = ?", new String[]{"1"});
  59. }
  60.  
  61. Cursor readData () {
  62. SQLiteDatabase DB = this.getWritableDatabase();
  63. Cursor cursor = DB.rawQuery("SELECT * FROM user", null);
  64. return cursor;
  65. }
  66. }
  67.  
Advertisement
RAW Paste Data Copied
Advertisement