I am createing checkbox list from an arrayList that I am getting from the Server, programmatically.The checkBox list is being created but I am facing problem that the value change in the MySQL table every minute. Regarding, I have to update the values of checkboxes list in the MainActivity. Is there any way in Android to update the values (getText) of the checkboxes in the MainActivity immediately like Ajax in JavaScript?
What I am trying to achieve, to rebuild the check box list in the MainActivity when value of the tables's record changes immediately. Which approach can I use to achieve that or the best what I can achieve, to remove the chechbox list element from the xml file and then send a new request to the Server periodically?
I appreciate any help.
Try to use this code in you onPostExecute()
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
new MyAsyncTask().execute();
}
}, 5*60*1000); // this is for a gap of 5 minutes
Maybe I understand what you want, update information from server continuous. Still using Handler, but by this way:
final Handler updateInfoHandler;
protected void onCreate(Bundle savedInstanceState) {
...
updateInfoHandler.post(new Runnable() {
#Override
public void run() {
//code update infomation
updateInfoHandler.postDelayed(this, 60000);//auto update info each 60s
}
});
}
Related
I have a method that loads data from Firebase into ArrayList. After this,I use that ArrayList to construct RecyclerView. I've decided to load data on another thread. Below is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_just);
citiesRecyclerView =
(RecyclerView)findViewById(R.id.recyclerView);
handler = new Handler()
{
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what==1)
{
cityAdapter = new
CityAdapter(MainActivity.this,cities) ;
citiesRecyclerView.setAdapter(cityAdapter);
}
}
};
t = new Thread(new Runnable() {
#Override
public void run() {
//method that loads data into List.If this method was
//successfully done,then I send message 1 to Handler
loadDataFromFirebase();
}
});
t.start();
//other operations below
}
Hope,that everything understandable. Code works fine. And my problem is that I need to use loadDataFromFirebase method in thread again. I wanted to call t.start() again in order to call loadDataFromFirebase method,but there was error that thread already started. I checked that by writing this code:
if(t.getState()== Thread.State.NEW)
t.start();
else
someMethod();
else statement worked above.
And my questions are:
1) Does loadDataFromFirebase method work really on another thread by this way?
2) How to call loadDataFromFirebase method again in another thread, if something happened? Do I need to create another variable for Thread again?
It's not a good idea to handle all low-level thread work by your own.
Accroding to Android you could:
Use AsyncTask (but notice that they have many drawbacks such as context leak in some cases etc),
I could suggest you to get into RxJava - it's a painless way to use async work in your app.
To 'download' data from Firebase you could probably use FCM (push notifications) to load data on demand.
And what about your question:
"It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution."(c) http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html#start()
If you are using firebase SDK you can use realtime database feature, so do not need to query it each time.
You should just subscribe one time and get updates. For example:
firebaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
YourDataObject value = dataSnapshot.getValue(YourDataObject.class);
Log.d(TAG, "Value is: " + value);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
You can read docs here.
My situation is the following: I have a RecyclerView in which I want to insert data.
I add data one by one until the RecyclerView is full. The data comes from a web service.
This is the code I use:
#Override
public void receive(Response response) {
_adapter.add(response.getData());
new Handler().post(new Runnable() {
#Override
public void run() {
fetchIfNotFull();
}
});
}
private void fetchIfNotFull() {
if (_layoutManager.findLastVisibleItemPosition() == _layoutManager.getItemCount() - 1)
fetchData(); // this will call receive(Response) when it's done
}
The problem is that, when I run the application, the RecyclerView is not filled, like I expect (but sometimes it does!).
I found out that _layoutManager.findLastVisibleItemPosition() does not always return the correct value (the one I expect at least), whereas _layoutManager.getItemCount() does, so no more data are fetched...
I thought that wrapping the call inside the Handler would help, so it would be called after the next layout update, but it didn't do the trick.
And here is the strange thing: If I call handler.postDelayed() with 1000 milliseconds, it works fine! (I didn't try other values), because the layout was updated after that time. But I don't like this solution (hack). Is there a way to make sure that the LayoutManager has been updated?
After the line
_adapter.add(response.getData());
add this one
_adapter.notifyItemChanged(_adapter.getItemCount() - 1);
I have ListView of Persons, ArrayAdapter to display images of this persons. There is two buttons "like" and "dislike" under photos of each person. If I press like or dislike button, this item deleted with animation from list:
protected void removeListItem(View rowView, final int positon) {
Animation out = AnimationUtils.makeOutAnimation(getActivity(), true);
rowView.startAnimation(out);
rowView.setVisibility(View.INVISIBLE);
Handler handle = new Handler();
handle.postDelayed(new Runnable() {
public void run() {
persons.remove(positon);
mMyAnimListAdapter.notifyDataSetChanged();
}
}, 500);
}
Also there is some API that generates list of person that we can get. This API makes changes to the list (status changes to one of the next value: "none", "removed", "liked, "disliked").
If status changed to "removed" I need to remove this person from list and update ListView. I do this so:
if (changedPerson.getStatus().equals("removed")) {
persons.remove(index);
mMyAnimListAdapter.notifyDataSetChanged();
notifyRemovedStatus(idOfChangedPerson);
}
But when I do this, a lot of bugs occured:
List updates only after tap.
The fragment isn't closed if last item removed from list.
ArrayIdexOfBound Exception some times occured if we press on like/dislike button.
Can you help me, why is this hepenned and how to fix it?
The solution was easy, here code without bugs:
if (changedPerson.getStatus().equals("removed")) {
persons.remove(index);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
mMyAnimListAdapter.notifyDataSetChanged();
if (persons.size() == 0) {
getActivity().onBackPressed();
}
}});
notifyRemovedStatus(idOfChangedPerson);
}
I violated this rule "Do not access the Android UI toolkit from outside the UI thread".
This video explains working conceop:
https://www.udacity.com/course/viewer#!/c-ud853/l-1469948762/e-1530568562/m-1530568563
And this documentation was useful: http://developer.android.com/guide/components/processes-and-threads.html
I'm using Volley for Android. I have a ListView in a fragment. If this ListView is empty (only possible if the connection failed/no internet/etc.), I want to send a GET request to the server for the data, then populate the ListView accordingly if it succeeds. If the call failed, I want to call it again in 5 minutes. This goes on until it succeeds.
What is the best way to achieve this? I'm new to Android development. I read about Services, but IDK if that is overkill.
You could use ScheduledExecutorService to manage and schedule your request.
Take a look at:
http://tutorials.jenkov.com/java-util-concurrent/scheduledexecutorservice.html
http://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService.html
I use to have a layer to define all my calls to services. Lets say ServiceLayer.java for example.
You could define a Handler as a global variable. (You will need to create the ServiceLayer in the MainThread). And then manage the error in the service call making the handler recall the service in 5 minutes. Something like this
public class ServiceLayer {
Handler handler = new Handler();
...
public void callToService(final String parameter,final String moreParameters,final Callback callbackDefinedByYou){
StringRequest req = new StringRequest(Method.GET, url, new Response.Listener<String>(){
#Override
public void onResponse(String s) {
//Do whatever you need, populate listviews etc
callbackDefinedByYou.populateListView(s);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Manage the error and recall again this service
callbackDefinedByYou.onError(volleyError);
handler.postDelayed(new Runnable() {
public void run(){
callToService(parameter, moreParameter, callbackDefinedByYou);
}
}, 300000); //5 minutes
}
});
VolleyHelper.addRequestToQueue(req);
}
In this code, everytime service fails a recall is made but, in some cases you should stop doing net calls. For example when you detect there is no internet conexion, and let the user refresh screen
I have a question regarding grid views in android.
I have a grid of 5x5 images. And I want to change these images continously. Loads new set of images from the array every time.
I have a random generator function which changes the value of the mThumbIds array after it loads every time.
But I am unable to apply the new images before it needs some event to render the new set of images. Here I do not have any event. I want them to change continuously.
Can you please me.
Unable to find any solution for this.
Did you try using an AsyncTask to change your images ? The AsyncTask could change one image, then launch a new AsyncTask.
An other option is to use a Handler. That may be your best option actually. http://mobileorchard.com/android-app-developmentthreading-part-1-handlers/
Do you mean a timer to trigger the image changing function every 2 seconds?. If so try a Handler. Something like
private Handler mHandler = new Handler();
public void onCreate(Bundle savedInstanceState) {
// init grid and set first batch of images
}
protected void onResume() {
mHandler.postDelayed(mUpdateImagesTask , 2000);
}
private Runnable mUpdateImagesTask = new Runnable() {
public void run() {
// Code to change the images
// call me in 2 seconds...
mHandler.postDelayed(this, 2000); // 2 seconds
}
};
If you want to stop the loop just put some conditions to call Handler.postDelayer() inside mUpdateImagesTask or call mHandler.removeCallbacks(mUpdateImagesTask) from outside the Runnable (at a button click, i.e).