I'm getting some data from the Trello API over HTTP. So an example of the response would be:
'[{"name":"asd","desc":"yes"},{"name":"xyz","desc":"no"}]'
I'm using the volley library for making the request and getting the response. Is there a way for me to get the response in the form of json objects directly instead of in a string?
If not how should I proceed?
Thanks!
You can use JSONArray(). And then you can use getString() so you can use all string function.
Example code:
JSONArray jsonArray = new JSONArray(responseString);
int i = 0;
while (i <jsonArray.length()) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
String name = jsonObj.getString("name");
String description = jsonObj.getString("desc");
//TODO create your Java object and store these strings into it.
i++;
}
use volley can solve easily.
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,new Response.Listener<JSONArray>(){
#Override
public void onResponse(JSONArray response) {
//the response is JsonArray
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
}
});
Related
i am using gofile link but when i call it i get this error
E/Volley: [4463] NetworkUtility.shouldRetryException: Unexpected response code 404 for https://api.gofile.io/getFolder?folderId=XuxRGg
i also attach the code part
public class GoFile {
public interface goFileCallback {
void onSuccess(String result);
void onError(VolleyError error);
}
public static void getStreamLink(Context context, String url, final goFileCallback callback) {
String[] parts = url.split("/");
String id = parts[4];
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(com.android.volley.Request.Method.GET, "https://api.gofile.io/getFolder?folderId="+id, response -> {
JsonObject jsonObject = new Gson().fromJson(response, JsonObject.class);
JsonObject data = jsonObject.get("data").getAsJsonObject();
JsonObject contents = data.get("contents").getAsJsonObject();
for (String keyStr : contents.keySet()) {
JsonObject md5 = contents.get(keyStr).getAsJsonObject();
String link = md5.get("link").getAsString();
callback.onSuccess(link);
}
}, error -> callback.onError(error));
queue.add(sr);
}
}
i would be glad if some one help me to solve this
You should double check the link "https://api.gofile.io/getFolder?folderId=XuxRGg". Typing it in chrome also return 404.
say 404_Not Found response code -
check api link and find http_response_code(404)(in php) - probably there isn't response in database
I am trying to fetch all videos of a channel using youtube data api, but my code is giving error and doesn't respond to PAGE token
displayVideos();
}
private void displayVideos ()
{
RequestQueue requestQueue= Volley.newRequestQueue(this);
StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
System.out.println(jsonObject.get("nextPageToken"));
JSONArray jsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
if (jsonObject1.has("id")){
JSONObject jsonVideoId=jsonObject1.getJSONObject("id");
if (jsonVideoId.has("kind")){
if(jsonVideoId.getString("kind").equals("youtube#video")){
JSONObject jsonObjectSnippet = jsonObject1.getJSONObject("snippet");
JSONObject jsonObjectDefault=jsonObjectSnippet.getJSONObject("thumbnails").getJSONObject("medium");
String video_id=jsonVideoId.getString("videoId");
VideoDetails vd=new VideoDetails();
vd.setVideoId(video_id);
vd.setTitle(jsonObjectSnippet.getString("title"));
vd.setDescription(jsonObjectSnippet.getString("description"));
vd.setUrl(jsonObjectDefault.getString("url"));
videoDetailsoArrayList.add(vd);
}
// recyclerView.setAdapter(adapter);
// adapter.notifyDataSetChanged();
}
}
}
}catch (JSONException e) {
e.printStackTrace();
}
the url I am trying to parse is
String url="https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCVMWWQ985A_-SESZUy_SsVQ&maxResults=50&pageToken="+nextPageToken+"&order=date&pageToken=CAUQAA&key=API_KEY";
I have been searchingb to apply nextpage token or page token in android studio but couldnt get specific tutorial. there are many examples but being naive in android studio I cant implement it into my code.
Please note that your URL does contain two instances of the parameter pageToken:
"https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCVMWWQ985A_-SESZUy_SsVQ&maxResults=50&pageToken="+nextPageToken+"&order=date&pageToken=CAUQAA&key=API_KEY".
It should have only one for that to work OK; to be more precise, your URL should contain only this instance: pageToken="+nextPageToken+".
On the other hand, your code above does not show the loop implementing pagination. That is that you haven't shown the piece of code where you actually assign a valid value to the variable nextPageToken.
Therefore I cannot tell if your program will work or not.
The pagination loop would look like this:
// initially no pageToken
nextPageToken = null;
// URL as above, without the parameter pageToken
url = ...
do {
invoke the API on the URL: url + (nextPageToken != null ? "&pageToken=" + nextPageToken : "")
nextPageToken = jsonObject.get("nextPageToken");
} while (nextPageToken != null)
I am new to APIs and finally figured out how to successfully retrieve a request response from a website. The thing is I am completely lost on how I should handle the response. I don't know how to access certain values within the response
here is my API Volley code
RequestQueue requestQueue = Volley.newRequestQueue(this);
String uri = Uri.parse("https://chicken-coop.p.rapidapi.com/games/Fortnite?platform=pc")
.buildUpon()
.build().toString();
StringRequest stringRequest = new StringRequest(
Request.Method.GET, uri, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
displayResults.setText("Response: " + response.substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
displayResults.setText( "" + error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("X-RapidAPI-Key", "5cdb2bbe57mshd9242c8d3177cb3p16f2fbjsnd7c5829eb4ad");
params.put("X-RapidAPI-Host", "chicken-coop.p.rapidapi.com");
return params;
}
};
requestQueue.add(stringRequest);
Here is the response query that I received
"result":{10 items
"title":"Fortnite"
"releaseDate":"Jul 25, 2017"
"description":"Epic Games next project has you building forts and stopping a zombie invasion."
"genre":[...
]6 items
"image":"https://static.metacritic.com/images/products/games/5/c7eb46ceb7da9c72c5a95193e8621faf-98.jpg"
"score":81
"developer":"Epic Games"
"publisher":[...
]1 item
"rating":"T"
"alsoAvailableOn":[6 items
0:
"iPhone/iPad"
1:
"PlayStation 3"
2:
"PlayStation 4"
3:
"Switch"
4:
"Xbox 360"
5:
"Xbox One"
How would I go about finding an explicit value from the response query? I have been searching for how to do this online and there are so many different ways to go about and I have no clue what to do. For example, how would I be able to put the Release Date into its own text box? Most of the examples I see online use JsonObjects when I m using a string response
in your onResponse method you need to parse your result so you can extract any data you want
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("result");
// toaccess to your json data
String title = jsonArray.getString("title");
// your code
} catch (JSONException e) {
e.printStackTrace();
}
}
Why i can't send parameter in url with string contain more than one word in JSON Object Request?
When i trying to send parameter with string "haha" it work, but when i trying to send parameter with string "haha haha" (with space between the words) it calls onErrorResponse function.
Below is my code :
String url = String.format("http://172.xx.x.xx:xxxxx/api/users?name=%s", nama);
JsonObjectRequest objectRequest = new JsonObjectRequest(
Request.Method.GET,
url,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
What the solution so my url can receive string parameter with more than one words inside the string parameter??
Try this
String nama = "haha haha";
String url = "http://172.xx.x.xx:xxxxx/api/users?name="+nama;
you can also use this because when you send request the spacce reloaced by %20
String url = String.format("http://172.xx.x.xx:xxxxx/api/users?name=%s", nama.replace(" ","%20"));
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 4 years ago.
Hello everyone I'm kind of new in this field.
I made a rest request for project and I got this response:
{"success":true,"timestamp":1524649444,"base":"EUR","date":"2018-04-25","rates":{"AED":4.486623,"AFN":85.583411,"ALL":128.283655,"AMD":585.986726,"ANG":2.175126,"AOA":270.568194,"ARS":24.745299,"AUD":1.609775,"AWG":2.1 // and so on.
how can I insert the currency and his value to arraylist?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fixer_request);
System.out.println("-->rest");
String url = "http://data.fixer.io/api/latest?access_key=7e4976fbeb5d633e337487fea31fd7ca";
RequestQueue requestQueue= Volley.newRequestQueue(this);
JsonObjectRequest objectRequest= new JsonObjectRequest(
Request.Method.GET,
url,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("rest Response",response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("rest Response",error.toString());
}
}
);
requestQueue.add(objectRequest);
}
You have to change your JSON response like this:
{"success":true,"timestamp":1524649444,"base":"EUR","date":"2018-04-25","rates":[{"currency_name":"AED","currency_value":"4.486623"},{"currency_name":"AFN","currency_value":"85.583411"},{"currency_name":"ALL","currency_value":"128.283655"},{"currency_name":"AMD","currency_value":"585.986726"}]}
In your JSON there is no array to from which you can add value in array list.
If you can't change your JSON response than you have to pre-declare all type of currency in your array list and than add there currency accordingly.
Use Gson library to convert json object to Java object easily
google-gson
Create a JSONObject:
JSONObject jObject = new JSONObject(result);
To get a specific string
String aJsonString = jObject.getString("STRINGNAME");
To get a specific boolean
boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME");
To get a specific integer
int aJsonInteger = jObject.getInt("INTEGERNAME");
To get a specific long
long aJsonLong = jObject.getBoolean("LONGNAME");
To get a specific double
double aJsonDouble = jObject.getDouble("DOUBLENAME");
To get a specific JSONArray:
JSONArray jArray = jObject.getJSONArray("ARRAYNAME");
To get the items from the array
for (int i=0; i < jArray.length(); i++)
{
try {
JSONObject oneObject = jArray.getJSONObject(i);
// Pulling items from the array
String oneObjectsItem = oneObject.getString("STRINGNAMEinTHEarray");
String oneObjectsItem2 = oneObject.getString("anotherSTRINGNAMEINtheARRAY");
} catch (JSONException e) {
// Oops
}
}
you can from http://www.jsonschema2pojo.org/ to convert json to java class annotation base are clear code
and you can use from library retrofit Gson base are easy
or use :
JSONArray jArray2 = jArray.getJSONArray("PreFactorHotels");
for (int i = 0; i < jArray2.length(); i++) {
hotelPreFactorModels.add(new HotelPreFactorModel(jArray2.getJSONObject(i).getString("HotelNameE"),
Utility.dateShow(jArray2.getJSONObject(i).getString("HotelChekin"))
, Utility.dateShow(jArray2.getJSONObject(i).getString("HotelChekout")),
jArray2.getJSONObject(i).getString("AdlCount"),
jArray2.getJSONObject(i).getString("ChdCount"),jArray2.getJSONObject(i).getString("RoomTitleFa")));
}
USING GSON libray
it requires three steps
String afikJson = "YOUR JSON...";
Gson gson = new Gson();//create Gson object
//and create Type object with arrayList as a type of data
Type afikListType = new TypeToken<ArrayList<Afik>>(){}.getType();
//map your JSON
List<Afik> afikList = gson.fromJson(afikJson, afikListType);