I am making request to web service and have to do this extending AsyncTask for every methods. So how many methods i have in webservice that many classes i need to create in this way.
I found this topic how to make callback:
Making Callback
But there are shown one class callback, but what if i want that there would lots of callbacks in one class ?
The AsyncTask class has generic parameters for data that is passed between its methods. You can use a custom class to pass the data from one method to other.
Web-service access is usually done in 3 steps :
Retrieving the content (XML/JSON etc.)
Parsing the content
Reading the content.
You can pass the AsyncTask the URL to be fetched (As shown there)
In background you can retrieve content and parse it. The reading of content can be done in different code blocks which run on UI thread depending on the result parameter.
Related
Currently I have an app which has code in its main activity that reads data from an xbee. My problem is that I want to relay this data to 4 different threads in 4 different classes throughout my project. I looked into bundling it, but that seems like a one time data transfer, not a stream of it.
One idea I had was to write the data to a string called messages and then have a getMessages() function, but I ran into a problem calling a static method from a non-static class or vise versa.
Have you considered using SharedPreferences or extending Application? SharedPreferences will let you store basic types (String, int, boolean, etc) in persistent storage. Application can be extending to store variables / methods that can be accessed anywhere in your program. For example, MyApplication app = (MyApplication)getApplicationContext();
Are you looking to modify this stream of data in each of your threads, or simply read a value and modify data separately? You may want to setup some boolean flags to ensure you aren't accessing / modifying data that isn't safe to perform those operations on. Hope that helps! Let me know if I can provide a code example for clarity.
one way of doing it to simply make your main activity write into android.database.sqlite and others will simply read from it
since not sure how your code layout is I just refer you the documetation page :
http://developer.android.com/reference/android/database/sqlite/package-summary.html
You can create one handler for each of your threads and then post messages on all the handlers. Below is the link which creates an Handler and post messages from the handler reference:-
using a Looper in a Service is the same as using a separate thread?
You can implement observer pattern to solve this.Make the four classes as observers and the activity as subject.
Expose a api like onDataChanged(byte[] data) which will be called whenever your activity has some new data.
To learn more about observe pattern refer-https://en.wikipedia.org/wiki/Observer_pattern
You can also have a look at classic producer consumer problem if you want synchronization https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem
I've been following this tutorial.Now, I have to fetch and parse some JSON from a web URL. For that I am thinking to use an AsyncTask for now (might try something else as well. Such as a separate thread. advice..?)
But am not able to decide and approach things for now as to how the AsyncTask can inform back to the controller about the state of execution (I thought of using a handler but that'll defeat the purpose of already used controller acting as a Observer for button click(s)..starting the AsyncTask as well) and where can I put the AsyncTask. Certainly not in the controller itself. As the controller has the sole responsibility of giving out commands/judging + it'll be a cluster f* :D
Any help in form of sample code clearly showing me how/what to accomplish is appreciated. Thanks
You can apply a simplified Observer pattern to your AsyncTask also. Here, your Controller becomes the Observer and AsyncTask will be the notifier. In your onPostExeccute of the AsyncTask, you notify your observers with the result. In your Controller, implement the update method and take action on the result.
Since usually AsyncTask needs to notify only one object, I follow the simpler Listener interface. Define a simple interface with a method called handleResult which takes appropriate data structure. My activity implements this interface (but in your case, it would be the controller) and adds code to handle the result. My AsyncTask stores this listener as a field and on completion of the task, calls the handleResult method.
But as you can see, it is very similar.
In my app, i have lots of GET,POST, PUT requests. Right now, i have a singleton class that holds my downloaded data and has many inner classes that extend AsyncTask.
In my singleton class, i have also a few interfaces like this:
/**
* Handlers for notifying listeners when data is downloaded
*
*/
public interface OnQuestionsLoadedListener {
public void onDataLoadComplete();
public void onDataLoadingError();
}
Is there something wrong with this pattern (many inner classes that extend AsyncTask)?
Could it be done more efficiently with maybe just 1 inner class for every HTTP call (1 for GET, 1 for POST, ...)? If so, how to decide what to do after e.g. GET request?
As a whole, you should get away from AsyncTasks while preforming network requests.
Your AsyncTasks are linked to your Activity. That means, if your Activity stops, your AsyncTask stops.
This isn't the biggest problem when fetching data to show in that Activity, since you won't care that the fetching has stopped. But when you want to send some saved data to the server, and your user pressed 'back' or something like that before everything is sent, the data could be lost and not send.
What you want to have instead, is a Service which will keep running regardless of what happens to your Activities.
I'd advise you to take a look into RoboSpice. Even if you decide not to use it, reading what it does and why it does will give you a good insight on the pretty long list of reasons not to use AsyncTasks for network requests and why better to use Services.
If you use this, the rest of your question about efficiently network requesting is obsolete too, since they'll handle it for you the best way possible.
Nothing wrong with many async classes.
What ido is have a network layer,a service class. Send an intent to the service class with a resultreceiver object as part of intent. then in the service make http request in async task and send back the the result through result receiver object.
A good design is to abstract the ui (activity or fragment) from network access.
In a recently developed app I followed a similar scheme but in addition implemented a WebRequest class doing the actual GET, POST, PUT etc.
What I now have is a "Connector" class which has a whole lot of AsyncTask subclasses within.
In my implementation, however, I made them accept a Callback object to which each of those subclasses passes the Http result.
I think this is a valid if perhaps not ideal way.
What I imagine could be an improvement would be if I had just one subclass of Asynctask to which I would pass the request body (which is now built within those different tasks), the request url and method as well as the callback (which is, in my opinion a rather nice way to get the results).
I have a Network Client class that is receiving a large binary block and parsing it into a usable Java object. The Network Client is on a separate thread from the app's View. What is the best way to make this object available to the View? I've come up with the following solutions, but I feel like none of them are the correct one:
Create the object in the Network Client and let the View access it directly
I would send a small message in a Handler telling the View that the data has been updated
Con: requires that I synchronize the object between the threads to ensure that the Network Client doesn't replace the object while the View is accessing it
Serialize (Parcel?) the object in the Network Client and send it through a Handler to the View
Pro: there are no questions of ownership of the data
Con: would probably be a huge performance drain on the app
Create a reference to the object and pass that to the View
I come from a C++ background, and I'm not sure if this is even possible in Java. I C++, I could just send the View a pointer to the object and let it take care of it. That seems like something Java wouldn't let me do. Is this feasible?
Are any of these solutions advisable, or should I approach the problem in a completely different way?
If you don't want to keep downloading when the activity is in the background, then use non-blocking IO, not threads.
If you do want to keep downloading when the activity is in the background, you probably want to use a service. You can make the object Parcelable or so; I think the underlying service implementation passes pointers around if your activity and service are within the same process (I think they are by default, but ICBW).
If the object is really big and you don't feel comfortable returning it with a get method, maybe you could put its contents into an SQLite database and optionally expose it as a ContentProvider. You could also send an Intent and either cause the View to then go and grab the payload or attach it to the Intent.
Look at the application class subclassing this class and referencing this within your manifest will enable you to store the reference to the service/download controller at a central position that will be available in every activity of your app. This enables you to keep the data in memory and reduce the need of recreating the big object if you need it in more places then just one activity.
For the download you can use a local service that communicates with your activity through a binder object. Keep in mind that a service is not a thread. If you want have the download running in the background you need to create a thread in the oncreate method of your service.
Also keep in mind that it is good practice to have an annotation show the user that a service is doing something and let him access the service and cancel it or view it status.
I am interested in creating a web app that uses JSP, Servlets and XML.
At the moment I have the following:
JSP - Form input.
Servlet - Retrieving Form data and sending that data to a java object.
Java object (1) - Converts data into XML file....instantiates java object (2).
Java object (2) - Sends that file to a database.
On the returning side the database will send back another XML file that I will then process using XSLT to display back to the user.
Can I place that XSLT code in the orignial Servlets doPost() method? So my doPost()` method would:
Retrieve user inputted data from the form on my JSP page.
Instantiate a java object to convert that data to XML, in-turn that object will instantiates another object to send the XML file to a database.
Converts the resulting XML file sent from the database and displays it for the user.
Can one servlet doPost() method handle all of this? If not, how would I set up my application and classes to handle this work flow?
Thank you in advance
I wouldn't load the XSLT in POST, because every method has to do it.
Read that XSTL in the init method, precompile and cache it. Just make sure that you keep it thread safe.
Once you have the XSLT, you've got to apply it to every XML response, so those steps do belong in POST.
All your doPost() method has to do is generate a suitable servlet response (some form of content, and a suitable HTTP response structure). So it can do anything you want (including the above).
However it sounds like your rendering requirement is distinct from your form submission and storage requirement. So I would make your doPost() method delegate to a suitable method for rendering the output. That way you can generate output from stored data separately from submitting data to the database.
Well, this is not really specific to servlets, but more to Java/OOP (object oriented programming) in general. You can in fact do everything in a single method, even in a main() method. But hundreds or more of lines in a single method isn't really readable, maintainable, reuseable nor testable in long terms. Right now, you're probably just starting with Java and you probably don't need to do anything else than this, but if you ever need to duplicate (almost) the same lines of code, then it's time to refactor. Extract the variables from the duplicate code lines and wrap those lines in a new method which takes those variables as arguments and does a simple one-step task.
In general, you'd like to already split the big task in separate subtasks beforehand, using separate and reuseable classes and methods. In your case, you can for example have a single DAO class for all the DB interaction task, a generic XML helper class to convert Javabeans to XML and vice versa with help of XSL and (maybe) a domain object to manage the input/output processing (conversion/validation/errorhandling/response) and executing actions. Write down in paper how the big picture is to be accomplished in small single tasks. Each task can be often as good done by a single method. Group the methods with the same responsibilities and/or the same shared data in the same class.
To go a step further, for several tasks there may be 3rd party tools available which eases the task. I can think of for example XMLBeans and/or XStream to do the Javabean <--> XML conversion. That would already save a lot of boilerplate code and likely also the XSL step.
That said, duffymo's suggestion to load the XSL only once is a very good one. You don't need to re-execute exactly the same task which isn't dependent on request parameters at all again and again on every request, that's only inefficient.