Created
July 7, 2016 18:53
-
-
Save yahyaahrika/04df18c0a0679529b29c1deb33e1b9aa to your computer and use it in GitHub Desktop.
[Unfinished] Class to manage a local SQL database on an android device
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.onlocation.tracker; | |
import android.content.Context; | |
import android.database.Cursor; | |
import android.database.sqlite.*; | |
import java.util.ArrayList; | |
//Creates, opens and provides methods to manage a database | |
public class DatabaseManager { | |
public SQLiteDatabase openOrCreateDatabase(Context context, String tableName, String fields) { | |
SQLiteDatabase db = context.openOrCreateDatabase("OnlocationLocalDatabase", Context.MODE_PRIVATE, null); | |
db.execSQL("CREATE TABLE IF NOT EXISTS " + tableName + " " + fields + ";"); | |
return db; | |
} | |
public void insertRow(SQLiteDatabase db, String tableName, String fields, String values) { | |
db.execSQL("INSERT INTO " + tableName + " " + fields + " " + "VALUES " + values + ";"); | |
} | |
public void updateRow(SQLiteDatabase db, String tableName, ArrayList<String> fields, ArrayList<String> newValues, String fieldName, String fieldValue) { | |
db.execSQL("UPDATE " + tableName + "SET " + createUpdateQuery(fields, newValues) + " WHERE " + fieldName + " = '" + fieldValue + "';" ); | |
} | |
public void removeRow(SQLiteDatabase db, String tableName, String fieldName, String fieldValue) { | |
db.execSQL("DELETE FROM " + tableName + " " + "WHERE " + fieldName + " = '" + fieldValue + "';"); | |
} | |
public Integer getRowCount(SQLiteDatabase db, String tableName) { | |
Cursor c = db.rawQuery("SELECT COUNT(*) FROM " + tableName + ";", null); | |
return c.getCount(); | |
} | |
private String createUpdateQuery(ArrayList<String> fields, ArrayList<String> newValues) { | |
String query = null; | |
for(int i = 0; i<fields.size(); i++) { | |
query += fields.get(i) + "='" + newValues.get(i) + "', "; | |
} | |
return query; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment