Volley String Response of XML data and parse xml data - java

Following is my approach:
private void liveScores(){
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
if(requestQueue == null)
{
requestQueue = Volley.newRequestQueue(LiveScores.this);
}
requestQueue.add(stringRequest);
}
What I want is that i'm getting this response in string and this is xml data. I'm not able to use xmlpullparse in this. Can any one tell me how to make it async means these are live scores data and how to keep it refreshing after a while and also how to get objects of this response differentiate.
this is link of xml response and i want to get title element and put it in Listview.
Any help will be appreciated thanks.

Related

Sending a GET request with payload Volley

I want to make a GET request using Volley in Android Studio and in this request I want to include a body.
The problem is that when using the GET request, the body in the server is None (I am using Flask). On the other side, when using the POST method, the body reaches the server correctly. This is my code:
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url = Globals.WINGS_VEHICLES_URL;
JSONObject payload = new JSONObject();
try {
payload.put("user_id", Globals.USER_ID);
} catch (JSONException e) {
e.printStackTrace();
}
final String requestBody = payload.toString();
System.out.println(requestBody);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public byte[] getBody() {
return requestBody.getBytes();
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(0, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(stringRequest);
Is this a Volley restriction, or am I doing something wrong? Assume that I am using a JSONObject as body, non empty.
please check this answer
HTTP GET with request body
and Use POST Http method to send Body!!

Volley string request returns random character

I'm new to HTTP requests.
In my app I want to send a simple GET request from my API, which I first test in an API tester, and the response looks like this.
and for now I want to print out the exact same response with my app, so I use a StringRequest from the Android Volley Library. Here's my code.
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, TEST_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.println(Log.INFO, "SONGTUBEAPI", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.println(Log.ERROR, "SONGTUBEAPI", error.toString());
}
});
queue.add(stringRequest);
but now my response contains random characters.
2019-10-07 17:59:34.929 5140-5140/com.steven_wang.audioplayer I/SONGTUBEAPI: ������ftypdash��������iso6mp41����xmoov������lmvhd��������ØóíÜØóíÜ����¬D��¯������������������������������������������������������������������������������������������#������������������������������������������������������������������(mvex������ trex������������������������������������������������Ütrak������\tkhd������ØóíÜØóíÜ����������������¯��������������������������������������������������������������������������������������������#��������������������������xmdia������ mdhd��������ØóíÜØóíÜ����¬D��¯��Ç����������hdlr����������������soun������������������������ISO Media file produced by Google Inc. Created on: 05/04/2019.��������ñminf������$dinf������dref��������������������url ������������µstbl������istsd��������������������Ymp4a������������������������������������������¬D����������5esds��������'����#��������������������������������������������������������stts����������������������stsc����������������������stco����������������������stsz������������������������������smhd��������������������dsidx������������������¬D������������������������xä��¸����������w&��¸����������w'��¸����������vä��¸����������wl��¸����������vÕ��¸����������wZ��¸����������w!��¸����������w!��¸����������wG��¸����������w,��¸����������w:��¸����������w3��¸����������wA��¸����������v°��¸����������w¤��¸����������vð��¸����������w��¸����������wR��¸����������væ��¸����������w¦��¸����������v��¸����������wó��¸����������wm��¸����������v��¸����������vó��¸������������æ����T������������moof������mfhd��������������������traf������tfhd����*��������������������������������tfdt��������������������Ìtrun��������®���� ����s����t������������­����é����Ò����Ú����¹������������a����Q��������[����i��������|����������������v����²����;����p����2����H����J����P����e����c��������i����s����n��������Í��������{����j��������Y����X����U����f������������s����n����s��������H����8����R����P����Q��������g����h����Ú��������V����j������������¼����^����j����p����E����F����b����X��������ø����©������������Y����¢����T����N����a����H����Y����^����g������������f����s����e��������­����j����u��������V����p����b��������c������������u����W����|����h����¼����C����N����N����V����R����h����h����^��������b����h����j������������z����j����Y����Y����m��������g����c����É����ª��������j��������l����}����J����G����N����U����X����]��������a������������v����r����´����Ì��������j����a����e��������d����h����Z��������¦����c����i����Y��������M����F����p����Z����Q����c����a����q��������k����l����v����{��������¸����l����p����X����X����U����e����g����^����ó����È����l��������}����©����9����R����w����X����W��������S����h��������l����c����x��������à��������e����p����<����c����e����}����P��������������������r����U����r����I����Y����B����Y����h��������g����o����¬����f����s������������©����d����v����v����H����J����a����[����e����ö������������a����Y����}����X����S����P����V����n����f����\����v����Ï����c����w����h����k����©����³����B����m����H����\����h����f����k����o����î��������~��������N����¼����H����b����k����Y����a����_����W����b����Æ����l����j����W����l��������±����c����o����I����M����^����i����h����Ä����±����N����p��������c����­����C����p����T����_����]��������s����q����¡����b����{����d����{����Ð����\����l����d����Z����Z����c����\����k��������Ë����t����j����{��������Y����=����g����E����Z����S����`��������¯����[����V����h����s��������Ë����k����R���
What am I doing wrong? I tried fixing the encoding to utf-8 but the result is still the same.

Make POST request to Api in Android Studio

