How to call the web service only once in android - android

I have three tabs in my view. Every time when I press the each tab some layout will be inflated and a web service call is done. I am populating some data into my inflated view through this web service call. Everything is working fine. But the problem is I don't want to call the web service every time when I press the tab for the second time. Previous data should be populated automatically without making a call to the web service. I don't think I can use onResume() method for this. Googled out many pages to find this answer but nothing is helpful. Please post the code if necessary. Thanks in advance.
These are my workarounds till now.
TabHost setCurrentTab only calls oncreate method for Activity in Tab once
http://developer.android.com/training/basics/activity-lifecycle/recreating.html
http://jnastase.alner.net/archive/2010/10/27/handling-orientation-change-in-android.aspx

Your webservice should return some data, keep this data to your local memory and check every time either this data is null or not, if null then call service otherwise inflate from local data.

First of all, you should know the state of your 'call': not calling, pending, called. You must store it somewhere (activity, shared preferences, database etc) then making a call. Now, for data: you should implement some caching (again, in activity, shared preferences, database or even in plain files).
Then, in any state of a call, you can show data from cache, if it exists, and when call is done you can store new data in cache and show it.

whenever any changes made in one tab, store value in some variable, whenever next time the page is initialized, initialize with old selected value. Please try it out.. It may solve the problem..

Related

Android RecyclerView reloading the activity to update data vs notifyDataSetChanged efficiency?

I have an activity that in onCreate calls an API and populates a RecyclerView with product names, current stock, and an EditText to insert a value for each product.
You can then hit an add or subtract button at the top of the activity and all products with an inserted value will have their stock updated in the database by the given values via the API.
I do not pass the on screen stock values to the API (as another user may have changed it in the meantime), simply the inserted values, product ids and whether to increment/decrement the database value.
Currently, after I send the update request and it is successful, I call finish() and just reload the activity to get the updated data.
I'm wondering if it would be better to make an API call for the data after the update request and then just update the RecyclerView, it would almost be duplicate code of the onCreate but would prevent reloading the activity.
Does anyone have any insight as to the efficiency of this vs reloading the activity? It seems like reloading would be the more inefficient option but i'm not too sure.
Assume in your onCreate method you have something like this:
onCreate() {
setContentView(xx);
callApiGetDataAndSetDataToRecyclerView();
}
If so, pls try to change the code like below after I send the update request and it is successful:
doAfterUpdateRequestSuccessful() {
List<Object> latestData = callApiGetData() // this should not be in the ui thread, I believe you are clear about it but just want to repeat
recyclerViewAdapter.setData(latestData);
recyclerViewAdapter.notifyDataSetChanged();
}
Then your recycler view will be updated with latest data.
And like #ADM's comment, finish and recreate the activity is never a solution for updating recycler view, the ux will be very very bad.
Reload the activity is not so efficient. You should instead move your fetch data and render logic to an independent method and invoke this method from onCreate and every time you want to refresh the rendered data.

Fragments, Activities , and Data

I have an android application where I have an activity with two fragments. One with a map view and the other with a listview. In the main activity I get the user's gps and results from the database based off the gps and send that data to the fragments. That made since instead of calling inside the fragment twice the same data. However, a lot of times the request for the backend data and the gps coordinates of the user are not completed before the fragments are created.
I set up an interface to pass the data back and forth but need to find a way to pause the fragment creation until all data is there.
Any ideas? I can post code if neccesary.
Don't "pause" the fragment. Have a "loading" state, a "loaded" state, and an "error" state. Then show the user what is going on between each state.
You should not block the fragment UI until the data is ready, but instead you should show the user that the page is loading (e.g. with a Progress Bar).
Once the data is ready, you should populate the fragments with data (through a callback) or show an error message.
Thanks for the responses. I found a better way to do it. So I was passing data from the activity to fragment via an Interface and in the onAttach method of the fragment. Instead I created a Local Broadcast Manager that listens for the data to be complete in the activity class and sends to the map fragment to populate.
Hope this helps someone else.

Recommended method to retrieve data to display (from an API) in an Android Fragment

If I need to display data coming from an API in a Fragment (using an AsyncTask), let's say a list of items in a RecyclerView, I believe it shouldn't be done in onCreate() or onCreateView() since theoretically the view elements are being initialized and may not be ready to use if the call to the API is faster. Am I correct?
(I assume it's kind of impossible to get a response from an API in less time than it takes for Android to create the view though).
There is onActivityCreated() and onStart() but I am still confused about when the parent Activity calls them.
The thing I want to avoid is reloading data (making a call to the API) if it's not necessary, for instance because of an orientation change or going back to this Activity after a click on the back button from a possible "next" Activity.
Thanks.
If it is your first "window" (Activity or whatever) the only way I know is showing a loading text, image, etc.
If it isn't your first view you can load your data in another window and store it to later usage when the user reaches the View to show the info.
You can load it right in your onCreate, onStart or so, but as you said probably you won't have time to download the info, so again, show a loading page or whatever you want while your data comes.
To avoid initialization errors call your AsyncTask after initializing the elements. And to avoid calling the API multiple times save your data locally while the app is opened, it depends on your app requirements

Android Fragment : which life cycle method to use for web service call

I am developing an application in which several fragments are involved.
In each fragment I have to call web service to fetch data.
Currently I am calling web service from onCreateView() method of Fragment. Issue i am getting that whenever web service call is in progress and if device orientation is changed then new web service call starts invoking.
I think this might be because onCreateView() method gets called on configuration change.
How can I solve this. and which Life cycle method should I use to call web service so that it will be get called only once
I have resolved this by following workaround
Create an operation identifier for each web service call method. E.g. for example "Authentication" for login call
Create one object of ArrayList say currentTasks
ArrayList<String> currentTasks = new ArrayList<String>();
In every method where I am calling web service, check if operation identifier of corresponding method is already present in ArrayList. If not then start operation.
String operationId = "Authentication";
if(currentTasks.indexOf(operationId) == -1)
{
<do web service call operation here>
currentTasks.add(operationId);
}
Method in which above operation's response is receiving, remove operation identifier from ArrayList
if(currentTasks.indexOf("Authentication") != -1){
currentTasks.remove("Authentication");
}
This will ensure that call will not go to web method which is currently in progress.
I know this is not the best way to achieve it and this might not the best practice to follow but for now this works for me.
If your web service code is getting restarted due to a device orientation change, than you're probably using an AsyncTask. This is a common problem with AsyncTasks and you have several ways to solve it.
One common workaround is to wrap your AsyncTask around an invisible Fragment and make sure this fragment does not get destroyed and recreated again during an orientation change. Check out this tutorial on how to do it: Retaining Objects Across Config Changes
A simple solution would be to use a static variable pointing to asynctask. Create and call an AsyncTask if variable is not null.
Regards,
Prateek

Cannot see the changes from database after adding in android?

I have tabs activities. one activity gets data from local database, but when I add information to database through another activity and back to the activity which shows the database contents, I don't see the changes! >> I need to re-run the applications to see the changes !
why and how to solve it ?
Ahh you probably need to re-bind your adapter, or call notifyDataSetChanged() on your adapter.
For instance, in your onResume() method call listView.setAdapter(new MySpecialAdapter()). That way no matter if your program is resumed from your other activity, or some other program, it will refresh the data.

Categories

Resources