Android - Single data request class that handle a lot of activity - java

Im new to android and just learning how to pass data from server using json and volley.
what i want to ask is:
if i have a lot of activities on my apps, and each of every activity need to take data from the server, and I need to use json in every single class, and put the requeststring in it, which is very redundant.
Is there a way to put all the functions in just 1 class (maybe static), so I will have 1 class that only handling the data request from the client to the server. I found it really confusing, because at the same time, I need to modify the UI when the apps received the data (eg. move to another activity, or just simple change the textview).
So, basically the class will check whether the data exist on the database, if not, it will request the data from the server, and return it to the activity
it is possible to do this? Is there any tutorial that I can refer to?
Thanks a lot! cheers!

Related

How to get access to values from every Activity using Service

I trying to make the app similar to Nissan Leaf Spy. This app receives data from bluetooth interface ELM 327. My goal is to collect data like:
Speed
Temperature
Power
Battery capacity
And some more data
And display them on real time chart using GraphView.
For one parameter is one chart in Activity. So there are at least as many Activities as parameters I need to display. My guess is to use
Android Services
to do work in background to co collect and save every data in different array via bluetooth. Of course when I change Activity to see another Activity the one that works will stop working and there will be no more real time.
The question is: is there any kind of 'superclass' that is always working or do I need to save this data using SQL? Or should I just use intent.putExtraString(key,value) and getIntent().getStringExtra(key). I will be grateful for your help!
About having different activities for different parameters, you need to have just one activity. You can have a graph and different ArrayLists with adapters for parameters and then use one of them to feed the graph according to the parameter selected say, from a Spinner.
To feed those ArrayLists is just as easy. You can have a Service running, for general data collection, with an AsyncTask inside it, which will keep the feed live for a selected parameter when the app is active and not in the background. The Service, by itself, can collect data in some sort of a buffer large enough to feed those graphs.
Remember, AsyncTasks are good for updating UI components without blocking the main thread.
EDIT: Look, if you have an activity (let's consider some other activity than main) where you're going to show the data or graph, you can have AsyncTask running as soon as you enter the activity(you can define a default parameter for a graph to be shown) or when you select from a drop down, giving you real-time data while you're on the activity.
The reason I am using AsyncTask for the live feed is that you can have different UI views and seamlessly integrate without any future problems and that it'd modularize Service into functionalities for serving Activity and would end when you close the app. The Service running in the background would primarily provide to a temp log file or be an InputStream source for AsyncTask when it runs after app launch or activity launch.

Best practices to get data and save it

I have an android application and in one of my activities I am making a call to get say "Customers", this call is made to an external API, when I get the response I get it as a JSON object. The problem i am having is that I have a ListView in the activity and when you click on of its items it shows you the details but then when you hit the back button I have to make the call again to populate it. In Samsung Galaxy 4S it seems to keep the data of the list view but in the HTC android incredible it's blank. So what I did is, make it rebind OnResume(), this fixed the issues for both BUT the consequence is making another call to that server. When its 10 or 100 customers it doesnt matter but I know that there are some accounts that have up to 5000 and I am sure it will crash.
What are my options to improve performance on this issue with Android?, I tried a static variable but at some point that object got cleared too.
How do Android applications usually handle this cases where the data is retrieved from API's and they need to be stored through out the application and there is no need to make another call for the same information?, I was thinking on static object but i want to make sure I do this the right way.
You have a couple of options.
1) You can cache the data in memory. For example you can make a static cache or cache the data within the Activity or the App object. If you are doing this in only one view and if it is not a lot of data, this might be an ok solution. However, if you have to do this for many activities and there is a lot of data that has to be cached, you might want to go for option 2. Also storing data in memory in android, does not mean it won't be garbage collected (in some cases, even if you have a reference to it.)
2) You can cache the data in the internal storage and refresh it from time to time.
You can find more info about the internal storage and how to use it here: http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
Basically, you store the response within the internal storage under a specific identifier. The next time you open the activity, you check if the storage has data for that identifier and if yes, you read it and display it. If no, you make the API call.
Keep in mind, that you will have to refresh the cache from time to time.
I had the problem with ListViews on my application too. What I did is that I wrote a custom adapter and that solved the issue..
However the thing you can do is to make a global variable and save the returned results to it. When your application wants to call the server, check the variable, if it's null make the call, if it's not then just draw the ListView with the already fetched data..
Keep in my mind, to implement a refresh button, you need to skip the check.

One connection shared between two fragments

I started to write my first mature Android application and I stuck...
I want to implement tablet view easily to I used android compatibility library v4 and fragments API. Everything was cool until I created network connection and share it beetween two fragments. You know, I have two views...
Let's assume that we have simple chat application and we need to have user list and messages list. I need to implement those both fragments depending from message received from network. So if someone is entering chat I need to update userlist fragment and if someone send new message I need to send it to messages fragment
Could anyone tell me how to do it?
Any ideas how to update both fragments with one connection.
Thanks in advance
You should have a separate CommunicationManager Class which handles all the sending & receiving - the fragments only display the information you need - all the communication logic is in this one class. Then you will have no problems with your app logic anymore.
As far as I understood you want to use one network connection (saying generally), receive a response and again display it in two different fragments.
There are some patterns you can follow to do that, but here are some suggestions to solve your problem.
Try to use the standard Android pattern where you will have:
A class for Networking. (keep it in background or executorthread)
A clsss for Repository. (It will be used to fetch the data from the Networking class). When you instantiate the Networking.class in Repository.class use a Singleton Pattern so that only one instance of Networking.class is used across the whole app which will let you to use one Networking.class to fetch all the data you need without instantiating Networking.class again.
As #Zakaria suggested, use the Android View model pattern
A One ViewModel class will be enough to use the Repository.class in it to receive data from the Networking class and share the data (Observe data) in your fragments and show your required data to user.
That's it, it will solve you problem.