I'm trying to make a POST request to an api that I have created in Visual Studio. The api works, and I finally managed to find some code that allows me to connect to it (and it's not deprecated). The problem is that this code was made for a GET request while I need to make a POST. I created two boxes where I insert the data I want to pass (utente, password) and I created a button that takes the data from the boxex and convert them to string.
I tried already searching a lot of examples and tutorials that show how to make a POST request but the majority are very old and doesn't work anymore in Android Studio, or at least I can't make them work.
Now, this is the function that should be sending the data, I haven't touched the code since I don't really know what to modify except for the Request Method.
private StringRequest searchNameStringRequest(String utente, String password)
{
String url = "http://192.168.1.11:57279/api/utente";
return new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
try
{
JSONObject result = new JSONObject(response).getJSONObject("list");
int maxItems = result.getInt("end");
JSONArray resultList = result.getJSONArray("item");
}
catch (JSONException e)
{
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(MainActivity.this, "Food source is not responding (USDA API)", Toast.LENGTH_LONG).show();
}
});
}
Can someone explain me how to take the data and send it like a JSON Object that has
keys = user, password
values = utente, password (the values are from the two boxes mentioned before)
Thank to anyone who is willing to help me and I hope that asking for so much help isn't against the site rules.
I'm using Volley since is not so complicated and because it seems to work.
Using the GET method it show me the existing json with message cannot be converted to JSON object (I don't care about that, it's just a confirmation that it connects to the api)
Using the POST method it throws the ErrorResponse at the end (Food source is not responding)
EDIT: Added OnCreate method since I need a StringRequest return
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queue = Volley.newRequestQueue(this);
Button invia = findViewById(R.id.submit);
final EditText utenteInserito = findViewById(R.id.utente);
final EditText passwordInserito = findViewById(R.id.password);
invia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String utente = utenteInserito.getText().toString();
String password = passwordInserito.getText().toString();
queue.cancelAll(R.id.submit);
StringRequest stringRequest = searchNameStringRequest(utente, password);
stringRequest.setTag(R.id.submit);
queue.add(stringRequest);
}
});
}
EDIT: I have followed the suggested answer given but it doesn't seem to work
The resulting code is shown below but I get the OnErrorResponse, I don't think it's a problem with the api because trying with a GET response it gives me the exiting json array, so I think it's a problem with the code.
private StringRequest searchNameStringRequest(final String utente, final String password)
{
String url = "http://192.168.1.11:57279/api/utente";
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
System.out.println(response);
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(MainActivity.this,"Service Unavailable",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams()
{
Map<String,String> map = new HashMap<>();
map.put("user", utente.trim());
map.put("password",password.trim());
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(request);
return request;
}
It's working following this question:
How to send a POST request using volley with string body?
Thanks to you all for your interest.
String url = "your url";
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response);
dialog.dismiss();
try {
// your logic when API sends your some data
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(context,"Service Unavailable",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
}){
//This is how you will send the data to API
#Override
protected Map<String, String> getParams(){
Map<String,String> map = new HashMap<>();
map.put("name",username.getText().toString());
map.put("password",password.getText().toString());
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(request);
}
Here is a nice tutorial, I have tried it and it worked seamlessly.
Android Login and Registration with PHP, MySQL and SQLite
You can skip the sqlite and the phpMyAdmin part.

Can't get all rows in MySQL database using Volley

I have try to get all row in table in MySQL database and it' working well but when new row insert the application don't update the response but in web browsers is update
private void connect() {
RequestQueue requestQueue = Volley.newRequestQueue(Objects.requireNonNull(getContext()));
StringRequest stringRequest = new StringRequest(Request.Method.GET, GET_ALL_PHRASES_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response","the response : " + response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("response","the response error : " + error);
}
});
requestQueue.add(stringRequest);
}
the response in android studio log-cat
{"phrase":[{"id":"id_1"},{"id":"Id_2"},{"id":"id_3"},{"id":"id_5"}],"success":1}
and the response in web browser is
{"phrase":[{"id":"id_1"},{"id":"Id_2"},{"id":"id_3"},{"id":"id_5"},{"id":"id_6"},{"id":"id_7"}],"success":1}
my question is why the response is update in web and in android didn't up date but when i clear cash it update
Try disabling the Volley cache and see if that helps.
stringRequest.setShouldCache(false);
requestQueue.add(request);
If the above doesn't work, you might want to try
requestQueue.getCache().clear();
requestQueue.add(request);

Volley Request not working in this class, am I using it incorrectly?

Below is my class for handling http requests. I have tried the Volley Request in a new Android Project with no other code and the request is handled properly and I receive the result I expected. But for some reason when I use this code in my working project as a class, it doesn't return any response.
The way I call the request is:
HttpRequest request = new HttpRequest();
String url = "some-url";
String urlReturn = request.getFromURL(url, <ACTIVITY>.this);
where <ACTIVITY> is the activity I am calling the request from and "some-url" is a url that returns a string of data.
public class HttpRequest {
String response_test = "";
public String getFromURL (String url, Context context) {
RequestQueue requestQueue = Volley.newRequestQueue(context);
// 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.e("response1", response);
response_test = "1";
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Log.d("log2=", error.toString());
//requestQueue.stop();
}
});
// Add the request to the RequestQueue.
requestQueue.add(stringRequest);
requestQueue.start();
return response_test;
}
response_test never changes, so onResponse is never called. I thought there may be a timing issue, but when I add loop for it to wait until response_test is changed, it waits forever. Any idea what may be the issue? Anything I may have overlooked in how I'm calling this class?
Any help appreciated.
Volley is async library. It does work on another thread and when the call is ready it executes the code in onResponse. In the example you are returning imideately. Check your logcat for the messages they should be there

Categories