Post


Sqlite Helper Class

Sqlite Helper Class

name the file :
DatabaseHelper.java


package in.iocare.sqlitetest;

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

public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "data.db";
public static final String TBL_NAME = "tempdata";
public static final String COL_1 = "ID";
public static final String COL_2 = "nodename";
public static final String COL_3 = "degc";

public DatabaseHelper(@Nullable Context context) {
super(context, DB_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TBL_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT,nodename TEXT,degc TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TBL_NAME);
onCreate(db);
}

public boolean insertData(String nodename,String degc) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,nodename);
contentValues.put(COL_3,degc);
long result = db.insert(TBL_NAME,null ,contentValues);
if(result == -1)
return false;
else
return true;
}

public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TBL_NAME,null);
return res;
}

public boolean updateData(String id,String nodename,String degc) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,id);
contentValues.put(COL_2,nodename);
contentValues.put(COL_3,degc);
db.update(TBL_NAME, contentValues, "ID = ?",new String[] { id });
return true;
}

public Integer deleteData (String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TBL_NAME, "ID = ?",new String[] {id});
}
}
Posted in Internet 09 Dec 2018