Last active
June 22, 2016 23:24
-
-
Save yahyaahrika/4dc9c9d61ca20458df53593df755cb82 to your computer and use it in GitHub Desktop.
Connection DataBase Sqlite android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.cco.statrt.service; | |
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 HP on 21/06/2016. | |
*/ | |
public class DbConnection extends SQLiteOpenHelper { | |
public static final String DbName="student.db"; | |
public static final int version=1; | |
//Constants for identifying table and columns | |
public static final String TABLE_NOTES = "notes"; | |
public static final String NOTE_ID = "_id"; | |
public static final String NOTE_TEXT = "noteText"; | |
public static final String NOTE_CREATED = "noteCreated"; | |
SQLiteDatabase db; | |
//SQL to create table | |
private static final String TABLE_CREATE = | |
"CREATE TABLE " + TABLE_NOTES + " (" + | |
NOTE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + | |
NOTE_TEXT + " TEXT, " + | |
NOTE_CREATED + " TEXT default CURRENT_TIMESTAMP" + | |
")"; | |
public DbConnection(Context context) { | |
super(context, DbName, null, version); | |
} | |
@Override | |
public void onCreate(SQLiteDatabase sqLiteDatabase) { | |
sqLiteDatabase.execSQL(TABLE_CREATE); | |
} | |
@Override | |
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { | |
sqLiteDatabase.execSQL("DROP TABLE IF NOT EXISTS '"+TABLE_NOTES+"'"); | |
} | |
public void InsertNotes(String text){ | |
db=getWritableDatabase(); | |
ContentValues cv=new ContentValues(); | |
cv.put(NOTE_TEXT,text); | |
db.insert(TABLE_NOTES,null,cv); | |
} | |
public void UpdateNotes(int id,String text){ | |
db=getWritableDatabase(); | |
ContentValues cv=new ContentValues(); | |
cv.put(NOTE_TEXT,text); | |
db.update(TABLE_NOTES,cv,NOTE_ID+" = ?",new String[]{Integer.toString(id)}); | |
} | |
public void DeleteNotes(int id){ | |
db=getWritableDatabase(); | |
db.delete(TABLE_NOTES,NOTE_ID+" = ?",new String[]{Integer.toString(id)}); | |
} | |
public ArrayList SelectNotes(){ | |
ArrayList array_list =new ArrayList(); | |
SQLiteDatabase db=this.getReadableDatabase(); | |
Cursor cr=db.rawQuery("select * from "+TABLE_NOTES, null); | |
cr.moveToFirst(); | |
while(cr.isAfterLast()==false){ | |
array_list.add(cr.getString(cr.getColumnIndex(NOTE_ID))+":"+ | |
cr.getString(cr.getColumnIndex(NOTE_TEXT)).substring(0,25)+"..."); | |
cr.moveToNext(); | |
} | |
return array_list; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
tes