I am trying to use a Parse Query to fill up an ArrayList. I understand that findInBackground() is async, so it does not necessarily finish running before the rest of the code is executed on the main thread. However, my next function in the main thread requires that the ArrayList is filled. How can I wait for the findInBackground() callback to finish before I proceed with the next function?
This is my first time working with android studio and java, so any advice or examples would be appreciated.
after you get response, callback's method done is called and you can add your code inside this method and handle the result.
Example:
ParseQuery<ParseObject> query = new ParseQuery("SOME_CLASS");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
//here you can add your code
//you get your result as a List of parse objects - objects
}
});
Related
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 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!
I am trying to get a value from native method in my Java program. But for some reason, the native method is not responding.My program is stuck over there. So, If no response from native method for 2mins, then my java code should have the control again and proceed further.
How should I implement this? Simply I want control back from native method after some time..
you can start a runnable so that thread will call the native method you want , and this will be bugged for 2 mins not the main application.
Runnable updateRunnable = new Runnable() {
#Override
public void run() {
yourObject.yourFuctionCall();
}
}
new Thread(updateRunnable).start();
hope it helps
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
Every time I do a httpRequest, the screen will appear to be locked up for a few seconds while the code is executing. Hence I used AsyncTask to do all my httpRequest stuff in a separate thread while putting up a ProgressDialog so the user knows something is happening.
I recently encountered the following situation: the input of one of my httpRequest is dependent on the result from a previous httpRequest (+parse) action. I can't just put the two AsyncTasks sequentially cause Android will put them in two threads and start the second one without the first one being finished. And without an appropriate input (the result of the first httpRequest), my second httpRequest will crash the app.
Is there way I can put-in a wait() to force the second AsyncTask not to start until the first one finishes?
I also had some same situation the other day.
I had solved it in this way:
Pass the reference of your activity to the constructor of async class and execute the do in background function. Now in post execute function call a public method of ur activity from async class to execute the task again... or try this:
if (asynclass.getStatus() == android.os.AsyncTask.Status.PENDING) {
asynclass.execute();
} else if (RF.getStatus() == android.os.AsyncTask.Status.FINISHED) {
asynclass = new asyncclass();
asynclass.execute();
} else {
Toast.maketoast(this, "Plz wait", 1).show();
}
Cheers
so i think(not sure),you need to call second asyncTask on post execution method
protected void onPostExecute(final Void unused) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
new secTask().execute();
}}
Yes, you can. But it is only possible in onProgressUpdate() or onPostExecute(). Try doing it like this:
private class Task1 extends AsyncTask<Void, Void, Void> {
...
...
protected void onPostExecute(Void unused) {
dialog1.dismiss();
new Task2().execute();
}
}
Similarly, you'll have to put new Task3().execute(); in the onPostExecute() method of Task2's AsyncTask
Don't call them like this in your main code. If you do, then all of them will run together:
// This is wrong
new Task1().execute();
new Task2().execute();
new Task3().execute();
Reference: AsyncTask
How about using executOnExecutor method :
public void runTasks() {
AsyncTask<Void,Void,Void> aTask = myTask();
AsyncTask<Void,Void,Integer> aTask1 = myTask1();
AsyncTask<Void,Void,Void> aTask2 = myTask2();
aTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
aTask1.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
aTask2.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}
Stumbled on this thread looking for a better solution than what I currently use, but it still seems the best...
What I do is pass a runnable in the constructor of each of my async tasks.
Either in the post execute or at the end of the do in the background, I launch my next task, if I have one by executing the runnable.
if(doOnPostExec != null)
doOnPostExec.run();
This way I can changeup the order of my asynctasks by the runnables I pass keeping the code flexible, and if I pass no runnable they complete normally. The runnables just contain one line calling the next asynctask.
I just don't like making all those runnables. Was hoping something existed like in vb.net for chaining delegates.
I encountered this problem before. What I did is use a call back interface class and call its method inside the onPostExecute() method. This way you can call another AsyncTask from the callback method.