First steps in Android architecture - please help me avoid a big mistake

I'm a relatively experienced .NET/iOS developer taking first steps in Android development - to help me avoid going down the wrong path I'd be grateful for some guidance:
Essentially, I have an app that displays locations on a map/list. As the user scrolls around the map, the locations are fetched from a JSON web service. A location can be tapped, at which point another JSON web service is called to retrieve live information for that location. The live info is then displayed.
So, having read the various 'getting started' Android docs, I would imagine I need:
An Activity to display the main map view of the locations
A second Activity to display the list view? These seems odd since I get the impression that each Activity has to be an entire screen of the app. I'd like to persist the other UI elements. (e.g. button to switch views, button for settings etc) Is this possible?
A Service (or IntentService?) to retrieve the locations from the web. How should it let the Activity and ContentProvider know when new locations have been retrieved - via Broadcasts or should they bind to it?
A ContentProvider, to cache and persist my locations. Perhaps the content provider should broadcast to the activities when new data is available to display?
Your help would be very much appreciated, since I feel a little lost!
Carlos
PS: I'll be developing with Mono for Android, unless enough people advise against
An Activity to display the main map view of the locations
Yes
A second Activity to display the list view? These seems odd since I
get the impression that each Activity has to be an entire screen of
the app. I'd like to persist the other UI elements. (e.g. button to
switch views, button for settings etc) Is this possible?
Not necessarily so. Take a look at the Fragments API. It allows you to switch only parts of your UI. It was introduced in Android 3.0, but there exists an official backport of it, so that you can also use it in previous Android versions.
With it, you can put your buttons into the activity, the map in one fragment and the list in another, and then just switch the map with list while retaining the buttons.
A Service (or IntentService?) to retrieve the locations from the web.
How should it let the Activity and ContentProvider know when new
locations have been retrieved - via Broadcasts or should they bind to
it?
I would strongly advice against this. You should use a service if you have long-lasting downloads in the background, like downloading a file or something. Short term JSON requests can and should be handled in the UI process. Use AsyncTask or an Executor for that. There has been advice by Google to put almost all of your requests into a service, but believe me, it's bull.
A ContentProvider, to cache and persist my locations. Perhaps the
content provider should broadcast to the activities when new data is
available to display?
Not required. You only really need a ContentProvider if you plan to make your content accessible to other Applications or the System. For HTTP caching, you can directly access the database/filesystem, or better yet, use the Apache HTTP Client Cache. Works well if you use the already embedded Apache HTTP Client, which you should.
Points 1 and 2 : You could use Fragments to update part of the screen, Activity will act as a container for multiple fragments ( use compatibility library for back porting fragments to API level 10 or less
You should use AsyncTask instead of a service to get the locations from a remote web service
AsyncTask has a callback onPostExecute(..) which will be called on completion of remote fetch, this can be used to update List, Maps or Fragments
1 . You can use MapActivity for map view;
2 . use Activity and place listView to include button in a single view instead of ListActiviy
3 .please follow the link for location updator tutorial
http://www.vogella.de/articles/AndroidLocationAPI/article.html
4 . use map overlay technique for your message display
please make comments if u want any suggestions further after u go through it

Pausing and notifying particular threads in a Java Webservice

I'm writing a Java webservice with CXF. I have the following problem: A client calls a method from the webservice. The webservice has to do two things in parallel and starts two threads. One of the threads needs some additional information from the client. It is not possible to add this information when calling the webservice method, because it is dependent from the calculation done in the webservice. I cannot redesign the webservice becuase it is part of a course assignement and the assignements states that I have to do it this way. I want to pause the thread and notify it when the client delivers the additional information. Unfortunately it is not possible in Java to notify a particular thread. I can't find any other way to solve my problem.
Has anybody a suggestion?
I've edited my answer after thinking about this some more.
You have a fairly complex architecture and if your client requires information from the server in order to complete the request then I think you need to publish one or more 'helper' methods.
For example, you could publish (without all the Web Service annotation):
MyData validateMyData(MyData data);
boolean processMyData(MyData data);
The client would then call validateMyData() as many times as it liked, until it knew it had complete information. The server can modify (through calculation, database look-up, or whatever) the variables in MyData in order to help complete the information and pass it back to the client (for updating the UI, if there is one).
Once the information is complete the client can then call processMyData() to process the complete request.
This has the advantage that the server methods can be implemented without the need for background threads as they should be able to do their thing using the request-thread supplied by the server environment.
The only caveat to this is if MyData can get very large and you don't want to keep passing it back and forth between client and server. In that case you would need to come up with a smaller class that just contains the changes the server wants to make to MyData and exclude data that doesn't need correcting.
IMO it's pretty odd for a web service request to effectively be incomplete. Why can't the request pass all the information in one go? I would try to redesign your service like that, and make it fail if you don't pass in all the information required to process the request.
EDIT: Okay, if you really have to do this, I wouldn't actually start a new thread when you receive the first request. I would store the information from the first request (whether in a database or just in memory if this is just a dummy one) and then when the second request comes in, launch the thread.

Categories