One connection shared between two fragments - java

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.

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.

Proper Usage of Android Fragment

I have been reading up on the Android API and it seems like Fragments are meant to sort of modularize an Activity. So if an Activity has a ListView and DetailView then it should be split into two separate fragments and have the Activity act as the master controller.
In my previous project that I worked on we were using Fragments kind of like children of the Activity.
For example: Let's say there is a AutomobileActivity that is designed to save automobile input data to the cloud.
We have fragments like:
SedanFragment
TruckFragment
SportsUtilityFragment
These fragments take up the entire view of the Activity and only one is displayed at a time. While these fragments use methods in the Activity to call common webservices like saving automobile information, getting car information. They also do different things like the Truck may have an additional entry to set the "Bed Size" and SportsUtilityFragment may have "Tow Limit" etc.
So in a way we are leveraging a lot of re-use and modularizing, but it's not exactly what the Android API is detailing. Is this a bad way to use Fragments?
This is a very objective question and this will have a lot of different answers. In my opinion what you are doing is correct. The reason behind this is that they have a set of common webservices. If we go by the mvc approach they can all have the same controller(for calling webservices), a model class(Superclass- vehicle) with separate models which inherit from this vehicle model class. By doing this you can have an additional entry parameter which will be present in these models. Your view, the fragments can easily call the instance of these models. If you modularize in this manner, you will be making life very easy for yourselves.

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

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!

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.

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

Categories