With API16 the new WAL (Write Ahead Logging) was introduced in Androids SQLiteDatabase class. I would like to test if WAL is enabled for a SQLite database. The app runs on older Android releases too, so I need a wrapper class for these new functions in SQLiteDatabase. The functions are:
public boolean isWriteAheadLoggingEnabled()
public boolean enableWriteAheadLogging()
public void disableWriteAheadLogging ()
In the Android Developer Blog I did find an article for a wrapper class that wraps new classes. What I didn't find is a wrapper for new methods in an already existing class. How should I do that?
The constructor for SQLiteDatabase is private so your're not going to be able to extend it and add "wrappers" to the class itself. You can however just write a "helper" wrapper like so:
public class WALWrapper {
private boolean mAvailable;
private Method mIsWriteAheadLoggingEnabled;
private Method mEnableWriteAheadLogging;
private Method mDisableWriteAheadLogging;
private final SQLiteDatabase mDb;
public WALWrapper(SQLiteDatabase db) {
mDb = db;
mAvailable = false;
try {
mIsWriteAheadLoggingEnabled =
SQLiteDatabase.class.getMethod("isWriteAheadLoggingEnabled");
mEnableWriteAheadLogging =
SQLiteDatabase.class.getMethod("enableWriteAheadLogging");
mDisableWriteAheadLogging =
SQLiteDatabase.class.getMethod("disableWriteAheadLogging");
mAvailable = true;
} catch (NoSuchMethodException e) {
}
}
/**
* Returns <code>true</code> if the {#link #isWriteAheadLoggingEnabled()},
* {#link #enableWriteAheadLogging()} and {#link #disableWriteAheadLogging()}
* are available.
* #return <code>true</code> if the WALWrapper is functional, <code>false</code>
* otherwise.
*/
public boolean isWALAvailable() {
return mAvailable;
}
public boolean isWriteAheadLoggingEnabled() {
boolean result = false;
if (mIsWriteAheadLoggingEnabled != null) {
try {
result = (Boolean) mIsWriteAheadLoggingEnabled.invoke(mDb);
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
return result;
}
public boolean enableWriteAheadLogging() {
boolean result = false;
if (mEnableWriteAheadLogging != null) {
try {
result = (Boolean) mEnableWriteAheadLogging.invoke(mDb);
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
return result;
}
public void disableWriteAheadLogging() {
if (mDisableWriteAheadLogging != null) {
try {
mDisableWriteAheadLogging.invoke(mDb);
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
}
}
Related
I try to implement the recommendation made in item #11 of issue 111316656 that says:
You should also be able to use reflection to get access to the FloatingActionButtonImpl backing the fab, and then call setImageMatrixScale(1) on that instance.
with the following code:
FloatingActionButton fab;
...
Method method = null;
try {
method = fab.getClass().getMethod("setImageMatrixScale", null);
method.invoke(fab, 1);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
But the NoSuchMethodException is raised. What is the problem?
Try like here
BluetoothGatt localBluetoothGatt = gatt;
java.lang.reflect.Method localMethod = localBluetoothGatt.getClass().getMethod("refresh", new Class[0]);
if (localMethod != null) {
boolean bool = ((Boolean) localMethod.invoke(localBluetoothGatt, new Object[0])).booleanValue();
return bool;
}
With the help of Mike M. (see comments in the question), this is the JAVA version of the workaround included in the referenced issue:
fab.show(new FloatingActionButton.OnVisibilityChangedListener() {
#Override
public void onShown(FloatingActionButton fab) {
try {
Field implField = FloatingActionButton.class.getDeclaredField("impl");
implField.setAccessible(true);
Object impl = implField.get(fab);
Class cls;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
cls = impl.getClass().getSuperclass();
} else {
cls = impl.getClass();
}
Method mthd = cls.getDeclaredMethod("setImageMatrixScale", Float.TYPE);
mthd.setAccessible(true);
mthd.invoke(impl, 1);
} catch (Exception e) {
e.printStackTrace();
}
}
});
I want to get users Advertising ID programmatically.I used the below code from the developer site.But its not working
Info adInfo = null;
try {
adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
} catch (IOException e) {
// Unrecoverable error connecting to Google Play services (e.g.,
// the old version of the service doesn't support getting AdvertisingId).
} catch (GooglePlayServicesNotAvailableException e) {
// Google Play services is not available entirely.
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GooglePlayServicesRepairableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final String id = adInfo.getId();
final boolean isLAT = adInfo.isLimitAdTrackingEnabled();
How can I get user's advertising id programmatically ?? please help me
I might be late but this might help someone else!
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
AdvertisingIdClient.Info idInfo = null;
try {
idInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String advertId = null;
try{
advertId = idInfo.getId();
}catch (NullPointerException e){
e.printStackTrace();
}
return advertId;
}
#Override
protected void onPostExecute(String advertId) {
Toast.makeText(getApplicationContext(), advertId, Toast.LENGTH_SHORT).show();
}
};
task.execute();
Get GAID(Google’s advertising ID)
1. Download latest Google Play Services SDK.
2. Import the code and add it as a library project.
3. Modify AndroidManifest.xml.
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
4. Enable ProGuard to shrink and obfuscate your code in project.properties this line
proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
5. Add rules in proguard-project.txt.
-keep class * extends java.util.ListResourceBundle {
protected Object[][] getContents(); }
-keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable {
public static final *** NULL; }
-keepnames #com.google.android.gms.common.annotation.KeepName class *
-keepclassmembernames class * {
#com.google.android.gms.common.annotation.KeepName *;
}
-keepnames class * implements android.os.Parcelable {
public static final ** CREATOR;
}
6. Call AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext()).getId() in a worker thread to get the id in String.
as like this
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
AdvertisingIdClient.Info idInfo = null;
try {
idInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
String advertId = null;
try{
advertId = idInfo.getId();
}catch (Exception e){
e.printStackTrace();
}
return advertId;
}
#Override
protected void onPostExecute(String advertId) {
Toast.makeText(getApplicationContext(), advertId, Toast.LENGTH_SHORT).show();
}
};
task.execute();
Enjoy!
or
https://developervisits.wordpress.com/2016/09/09/android-2/
You can call the below function in onCreate(Bundle savedInstanceState) of the activity
and in the logcat search for UIDMY then it will display the id like : I/UIDMY: a1cf5t4e-9eb2-4342-b9dc-10cx1ad1abe1
void getUIDs()
{
AsyncTask.execute(new Runnable() {
#Override
public void run() {
try {
AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(SplashScreen.this);
String myId = adInfo != null ? adInfo.getId() : null;
Log.i("UIDMY", myId);
} catch (Exception e) {
Toast toast = Toast.makeText(context, "error occurred ", Toast.LENGTH_SHORT);
toast.setGravity(gravity, 0,0);
toast.show();
}
}
});
}
Just in case someone is interested in trying out the fetching AdvertisingId part while Rx-ing then this might be helpful.
private void fetchAndDoSomethingWithAdId() {
Observable.fromCallable(new Callable<String>() {
#Override
public String call() throws Exception {
return AdvertisingIdClient.getAdvertisingIdInfo(context).getId();
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<String>() {
#Override
public void call(String id) {
//do what you want to do with id for e.g using it for tracking
}
}, new Action1<Throwable>() {
#Override
public void call(Throwable throwable) {
throwable.printStackTrace();
}
});
}
The modern way is to use Coroutines in Kotlin, since AsyncTask is now being deprecated for Android. Here is how I did it:
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class AdvertisingInfo(val context: Context) {
private val adInfo = AdvertisingIdClient(context.applicationContext)
suspend fun getAdvertisingId(): String =
withContext(Dispatchers.IO) {
//Connect with start(), disconnect with finish()
adInfo.start()
val adIdInfo = adInfo.info
adInfo.finish()
adIdInfo.id
}
}
When you are ready to use the advertising ID, you need to call another suspending function:
suspend fun applyDeviceId(context: Context) {
val advertisingInfo = AdvertisingInfo(context)
// Here is the suspending function call,
// in this case I'm assigning it to a static object
MyStaticObject.adId = advertisingInfo.getAdvertisingId()
}
Fetch the advertising id from background thread:
AsyncTask.execute(new Runnable() {
#Override
public void run() {
try {
AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(mContext);
String adId = adInfo != null ? adInfo.getId() : null;
// Use the advertising id
} catch (IOException | GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException exception) {
// Error handling if needed
}
}
});
I added null checks to prevent any crashes. The Google example implementation code would crash with a NullPointerException if an exception occures.
With OS validation.
Call this in an AsyncTask
/** Retrieve the Android Advertising Id
*
* The device must be KitKat (4.4)+
* This method must be invoked from a background thread.
*
* */
public static synchronized String getAdId (Context context) {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
return null;
}
AdvertisingIdClient.Info idInfo = null;
try {
idInfo = AdvertisingIdClient.getAdvertisingIdInfo(context);
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String advertId = null;
try{
advertId = idInfo.getId();
}catch (NullPointerException e){
e.printStackTrace();
}
return advertId;
}
If you are using Kotlin use this to get the Google Advertising ID of the device
CoroutineScope(Dispatchers.IO).launch {
var idInfo: AdvertisingIdClient.Info? = null
try {
idInfo = AdvertisingIdClient.getAdvertisingIdInfo(applicationContext)
} catch (e: GooglePlayServicesNotAvailableException) {
e.printStackTrace()
} catch (e: GooglePlayServicesRepairableException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
var advertId: String? = null
try {
advertId = idInfo!!.id
} catch (e: NullPointerException) {
e.printStackTrace()
}
Log.d(TAG, "onCreate:AD ID $advertId")
}
import com.google.android.gms.ads.identifier.AdvertisingIdClient.Info;
Info adInfo = null;
try {
adInfo = AdvertisingIdClient.getAdvertisingIdInfo(mContext);
} catch (IOException e) {
e.printStackTrace();
} catch (GooglePlayServicesAvailabilityException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
String AdId = adInfo.getId();
You need add gms libs otherwise you cannot get the advertising id. It can be reset by user or when you do a factory reset (at factory reset time the Android id also reset).
Make sure you have added play identity services, then you can get advertising id by running a thread like this:
Thread thread = new Thread() {
#Override
public void run() {
try {
AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
String advertisingId = adInfo != null ? adInfo.getId() : null;
} catch (IOException | GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException exception) {
exception.printStackTrace();
}
}
};
// call thread start for background process
thread.start();
You only need this package:
implementation("com.google.android.gms:play-services-ads-identifier:17.0.0")
It's not really listed anywhere but it's published on Mavne.
Get Google Services using
GoogleApiAvailabilityLight.getInstance
You need to run your code using Async Task
try this
Using the new Android Advertiser id inside an SDK
Using Kotlin & RxJava Observers
Import in your Gradle file
implementation 'com.google.android.gms:play-services-ads:15.0.0'
Import on top of your kotlin source file
import io.reactivex.Observable
import com.google.android.gms.ads.identifier.AdvertisingIdClient
Implement a helper function
private fun fetchAdIdAndThen(onNext : Consumer<String>, onError : Consumer<Throwable>) {
Observable.fromCallable(Callable<String> {
AdvertisingIdClient.getAdvertisingIdInfo(context).getId()
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(onNext, onError);
}
Then
fetchAdIdAndThen(Consumer<String>() {
adId ->
performMyTaskWithADID(activity, 10000, adId);
}, Consumer<Throwable>() {
throwable ->
throwable.printStackTrace();
performMyTaskWithADID(activity, 10000, "NoADID");
})
I am using ormLite to store data on device.
I can not understand why but when I store about 100 objects some of them stores too long time, up to second.
Here is the code
from DatabaseManager:
public class DatabaseManager
public void addSomeObject(SomeObject object) {
try {
getHelper().getSomeObjectDao().create(object);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public class DatabaseHelper extends OrmLiteSqliteOpenHelper
public Dao<SomeObject, Integer> getSomeObjectDao() {
if (null == someObjectDao) {
try {
someObjectDao = getDao(SomeObject.class);
} catch (Exception e) {
e.printStackTrace();
}
}
return someObjectDao;
}
Any ideas to avoid this situations?
Thanks to Gray!
Solution is, as mentioned Gray, using callBatchTasks method:
public void updateListOfObjects (final List <Object> list) {
try {
getHelper().getObjectDao().callBatchTasks(new Callable<Object> (){
#Override
public Object call() throws Exception {
for (Object obj : list){
getHelper().getObjectDao().createOrUpdate(obj);
}
return null;
}
});
} catch (Exception e) {
Log.d(TAG, "updateListOfObjects. Exception " + e.toString());
}
}
Using this way, my objects (two types of objects, 1st type - about 100 items, 2nd type - about 150 items) store in 1.7 sec.
See the ORMLite documentation.
I'm currently stuck with the following situation;
Basically I've got a Work class, which has a ForeignCollection of WorkTasks.
I'd like to simply receive all WorkTasks, linked to Work object.
If I query for all WorkTasks, I do get a list of results but with 'work = null'. So it can't make any link to the correct Work object.
Resulting in no results with querying for the work_id and an empty list in Work itself.
I've seen examples and questions about this countless of times but apparently im missing out on something.
Below is the code that im using which is relevant;
The DatabaseHelper;
#Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
applicantDao = DaoManager.createDao(connectionSource, Applicant.class);
educationDao = DaoManager.createDao(connectionSource, Education.class);
workDao = DaoManager.createDao(connectionSource, Work.class);
workTaskDao = DaoManager.createDao(getConnectionSource(), WorkTask.class);
onlinePersonDao = DaoManager.createDao(connectionSource, OnlinePerson.class);
institutionDao = DaoManager.createDao(connectionSource, Institution.class);
lessonDao = DaoManager.createDao(connectionSource, Lesson.class);
TableUtils.createTable(connectionSource, Applicant.class);
TableUtils.createTable(connectionSource, Education.class);
TableUtils.createTable(connectionSource, Work.class);
TableUtils.createTable(connectionSource, Institution.class);
TableUtils.createTable(connectionSource, Lesson.class);
TableUtils.createTable(connectionSource, OnlinePerson.class);
TableUtils.createTable(connectionSource, Reference.class);
TableUtils.createTable(connectionSource, WorkTask.class);
[....]
public Dao<WorkTask, Integer> getWorkTaskDao() {
if (null == workTaskDao) {
try {
workTaskDao = getDao(WorkTask.class);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
return workTaskDao;
}
The database manager:
public List<Experience> getAllWork() {
List<Experience> exp = null;
try {
exp = getHelper().getWorkDao().queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}
return exp;
}
public List<WorkTask> getAllWorkTask() {
List<WorkTask> workTask = null;
try {
workTask = getHelper().getWorkTaskDao().queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}
return workTask;
}
public List<WorkTask> getWorkTaskByWorkId(int workId) {
List<WorkTask> workTasks = null;
try {
workTasks = getHelper().getWorkTaskDao().queryForEq("work_id", workId);
} catch (SQLException e) {
e.printStackTrace();
}
return workTasks;
}
public void addWork(Collection<Work> jobs) {
try {
for (Experience work : jobs) {
Work w = (Work) work;
// Add nested child first
this.addInstitution(w.institution);
this.addWorkTask(w.tasks);
getHelper().getWorkDao().createOrUpdate(w);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void addWorkTask(Collection<WorkTask> worktasks) {
try {
for (WorkTask wt : worktasks) {
getHelper().getWorkTaskDao().createOrUpdate(wt);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
The list from the work model (gets a pre-filled id from an abstract parent):
#ForeignCollectionField(eager = true)
#SerializedName("tasks")
public Collection<WorkTask> tasks;
public ArrayList<WorkTask> getTasks(){
ArrayList<WorkTask> taskList = new ArrayList<WorkTask>();
Iterator iterator = tasks.iterator();
while(iterator.hasNext()){
WorkTask task = (WorkTask) iterator.next();
taskList.add(task);
}
return taskList;
}
The WorkTask :
public class WorkTask {
/**
* Auto-incremented id for the ORMLite-SQLite database
*/
#DatabaseField(generatedId = true)
public int id;
/**
* Foreign field id for the ORMLite-SQLite database
*/
#DatabaseField(foreign = true, foreignAutoCreate = true, foreignAutoRefresh = true, columnName = "work_id")
public Work work;
And finally all the things that are failing me:
ArrayList<WorkTask> tasks_iterated = work.getTasks();
ArrayList<WorkTask> tasks_id = (ArrayList<WorkTask>) DatabaseManager.getInstance()
.getWorkTaskByWorkId(work.id);
ArrayList<WorkTask> tasks = (ArrayList<WorkTask>) DatabaseManager.getInstance().getAllWorkTask();
This eventually leaves me with:
tasks_iterated = empty
tasks_id = empty
tasks = a full list of my tasks but all with the attribute 'work = null' so I can't place them to the correct Work object.
Fixed it by changing my adding method to:
public void addWorkTask(Collection<WorkTask> worktasks, Work work) {
try {
for (WorkTask wt : worktasks) {
wt.work = work;
getHelper().getWorkTaskDao().createOrUpdate(wt);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Not sure if it's the only way to do this though. Seems a bit weird i'd have to do this manually.
In my app, after user logs in, database is created. When user logs out, I have to delete the database from the internal storage to save space. The problem is, after deleting the database and a user logs back in, database cannot be created anymore. I tried using .close() but it only makes the problem worse.
Here is my code.
DatabaseHelper
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final String DATABASE_PATH = "/mnt/sdcard/Philpost/databases/";
private static final String DATABASE_NAME = "DeliveriesDB.sqlite";
private static final int DATABASE_VERSION = 1;
// the DAO object we use to access the SimpleData table
private Dao<DeliveriesDB, Integer> DeliveriesDbDao = null;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database,
ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, DeliveriesDB.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
throw new RuntimeException(e);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource,
int oldVersion, int newVersion) {
try {
Log.i(DatabaseHelper.class.getName(), "onUpgrade");
TableUtils.dropTable(connectionSource, DatabaseHelper.class, true);
onCreate(db, connectionSource);
} catch (java.sql.SQLException e) {
// TODO Auto-generated catch block
Log.e(DatabaseHelper.class.getName(), "Cant drop database", e);
e.printStackTrace();
}
}
public Dao<DeliveriesDB, Integer> getDeliveriesDbDao() {
if (null == DeliveriesDbDao) {
try {
DeliveriesDbDao = getDao(DeliveriesDB.class);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
return DeliveriesDbDao;
}
}
DatabaseManager
public class DatabaseManager {
static private DatabaseManager instance;
static public void init(Context ctx) {
if (null == instance) {
instance = new DatabaseManager(ctx);
}
}
static public DatabaseManager getInstance() {
return instance;
}
private DatabaseHelper helper;
public DatabaseManager(Context ctx) {
helper = new DatabaseHelper(ctx);
}
public DatabaseHelper getHelper(Context ctx) {
if(helper == null){
helper = OpenHelperManager.getHelper(ctx, DatabaseHelper.class);
}
return helper;
}
public void releaseDb(Context ctx) {
DatabaseConnection connect;
try {
connect = getHelper(ctx).getConnectionSource()
.getReadWriteConnection();
getHelper(ctx).getConnectionSource().releaseConnection(connect);
helper = null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void closeDb(){
helper.close();
}
public List<DeliveriesDB> getAllDeliveriesDB(Context ctx) {
List<DeliveriesDB> deliveriesdb = null;
try {
deliveriesdb = getHelper(ctx).getDeliveriesDbDao().queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}
return deliveriesdb;
}
public void addDeliveriesDb(DeliveriesDB l, Context ctx) {
try {
getHelper(ctx).getDeliveriesDbDao().create(l);
} catch (SQLException e) {
e.printStackTrace();
}
}
public DeliveriesDB getDeliveriesDbWithId(int deliveriesDbId, Context ctx) {
DeliveriesDB deliveriesDb = null;
try {
deliveriesDb = getHelper(ctx).getDeliveriesDbDao().queryForId(
deliveriesDbId);
} catch (SQLException e) {
e.printStackTrace();
}
return deliveriesDb;
}
public void deleteDeliveriesDb(DeliveriesDB deliveriesDb, Context ctx) {
try {
getHelper(ctx).getDeliveriesDbDao().delete(deliveriesDb);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void refreshDeliveriesDb(DeliveriesDB deliveriesDb, Context ctx) {
try {
getHelper(ctx).getDeliveriesDbDao().refresh(deliveriesDb);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void updateDeliveriesDb(DeliveriesDB deliveriesDb, Context ctx) {
try {
getHelper(ctx).getDeliveriesDbDao().update(deliveriesDb);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
The class where creation and deletion of database happens
public class DeliveryListActivity extends ListActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DatabaseManager.init(this);
setContentView(R.layout.deliverylist_layout);
if (getLastNonConfigurationInstance() != null) {
deliveryIndex = (Integer) getLastNonConfigurationInstance();
}
if (PhilpostApplication.DELIVERIES == null) {
new RetrieveDeliveriesTask().execute();
} else {
updateCachedList(PhilpostApplication.DELIVERIES);
}
}
private void updateCachedList(List<Delivery> deliveries) {
File expath = context.getFilesDir();
String apppath = "/databases/DeliveriesDB.sqlite";
File path = new File(expath, apppath);
adapter = new DeliveryListAdapter(this,
R.layout.deliverylist_row_layout, deliveries);
setListAdapter(adapter);
PhilpostApplication.DELIVERIES = deliveries;
Log.d(TAG, "Updating UI list");
if (PhilpostApplication.firstDb) {
if (!path.exists()) {
createBackupDb();
Log.d(TAG, "DB first Creation");
}
}
}
public void createBackupDb() {
for (int i = 0; i < PhilpostApplication.DELIVERIES.size(); i++) {
// create db first
dId = PhilpostApplication.DELIVERIES.get(i).getId();
rId = PhilpostApplication.DELIVERIES.get(i).getRecipientId();
lastn = PhilpostApplication.DELIVERIES.get(i).getLastName();
firstn = PhilpostApplication.DELIVERIES.get(i).getFirstName();
addr = PhilpostApplication.DELIVERIES.get(i).getAddress();
dtype = PhilpostApplication.DELIVERIES.get(i).getType();
amount = PhilpostApplication.DELIVERIES.get(i).getCash();
pMan = PhilpostApplication.DELIVERIES.get(i).getPostman();
stats = PhilpostApplication.DELIVERIES.get(i).getStatus();
createNewDeliveriesDb(dId, rId, lastn, firstn, addr, dtype, amount,
pMan, stats);
keyNum[i] = PhilpostApplication.DELIVERIES.get(i).getId();
}
Log.d(TAG, "database created");
PhilpostApplication.firstDb = false;
}
public void logout() {
if (PhilpostApplication.listSynced == false) {
// if( checkIfSyncedList() ){
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Sync data first before logging out.")
.setCancelable(false).setPositiveButton("OK", null);
final AlertDialog alert = builder.create();
alert.show();
} else {
dialog = ProgressDialog.show(this, "Logging out", "please wait");
try {
WebService.logout();
PhilpostApplication.SESSION_KEY = null; // clear Application
// Session
// Key
AccountStore.clear(this);
// clear cached list
PhilpostApplication.DELIVERIES = null;
MemoryUtils.deleteCache(this);
PhilpostApplication.incompleteSync = false;
PhilpostApplication.loggedIn = false;
PhilpostApplication.firstDb = true;
DatabaseManager.getInstance().closeDb();
deleteInternalDb();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (PhilpostApplication.canToggleGPS) {
turnGpsOff();
}
dialog.dismiss();
exitActivity();
}
}
}
Deleting Database
public void deleteInternalDb() {
File internalDb = new File(
Environment.getDataDirectory()
+ "/data/packagename/databases/DeliveriesDB.sqlite");
if (internalDb.exists()) {
internalDb.delete();
Log.d(TAG, "Internal Db deleted");
}
}
Check the example here this will give you an idea how to use existing database.
when your getting response from db follow following formate. it work fine bcz i had face this problem.we must have close db in finally block try this it may help you.
try
{
//Query
}
catch
{
}
finally
{
c.close();
db.close();
}