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

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

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.

How can I update my data into my activity?

I have a small problem to display data in my application. Actually for updating my data I wrote all the methods in the onCreate() method. So the problem is one all the data getting only the display will start.
But I need to show some data first after that I will update remaining data in the background.So please tell me where can I write the other methods.
code:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.summary_main);
displyProfile(personalDetailsInfo);
displyConditions();
displayAllergies();
displayWellness();
displayVaccine(vaccineHashMap);
}
First of all, creating an Android app that synchronizes with a Web service is not a simple task. You must take care of a lot of different things to do it properly (and it really depends on the application you are building and the nature of it). Sometimes you can use an AsyncTask to communicate with your webservice as #Roshni has said, but IMHO it's not the best option you have for this task (especially if you rotate your device ;D).
If you want a behaviour of Google+ you must keep in mind that it's using a lot of different components:
It uses a Rest Library (like Volley) to consume an API. There are a lot of examples in the web and it's very intuitive (1, 2, 3). Probably if your application is not very complicated you can use only this component and it will suffice.
It uses a SyncAdapter to synchronize its content with the API. Developers docs says this about this component:
The sync adapter component in your app encapsulates the code for the tasks that transfer data between the device and a server.
It stores its data in a SQL database using a ContentProvider:
Content providers manage access to a structured set of data. They encapsulate the data, and provide mechanisms for defining data security. Content providers are the standard interface that connects data in one process with code running in another process.
It uses a CursorLoader to query in background the data you need in your Activity/Fragment and when certain things happen, you can notify your observer to load more data. (This good tutorial explains how to work with CursorLoader written by Wolfram Rittmeyer).
There are a lot of very good Open Source applications to take a look on how are resolving this kind of issue like SeriesGuide, WordPress for Android, ioSched 2013.
Probably in your case if your data is simple you can use Volley and query the data you need, it will handle all asynchronous fetching for you and notify a corresponding listener, then in your Activity/Fragment you only have to update the related views.

Where is the Server Side in GWT Places & Activities?

If I understand correctly :
an Activity is a User action on widgets
This activity moves the application state in another Place
The url moves along, thanks to anchors (thought modern browsers have an api)
When we share the url, it define a Place, and it's enough to rebuild the State
(As I'm also a javascript guy, this looks much like Backbone's router and other modern JSFrameworks)
But to rebuild the State, we need to fetch some data to the Server. Is there anything in the P&A api to do this ? With RPC, this role is clearly done by GreetingServiceImpl that extends the RemoteServlet. With Backbone, we have the Sync object.
But I never see such code such when I look at A&P tutorials. Where is the Server ? Do we need RPC there ? Does it mix with RequestFactory ?
First, a small note about terminology:
A Place represents where you are in the app. When you look at that screen, it's generally composed of different "blocks", each dedicated to a specific activity, e.g.: a header (let's say with search box and logout link), a navigation menu, the "master" in a master-details view, the "details" in a master-details view. All these can be activities (though not necessarily, things that are never swapped to anything else won't gain anything being activities).
Because activities are by definition displayed on screen, you can interact with them, possibly triggering a move to another place (PlaceController#goTo).
The place is optionally synchronized with the URL (both ways) and generate browser history items; by default using the hash, but you can swap the implementation to use HTML5.
(places are similar to Backbone's router except they're type-checked, activities are a light layer on top with no equivalent in Backbone AFAICT)
Now to answer your question:
GWT is a toolkit, not a framework. That means most building blocks don't force you into using any other building block (places can work without activities, editors can work without widgets, etc.)
Activities start asynchronously, which is where you'd generally get the data from wherever it is. In the spirit of a toolkit, you're free to use whatever fits your needs: GWT-RPC, RequestFactory, RequestBuilder, Errai JAX-RS, Errai Bus, XMLHttpRequest, WebSockets, AppEngine Channels, etc. Some people also post events to their event bus to decouple the activity from how they get their data.
MVP describes the Client-architecture.
M_odel:
The business objects handled by you app.
V_iew:
UI elements, showing a representation of your model.
P_resenter:
A class which handles all userinteractions and modification to your model.
Lets assume you have an application which shows and stores Notes.
You have some Places:
a Place is like an good old HTML page in older days. In MVP it can be described a a set of running Presenter. In our simple application there are two places. Every Place does only have one running Presenter
NotesListPlace -> shows all stored notes
NotesEditPlace -> Creates / Edit a Note
The NotesEditPlace:
There is a View and a Presenter.
The View has an TextArea (for the Note) and a save button.
The presenter has a clickHandler for the save-button (there may be more, but as example it should be enough)
The User select a Note from the NoteList
PlaceChange from NoteListPlace -> NoteEditPlace
The Presenter starts and registers the click-handler at the view. If the button is pressed, the presenter reads the input from the textarea and update the Model (A new Notes-onject)
Now comes the server interaction. You can use every (GWT) transportlayer you want.
The success callback fires a PlaceChange event to the NoteListPlace.
All starts again. The presenter starts, a new server interacction to load the MOdel ( A List of Notes). The view is updated by the presenter...
Update 1
There is no need of a server. The presenter may persist the Model to the localStorage of the browser.
Update 2
You can use every transport mechanism you want. RequestFactory, GWT-RPC. I use RequestBuilder and GWT AutoBeans.

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.

Categories