I have a trouble, i need to get event/callback when i try to write to database.
I added greenDao lib to project, and i able to write/delete in db.
But no idea how to get callback after some operation under db.
In introduction to lib i read "AsyncOperationListener for asynchronous callback when operations complete".
Used this tutorial:
http://blog.surecase.eu/using-greendao-with-android-studio-ide/
Can anybody help me with this trouble?
UPD:
ok here we added some list in storage
getMyObjectDao().getSession().startAsyncSession().insertOrReplaceInTx(MyObject.class, list);
error here
List<MyObject> items = getBoxDao(c).getSession().startAsyncSession().loadAll(MyObject.class);
How can we asynchronously load data from db?
Is this correct solution?
#Override
public void onAsyncOperationCompleted(AsyncOperation operation) {
String operationIs = null;
switch (operation.getType()) {
case LoadAll:
itemsList = BoxRepository.getAllBoxes(getApplicationContext());
By default all the operations are performed synchronously, eliminating the need to get any callback. But the recent version of GreenDAO introduces AsyncSession, which can be used to perform operations asynchronously and also provides a way set listener on it. See the example below:
AsyncSession asyncSession = App.getInstance().daoSession.startAsyncSession();
asyncSession.setListener( new AsyncOperationListener() {
#Override
public void onAsyncOperationCompleted(AsyncOperation operation) {
// do whats needed
}
});
asyncSession.insert(MyObject);
Simple ask if anything unclear!
Related
Does using SnapshotParser while querying Firestore an expensive operation in terms of read operation?
We are building query in our app like this:
options = new FirestoreRecyclerOptions.Builder<Item>()
.setQuery(query, new SnapshotParser<Item>() {
#NonNull
#Override
public Item parseSnapshot(#NonNull DocumentSnapshot snapshot) {
Item item = snapshot.toObject(Item.class);
item.setId(snapshot.getId());
return item;
}
})
.setLifecycleOwner(this)
So while reading data from server, does SnapshotParser will make extra read operation (or hit server again) or it will parse using already read data?
Would it be the same operation(in terms of server hit) with or without SnapshotParser?
Please explain, if anything is missed, please let me know? Sorry for bad english.
From the official documentation of Firebsase-UI library:
If you need to customize how your model class is parsed, you can use a custom SnapshotParser.
So if you need to customize your model class it doesn't mean that you are creating extra read operations. The parseSnapshot() method uses as an argument a DocumentSnapshot object which contains the data set that you are getting from the database for which you are already charged in terms of read operations. This is happening if the the query return data. If your query does not return any data, you are still charged but only with a single read operation.
Here's my question: I have an app that needs to make a write operation, on an SQLite database, one time per second, it is better to use an AsyncTask to write data on this database or not?
public void insertData(Data data) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues RecordValues = new ContentValues();
RecordValues.put("uid", data.getUid());
RecordValues.put("id_usr", data.getUserId());
RecordValues.put("id_route", data.getIdRoute());
RecordValues.put("lat", data.getLatitude());
RecordValues.put("lng", data.getLongitude());
RecordValues.put("timestamp", data.getTime());
RecordValues.put("privacy", data.getTime());
db.insert("DBNAME", null, RecordValues);
db.close();
}
The DB is implemented by using a SqLiteClass.
The app makes some heavy tasks, working with live data, web-socket, google map and so on, so I want to optimize on this point.
I don't know if starts an asyncTask one time per second is better or not, i can make a mistake falling in error so we can speak about that.
Thanks in advance.
Yes, this is recommended to have the database operation in a background thread. You might consider using an AsyncTask or Handler to handle the DB operations in a background thread instead of putting this in the main UI thread.
You might be also curious about getting the update on your database on changing or inserting an item to your database table. You might consider, using the content observer to get notified about the content changes in your database table. Please check the LoaderCallbacks functions.
I have created a project in Github here to demonstrate the database operations using LoaderCallbacks. However, I have put all the database operations in the UI thread. It is better to handle them inside another thread using AsyncTask or Handler.
Do not insert data in main thread.if your data is big it might be hung up MainThread.
its better to insert in background thread useing AsyncTask,Handler,Third Party library RxJava.
and must use beginTransaction().
public void dbInsert()
{
db.beginTransaction();
//do your insertion.
db.setTransactionSuccessful();
db.endTransaction();
}
If I were you I would use a dedicated HandlerThread for that. Android Performance video series by Google recommends to use it, when you have a significant amount of operations to perform and they can be split into parts. You could do something like this:
//make sure you have one instance of this HandlerThread
private HandlerThread updateThread = acquireThisThread();
private Handler updateHandler;
private void someInitializingFunction() {
updateThread.start()
updateHandler = new Handler(updateThread.getLooper())
}
private void onEachSecondCallback() {
updateHandler.post(new Runnable() {
#Override
public void run() {
//your insertingDataFunction
insertData(getDataSomehow());
}
});
}
private void someDeinitializingFunction() {
updateThread.quit();
}
And here you have a link to the performance video. It uses totaly different example ,but if you base on that you will get why HandlerThread is cool here.
https://www.youtube.com/watch?v=adPLIAnx9og
I am trying to implement a solution for storing reference data in the database of my app.
The data is initially stored as JSON files, which I will need to sync from a server on each launch. I have a local copy of the files baked into the app. Each launch I have to check shared preferences for a version. And if it not present, I assume it is the first launch. So i need to read in the files, write the files to the database and fire on completed when that is done. The first screen expects this data to be in the database, so I will be not showing the UI for that screen in this scenario, until the process completes.
However in the future the network call to sync these files can happen asynchronously so want to be able to fire on completed on my observable as soon as i see the shared prefs have a version number and then ill kick of the update completely asynchronously
How can i set up a stream to represent this. I think the stream type will probably be void and i will just fire onCompleted/error as the subscriber doesnt care about the data, only what the process is complete
You could do something like this:
updateChecker.hasUpdates()
.flatMap(hasUpdates -> {
if (hasUpdates) {
return dataUpdater.update();
}
return Observable.just(false);
})
Assuming that
class UpdateChecker {
public Observable<Boolean> hasUpdates() {
return Observable.just(true); // Replace by API call
}
}
class DataUpdater {
public Observable<Boolean> update() {
// update the database here
return Observable.just(true);
}
}
I have been working on a library for Android. The library has a method which fetches data from a web service and puts it in a database. The fetching part is, of course, not done on the main thread. Here's a sample method:
public void fetchData() {
remoteTable.get(new TableOperationCallback<TEntity>() {
public void onCompleted(TEntity entity, Exception exception, ServiceFilterResponse response) {
if (exception == null) {
//CALBACK RECEIVED
//Put data in local database.
}
});
}
Now, somewhere else in my app, where the library is being consumed, I do something like this to refresh the data:
public void refreshData(){
mylibrary.fetchData();
List<MyItems> mList = localtable.getItems();
}
Here, the first statement will go and fetch the data on background thread. So, the second statement will be executed even before the data is actually fetched. How do I get around this? I want the second statement to be executed only after the callback of the first is complete.
Edit: If it matters, the method refreshData is not in any activity. I put that method in a separate class (and called it ViewModel - .NET habit!).
You can have a look at this link
Android Update Current Activity From Background Thread
You basically want a Callback interface. When the task in the library completes, then you do what you have to do
I am taking my first steps with Apache Wicket and ran into the following problem. I have a ListView that displays a "delete" link right next to its entries. When the delete link is clicked, the entity represented by the list item is deleted from the database but the list itself does not get updated until I reload the page manually in the browser.
IModel<List<SampleEntity>> sampleEntityListModel = new LoadableDetachableModel<List<SampleEntity>>() {
#Override
protected List<SampleEntity> load() {
return mSampleEntityBA.findAll();
}
};
mListview = new ListView<SampleEntity>("listview", sampleEntityListModel) {
#Override
protected void populateItem(final ListItem<SampleEntity> item) {
item.add(new Label("listlabel", new PropertyModel<String>(item.getModelObject(),
"text")));
item.add(new Link<SampleEntity>("deleteLink", item.getModel()) {
#Override
public void onClick() {
mSampleEntityBA.delete(item.getModelObject());
}
});
}
};
When onClick called, item.getModelObject() pulls from the sampleEntityListModel which in turn calls mSampleEntityBA.findAll(). The model object of sampleEntityListModel will be cached for the duration on the request cycle (until it is detached - which is usually what you want) and is not aware of the call to delete().
In order to refresh the sampleEntityListModel, add a sampleEntityListModel.detach() call just after the delete (sampleEntityListModel must be made final, but this will not cause any extra state to be serialized). This will cause the model to fetch a fresh set of data when the list view is rendered later in the request cycle.
You probably want an AjaxLink instead of that Link, and then you have to make the list refresh, using the tactics described here, possibly adjusting a bit for the fact that the wiki has Wicket 1.3 code instead of 1.4.
But you might also be better off with a different repeater, such as a RefreshingView or a DataView. There are some examples of assorted repeaters here. While none of them are exactly what you're looking for, looking at that code might help.
looks like the problem is that your mSampleEntityBA.findAll(); is returning incorrect data. hard to help without seeing more code.
on a different note, you should really be using DataView when working with database-backed lists.
You might also want to check out JQGrid from the wiQuery project instead of DataView.