JSON Object Request GET Method - java

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"));

Related

How to find specific data from a Volley Api string response

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();
}
}

How to make a GET request with parameters to a JSON in Java using Volley?

I'm doing a school project where i need to parse a JSON and make queries to get specific values. The API in question is this one http://data.nba.net/10s/prod/v2/2018/teams.json and I only want the teams of the "standard" array.
For example I want only the teams which are NBA Franchise, I tried the following:
private void loadTeams() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(application);
String franchise = preferences.getString("isnbafranchise", "true");
Uri baseUri = Uri.parse(NBA_REQUEST_URL);
Uri.Builder uriBuilder = baseUri.buildUpon();
uriBuilder.appendQueryParameter("isnbafranchise", franchise);
RequestQueue requestQueue = Volley.newRequestQueue(application);
StringRequest request = new StringRequest(Request.Method.GET, uriBuilder.toString(), new Response.Listener<String>() {
#Override
public void onResponse(String response) {
List<NBATeam> teamList = QueryUtils.extractFeatureFromJson(response);
teams.setValue(teamList);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error Volley", error.toString());
}
});
requestQueue.add(request);
}
But it is the same as without the appendQueryParameter, returns all the taams. I've also tried doing a GET request from Mozilla (http://data.nba.net/10s/prod/v2/2018/teams.json?isnbafranchise=true) and the same result, which makes me think that I'm not doing the query correctly.

How do i split a string of jsonObjects into an array

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) {
}
});

How to receive data from web asynchronous and use the result string in the next line of code?

I want to get some JSON code from my API. I wish to do something like this in the OnCreate:
try
{
String jsonstr = getSomeThingAndPauseAndroid("http://someplace.com/api/xyz");
if (!jsonstr.isEmpty()) JSONObject jsonobj = new JSONObject(jsonstr);
}
catch { // handle error }
But when it happens, Android just go doing stuff and don't wait for the request to complete and response and I get nothing on jsonstr.
Is there some way to do that not needing a lot of new class files?
The correct way to do this is to make the request asynchronously and trigger a method on response. This is an example using Google's Volley:
//Start volley:
RequestQueue queue = Volley.newRequestQueue(this); // this = context
final String url = "http://someplace.com/api/xyz"";
// prepare the Request
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
//This is where you setup your UI
//Remember to dismiss the ProgressDialog
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
//Remember to dismiss the ProgressDialog
Log.d("Error.Response", response);
}
}
);
// add it to the RequestQueue
//Here you should add a ProgressDialog so the user knows to wait
queue.add(getRequest);

How to return parsed data from Volley onResponse?

I am using Volley StringRequest to make GET call to web services using following code.
ArrayList<HashMap<String, Object>> list;
StringRequest getRequest = new StringRequest(Request.Method.GET,activity.getString(R.string.URL),
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
int success;
//Parsed data and Want to return list
//return list;
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error.Response", error.toString());
}
});
request.add(getRequest);
Any idea how do I return the list data?
Use interface as listeners and return the data
public interface DataListener {
void onDataReceived(ArrayList<HashMap<String, Object>> response);
void onError(DataResponse resp); }
then in onResponse
datalistener.onDataReceived(list);
In your case you have a list defined just outside the Volley request. Just assign the new data from where you receive the data.
list = yourNewList;
or use interfaces.
However you are using a StringRequest and you will only get a String as a response from the server. You will have to parse the String yourself and build up the list.
If you are expecting a JSON respons you can use JsonArrayRequest or JsonObjectRequest instead of StringRequest.

Categories

Resources