How can I update my data into my activity? - java

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.

Related

How to fetch data from SQLite in the background with callback without Room?

I want to know how to fetch data from the local SQLite database in the background with a callback in the main thread. Say, the callback should be in a Fragment. And I want to avoid using the Room library. Currently I fetch the data in the UI thread using SQLiteHelper.
I have considered various options and understood that there is no silver bullet. For example:
I could have used AsyncTask, but it should be subclassed and in case the activity is destroyed before the task is finished the data is passed to the destroyed referenced activity. As a result - a memory leak. Although, I restrict the screen rotation that lowers the chances of the Activity destruction, should I keep neglecting using AsynkTask?
Another option is IntentService. In this way I can fetch data from SQLite in the background and use EventBus for a callback. However, seems like it is an overkill for such a task. The plus - easy implementation.
CursorLoader with ContentProvider is the third option. I believe this is what I need. However, I believe the code could be verbose. I havent used these classes and after reading miles of texts, still dont know how to implement them.
What option should I choose? Please, provide me with a guided code in case you have one.
Please correct me, if I am wrong in some statements.

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 to handle prohibition of network-on-thread and need to update list adapter on UI thread?

Developing an Android application which uses CouchBase as its datastore. All interaction with Couch is via HTTP so it cannot be done on UI thread. This is ordinarily something we can work around pretty reasonably, but I'm hitting up against a rock and a hard place with this problem:
I'm trying to develop an encapsulated/ reusable CouchListAdapter. The concept being, fetch data from Couch in pages and then cache it. Say page size is 20, so when initialized, fetch first 20, then if asked for 21, go get 21 - 40.
Because of the prohibition of network on thread, my CouchViewLoader which has methods JSONObject getItemAt(int i) and int getCount(), when asked for data it does not have, has to kick off an asynchronous thread to get the data, then send out a broadcast handled by the enclosing activity which then rebinds/ notifies that data has changed.
I almost got it working but am stuck now where I get:
java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread.
How do I reconcile the inability to hit Couch on the UI thread and the need to only update my adapter from the UI thread??
Surely other people have solved this problem?
(Keep in mind, this is all designed around the idea that a given view may return more results than we can fit in memory or display on the screen.)
Have you considered an AsyncTask?
You can do the hard work in doInBackground(...).
You can then update your ListAdapter in the onPostExecute(...) method.
You might want to consider using a content provider with loaders. Basically all information you need is located at those links.
For a general view:
Content providers provide data.
Loaders fetch data from content providers in background threads.
Once loaders have done the background jobs, they notify the UI (such as CursorAdapter, CursorTreeAdapter…) to update.
Your jobs are:
Have your content provider query data with the server. You can do network tasks in a content provider.
Decorate the UI with the data that loaders fetch.
About content providers, although they say that You don't need to develop your own provider if you don't intend to share your data with other applications. — but as they highly recommend using loaders (which they do support older APIs with support library), and as my experiences, content providers will save your time a lot. I would say: just go with content provider :-)

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

Categories