Created
March 1, 2014 21:49
-
-
Save msdalp/9297983 to your computer and use it in GitHub Desktop.
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.test.db; | |
import android.content.ContentValues; | |
import android.content.Context; | |
import android.database.Cursor; | |
import android.database.sqlite.SQLiteDatabase; | |
import android.database.sqlite.SQLiteOpenHelper; | |
import android.util.Log; | |
import java.util.List; | |
import com.test.db.MainActivity.Data; | |
public class MyDb extends SQLiteOpenHelper { | |
public static final String TAG = "MyDb"; | |
public static final int VERSION = 1; | |
public static final String DATABASENAME = "mydb"; | |
public MyDb(Context context) { | |
super(context, DATABASENAME, null, VERSION); | |
} | |
@Override | |
public void onCreate(SQLiteDatabase db) { | |
db.execSQL("CREATE TABLE IF NOT EXISTS data" | |
+ " (ID INTEGER PRIMARY KEY, " | |
+ "DATA_ID TEXT, " | |
+ "VALUE TEXT);"); | |
} | |
@Override | |
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { | |
} | |
public synchronized boolean addData(List<Data> _objects) { | |
final SQLiteDatabase db = this.getWritableDatabase(); | |
boolean retval = false; | |
try { | |
for (Data object : _objects) { | |
ContentValues contentValues = new ContentValues(); | |
contentValues.put("ID", object.id); | |
contentValues.put("DATA_ID", object.dataId); | |
contentValues.put("VALUE", object.value); | |
db.insert("data", null, contentValues); | |
// db.insertWithOnConflict("data", null, contentValues, SQLiteDatabase.CONFLICT_REPLACE); | |
} | |
retval = true; | |
} catch (Exception ex) { | |
Log.e(TAG, "addData exception", ex); | |
} finally { | |
db.close(); | |
} | |
return retval; | |
} | |
public synchronized String getDataValue(long _id) { | |
final SQLiteDatabase db = this.getReadableDatabase(); | |
String retval = null; | |
try { | |
Cursor cursor = db.query("data", new String[]{"VALUE"}, | |
"ID = ?", new String[]{String.valueOf(_id)}, null, null, null); | |
if (cursor != null) { | |
if (cursor.moveToFirst()) { | |
do { | |
retval = cursor.getString(0); | |
} while (cursor.moveToNext()); | |
} | |
} | |
} catch (Exception ex) { | |
retval = null; | |
Log.e(TAG, "Cannot get data value:", ex); | |
} finally { | |
db.close(); | |
} | |
return retval; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment