Read data from server in a better way in Android [closed] - android

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I need to make http calls at every step of my app to get the response(in JSON) from server and display in list, grid views. Is there any better way to achieve this? Is this really the best way : http://smartmobsolution.blogspot.in/2014/02/the-best-way-toaccess-data-from-web-in.html ? Any third party libraries available to make the tasks simpler and faster like Connecting to web, Synchronizing with main thread, handling config changes etc?

Judging the example on that link, it's getting a JSON array or something on those lines, from the url, so you can use the Volley library to get the JSON from the url, and using a JsonObjectRequest you will get a JSONObject directly without any further parsing.
A sample request (you'll still need to add it to a queue and run the queue), would be something like this:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
url, null,
new Response.Listener < JSONObject > () {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});

Generly we use HTTP to get data from server.and time taken by request is depends on the data quantity. but there are many libraries also to get fast response data from server.currently i just came across with VOLLEY. this library is 4-5 time faster then HTTP.so i recomment you to go with this. Well,below the the two best refrences to use this lib:
1). volley By Javageeks
2).Androidhove.info

It depends what you want to do. Using JSON is good. XML may be better in some cases.
It also depends which system you are using on the Webserver. OKHttp for example support spdy which let you save some bandwidth and increase the request speed.
For parsing you may want to use JSON for simple stuff. You can also check SOAP which uses XML.
Using Volley is not recommend because it's slow and it does not support multipartentity pretty well.

Related

Android: What is the best HTTP library for files?

