Rest Service Access inside fragment class - android

In my application i need to display the data in list view from rest service . I have gone through many samples but am not satisfied with that so can somebody help me ? Need sample or explanation . Thanks in advance!

In android you can use libraries to consuming REST
Volley
Retrofit
Your question is very general. Try one from above.
Sample use Volley:
in gradle: compile 'com.mcxiaoke.volley:library:1.0.19'
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);

you can call api in fragments.
if you are new to android,
1)first fetch the data from api with a asynctask(check android json parsing with url in learn2crack).
2)after step 1 you have your data to populate to your list,if you want to make a custom list the same site also gives an example for android custom list(learn2crack)
you can call json on asynctask class.
call the async task in onCrateView of your fragment

Related

Android JSON: Unable to get response

I am trying to fetch a JSON response from OpenWeatherAPI to incorporate the current weather in my app. I have used volley to make a simple request to fetch the JSON response, but every time, I do not get the response. Instead, it always triggers the onErrorResponse method. What do I change to make this work?
I have added the uses Internet Permission in my manifest.
I have tried the solution to fetch JSON responses from many sources including the Official Android Developers Documentation, Other Questions from Stack Overflow, etc, but all of them failed.
I first used JSONObjectRequest instead of StringRequest, but even that did not provide me the results I required.
/*
Create a request queue to fetch the JSONObject response.
*/
RequestQueue queue = Volley.newRequestQueue(Objects.requireNonNull(getContext()));
/*
JSON Object request.
*/
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getContext(), response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "No JSON", Toast.LENGTH_SHORT).show();
}
});
queue.add(request);
I expect the Toast to show the response, but The Toast shows "No JSON".
Add "https://" before your URL. You will get a response on your browser, but will not in Android.

Android wait for volley to finish and update UI later

I am using volley package to retrieve data from a website(JSON).
Here is my method
private void getEarthquakeList(){
// ...
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
//Earthquake Feeder
String url ="https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_month.geojson";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response is: ",response);
//Parsing Json
parseJson(response);
final ListView earthquakeListView = (ListView)findViewById(R.id.list);
//Sort the array according to magnitude
earthquakeArrayList.sort((a, b) -> Double.compare(b.getTime(), a.getTime()));
mAdapter = new EarthquakeAdapter(getApplicationContext(), earthquakeArrayList);
earthquakeListView.setAdapter(mAdapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error",error.getMessage());
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
The problem is that right now I am updating the UI inside this method after it returns the response.
These are the lines
//Sort the array according to a date
earthquakeArrayList.sort((a, b) -> Double.compare(b.getTime(), a.getTime()));
mAdapter = new EarthquakeAdapter(getApplicationContext(), earthquakeArrayList);
earthquakeListView.setAdapter(mAdapter);
While I am running in the MainActivity there is no issue, the user opens the app and gets the list of earthquakes.
The issues start when I want to switch to service where I monitor every couple of minutes or when the website content is changing.
So I want my method without updating the UI in it.
The problem is that If I am not updating the UI inside onResponse, the UI thread continues and results in an empty array.
So this array stay empty earthquakeArrayList if I am not doing it inside
public void onResponse(String response)
Ideas how to separate the two, in one hand running the method and fetching the data and on the other hand the main thread will be able to access the data and not finish executing.
Thanks
EG
The recommended solution right now is to use LiveData. LiveData works on the Observer Pattern, so you can have any number of observers to the updated data both in the Service and the Activity but they need to be under the same context. These are a bit advanced topics but a good way to decouple your UI with the data layer. You can go through these two links
Google IO 2018 session on Livedata
Medium Article on LiveData

How to smoothly handle a json array with 200k rows using volly

I have url that has a json Array which contains a large amount of data.
I call the url with volly jsonArrayRequest like this
public void makeJsonArrayReq(){
showProgressDialog();
JsonArrayRequest req = new JsonArrayRequest(Const.URL_IPD_ADMITED,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("response ================", response.toString());
textView.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error", "Error: " + error.getMessage());
textView.setText("Error Occurs ");
hideProgressDialog();
}
});
AppController.getInstance().addToRequestQueue(req, "array");
}
My devise shows progressDialog for some time after that time it hang out the app then after a few minute it shows the response in the texview but it very lengthy process and it same when internet connection off and extract from volley cache. How can I handle the URL in my apps?
You need to change your api a bit to support pagination. There are several pagination techniques available, you have to choose one that suites your case.
In Android you can save the last fetched pageNumber(if that is what your API returns as page identifier) and your api should accept this variable in request (mostly through query params)
http://43.255.22.123:3000/android/mis/get/ipdAdmitPatMd?pageId=1
And in the next request it should update the pageId to 2.
Since the question is too broad hence providing exact code solution is not possible therefore I have explained the concept.

Android Developer Console How to send a HTTP Request?

I have a little app with a leaderboard and i want to hide players with fake scores. I read about it at https://developers.google.com/games/services/management/api/players/hide#request
The Problem is, that i have no idea from http Requests and that things.
So how do i send a HTTP Request? Is there a Terminal or something in the Developer Console from Google, where i put my command in?
Or what do i need to do, to send an Request like this?
I recommend that you use Volley
Add Volley to your project through Gradle
compile 'com.android.volley:volley:1.0.0'
Add the android.permission.INTERNET permission to your app's manifest.
The code is taken from 1
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com"; //set your web call here
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//handle success
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//handle error
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);

Volley - more than one request in the same Activity android

I want to send two different requests and handle two different responses in one Activity using Volley library.
My activity implements onResponseListener, so i have only one onResponse method and both responses are handled here. As they are completely same in structure i cant tell which is which.
How can i tell from which request i have received the response so i can handle them differently? Is there a way to "tag" a request or something like that?
I could set some kind of check variable, e.g. boolean firstRequestIsSent when i send the request, and then check it in the onResponse method, but its a pretty ugly solution.
Many thanks
Instead of implementing onResponse as part of the class, you can instantiate a new Response.Listener with the request. This way you will have a separate listener for each request.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener() {
#Override
public void onResponse(String response) {
// individual response here
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error here
}
});

Categories

Resources