Hy guys!
I am working on an android project(java) with another guy working on the server-side(php). In my application I need to call POST and GET methods in order to upload files to server, download files, send Strings, byte[] array etc.
My question is: What is the best library to use in my case?(I think my files will not exceed 3mb)
I am new in android so I tried so far:
1.Android Asynchronous Http Client(com.loopj.android:android-async-http:x.x.x)
-we gave up to this because it is not from a "trusted" source
2.AsyncTask+HttpClient+HttpPost
-we gave up to this too
3.Volley library
-best so far(for strings, image request), but it needs additional libraries to send images to server(org.apache.httpcomponents:httpmime:4.5)
-I followed so examples from here but I got exceptions, error, libraries error(duplicates) and never managed to solve one without other showing up.
-so I gave up on this too
My question posted for volley library here
4. Now I am thinking about using Retrofit, but dont know it fits my needs:
-send strings and all types of primitive data
-send image/images to server(together with an Api key)
-download image/images from server
Tell me if I am wrong somewhere or if I missed something working with the libraries specified above. I managed to send simple data with all of these, but I didnt managed to send Files(excepting loopj library).
Do you think should I go back to Volley, or starting reading about Retrofit? Volley seems to be the most flexible one, but not for uploading files.
Any reference or advice is welcome! Thanks in advance!
Update:
I found a possible solution for my problem:
-I convert my file/image to a byte array and encode it to a base64 string
-I send the string to server as basic StringRequest with HashMap<String,String>(Using Volley library from Google developers)
-The server decode the string a save the file
I think a very good fit for you would be AndroidAsync.
You can find more about it on their GitHub repository here: https://github.com/koush/AndroidAsync
As an example for you on how to upload files to server:
AsyncHttpPost post = new AsyncHttpPost("http://myservercom/postform.html");
MultipartFormDataBody body = new MultipartFormDataBody();
body.addFilePart("my-file", new File("/path/to/file.txt");
body.addStringPart("foo", "bar");
post.setBody(body);
AsyncHttpClient.getDefaultInstance().execute(post, new StringCallback() {
#Override
public void onCompleted(Exception e, AsyncHttpResponse source, String result) {
if (e != null) {
ex.printStackTrace();
return;
}
System.out.println("Server says: " + result);
}
});
There is also NanoHTTPD which you can find here: https://github.com/NanoHttpd/nanohttpd
I hope this will help you.
You should try HttpURLConnection its really easy to send data to a server.
https://developer.android.com/training/basics/network-ops/connecting.html

How to invalidate/force update of cache route at next request with Retrofit and OKHttp?

I'm using Retrofit with OKHttp client for caching responses from a JSON API.
This works nicely.
However, if I take an action on the device which causes the data to update on the server I need a way to 'invalidate' a particular route in order to ensure that next time a request is made for this data, it is fetched from the server again rather than the now outdated cached version.
Currently, I've worked around this by explicitly calling the new route with a "no-cache" flag in the Cache-Control header of the request, but this forces me to download the new data before it is needed, potentially multiple times if multiple actions are taken, just to keep the cache up to date.
Is there a way I can mark a route / method in my retrofit/OKhttp client as cache expired, requiring a mandatory update over the network the next time it's requested?
With retrofit2 and OkHttp3 you can force a new response by adding a Cache-Control header to your API method definition parameters:
#GET("ws/something")
Something getSomething(#Header("Cache-Control") String cacheControl);
and then when calling you either supply null for a (maybe-)cached version or "no-cache" for a live version:
myApi.getSomething(forceRefresh ? "no-cache" : null);
This is now possible in OkHttp by using the Cache.urls() function. As the documentation says:
The iterator supports Iterator.remove(). Removing a URL from the
iterator evicts the corresponding response from the cache. Use this to
evict selected responses.
This was merged into master late December 2014 and seems to be part of these tags (releases): parent-2.4.0-RC1 parent-2.4.0 parent-2.3.0 parent-2.2.0
There isn't an API for this, but there should be one. Please open an OkHttp issue to report this.
It'll probably take a while for us to implement because we'll need to figure out what the best API for this is. Invalidating a single URL is straightforward. Invalidating a range of URLs (say square.com/cash/*) is more difficult because OkHttp's cache is currently organized by URL checksums. There's also ugly edge cases like what happens if the invalidated URL is currently being written to the cache.
To quote the official code sample using urls():
val urlIterator = cache.urls()
while (urlIterator.hasNext()) {
if (urlIterator.next().startsWith("https://www.google.com/")) {
urlIterator.remove()
}
}

Using Sync Adapters+ Volley/RoboSpice for Syncronous processing of Network Requests

My application needs to periodically request the server for new data. I have researched regarding this and many suggested to use sync adapter for syncing with the server, however my requirement changed and I need to do the following process. Is it still advisable to use sync adapters or can I use any other library to efficiently make the following Http request sequence.
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
ZipFile imageZipFile;
/*this is a http post request and the size the zipfile is around 1Mb*/
ZipFile resultFile=makeHttpPostRequest(String URL, String payload);
SomeObject result= processZipFile(resultZipFile);
saveData(result);
for(String url:result.getUrls()){
/* this is a HttpGet request which returns a zip file that
contains 8 images , total size of zip would be around 200kb*/
imageZipFile= makeHttpGetRequest(url);
saveImageZipToDisk(imageZipFile)
}
}
As you can see I am making a Http Post request to get some data that contains the image URL's and use those URL's to make a new HttpGet request. I would need both the result from the POST and also the images for my app to run.
Is this a valid way to use sync adapters or is this totally unacceptable? or Can I use Volley/ Robo spice to spawn the image requests to multiple threads? Sorry I am being novice, but this is a scenario I have been trying to solve.
Update:
So after reviewing the pros and cons of Volley and Robospice, I am using volley as I could customize the code and have more control over the caching mechanism.
All alternatives should be working.
With async adapters, you will get :
async background processing in a native android process
might be more lightweight than the app process depending on your design
but the communication between the app and the async adapter will involve IPC which means bundling/unbundling stuff
With Volley, you will get :
async background processing in the same process as your app, inside Volley threads
communication between your requests and your app will be a fully double way OO channel
With RoboSpice, you will get :
what volley provides, but requests will be executed inside an Android service
possible easier setup of caching
more alternatives for networking (spring android, google http client, retrofit) etc.

Right approach for simple Android app [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I've been studying a lot about Android development recently and to really get the feeling of it, I want to start building a simple application that would get me going. Unfortunately, I think the more I read, the more confused I get.
I want to build an app that scans and reads a bar code, queries a RESTful web service with the EAN read from the bar code and outputs the name of the product.
Now, the scanning part was easy, as I used the zxing library as an intent service. Then, I played a lot with a framework called Volley which is supposed to handle the network communication with the web service and parsing the JSON result. Unfortunately, I wasn't able to integrate Volley with my app, but maybe this handy tool is more than I actually need.
What would be the right approach to achieve the above goal? Do I need a content provider? Do I need a service? How would these relate to each other?
I haven't worked with Volley myself, so I can't give you an answer if it's too advanced for what you want to achieve. In general when it comes to HTTP communication with a server I prefer to use AndroidAsyncHttpClient:
"An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries. All requests are made outside of your app’s main UI thread, but any callback logic will be executed on the same thread as the callback was created using Android’s Handler message passing."
Example relevant to what you want to do:
public class YourActivity extends Activity {
private void handleScannedBardcode(String barcode) {
// you need to make the request match the REST API you are using
RequestParams params = new RequestParams();
params.put("A_KEY_TO_IDENTIFY_THE_PARAMETER", barcode);
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://www.yourserver.com", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
// you need to add parsing of JSON data to match the response
JSONObject jo = new JSONObject(response);
String productName = jo.getString("productname");
updateProductView(productName);
}
});
}
private void updateProductView(String productName) {
// you need to use a view id that corresponds to a textview in your layout xml
TextView tv = (TextView)findViewById(R.id.productName);
tv.setText(productName);
}
}
Depending on how complex the JSON response is you can either opt for GSON or Jackson for parsing of large amounts of JSON or plain JSONObject
I use this library to handle the communication with my API: https://github.com/koush/ion
It's easy to use, has samples and code examples.
Go with simple solution first:
use HttpURLConnection to connect with web service,
then use either InputStreamReader or BufferedInputStream to read the input stream from the connection.
Create a JSON model class similar to the one you get from your web service.
Use Google GSON library to parse the response into a JSONResponse and then use the data.
I'm sure you'll be able to find enough help on SO regarding these individual points to get you started.

PHP to android using HTTPpost [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
Is there a way to send the selected data from my website to an android application? I want to use the data selected to use on conditions in android.Thanks in advance.
If you use WebView to load the webpage, you can invoke a native-method by using the JavaScriptInterface.
For example:
Bind the JavascriptInterface to your WebView in Android:
webView.addJavascriptInterface(new JavaScriptInterface(), "Android");
in HTML:
<button onclick="appTest('test');return false;">test-button</button>
in Javascript:
function appTest(args) {
if (typeof Android != "undefined"){
if (Android.appTest!= "undefined") {
Android.appTest(args);
}
}
}
and finally in Android:
class JavaScriptInterface {
public void appTest(String s) {
//do something
}
}
EDIT:
Sorry, didn't see HTTPpost in the header
Nope , It is not possible to send data using httppost from server to android.
Approach 1:
For this kind of data transmission you need to implement socket programming both the side.
Like : XMPP Server(Openfire);
Approac 2:
1) Implement push notification at device side.
2) Make one webservice at server side which will return response(whatever you want to send to mobile side).
3) Fire pushnotification from your server to google server and google server will send that push to android device.
4) When android receive push it will call the webservice of your server and will get the date that you want to send.
We are using Second approach in our application IjoomerAdvance.
Refer this link for Google push implementation between android and php
http://androidexample.com/Android_Push_Notifications_using_Google_Cloud_Messaging_GCM/index.php?view=article_discription&aid=119&aaid=139

Categories

Resources