What i want is to request a server using volley inside a service continuously, When a new entry is added in a database it notify a user that a new entry is available. I used volley to request a server and when a new request is added in a database it notify in a notification bar.
First you should add it to your build.gradle file in your project.
dependencies {
...
compile 'com.android.volley:volley:1.0.0'}
To make a request using Volley you should create a RequestQueue and pass it Request objects. The RequestQueue will manage the threads for the network, parsing, reading and writing operations. Below a quick code I did to make a request using the Volley lib.
private void consultarObjJson() {
RequestQueue pilha = Volley.newRequestQueue(this);
String url=webserviceCaminho+"alunos";
StringRequest consultaString = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String resposta) {
Log.d(TAG, "Resposta" + resposta);
GsonBuilder builder = new GsonBuilder();
Gson mGson = builder.create();
List<AlunoObj> post = new ArrayList<AlunoObj>();
post = Arrays.asList(mGson.fromJson(resposta, AlunoObj[].class));
alunoAdapter = new AlunoAdapter(getBaseContext(), post, "MainActivity");
recyclerView.setAdapter(alunoAdapter);
alunoAdapter.notifyDataSetChanged();
progressBar.setProgress(100);
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError erro) {
Log.d(TAG, "Erro :" + erro.getMessage());
}
}); pilha.add(consultaString);
}
For more details about how to use it check here Volley - Android developers
Related
I am learning about Volley and I don't know why the response from GET method is coming as a single char -> [.
I am using this method to get the JSON response:
public void getJsonMethod() {
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(context);
// String url = "https://www.w3schools.com/js/myTutorials.txt";
String url = "http://www.google.com"; // with this url I am getting response
// Request a string response from the provided URL.
final StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("Response is: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("Response is not good" + error.getMessage());
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
When I am using this link I do get a response but when I try to use some link that contains nothing but JSON like this one my response it "[".
I am calling this method from Activity like this:
GetJsonClass getJson = new GetJsonClass(this);
getJson.getJsonMethod();
Any ideas on what am I doing wrong here?
Answer + code
If anyone will start using Volley maybe this can help him :
as David Lacroix said in his answer, I called stringRequest and notJsonArrayRequest.
Here is how it should have been:
public void getJsonMethod() {
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(context);
String url = "your url";
JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
System.out.println("this is response good" + response);
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("this is response bad" + error);
}
});
queue.add(jsonObjectRequest);
}
See https://developer.android.com/training/volley/request
StringRequest. Specify a URL and receive a raw string in response. See Setting Up a Request Queue for an example.
JsonObjectRequest and JsonArrayRequest (both subclasses of JsonRequest). Specify a URL and get a JSON object or array (respectively) in response.
You should be using a JsonArrayRequest
myTutorials.txt is being served with status code 304 (no proper suffix and MIME type either):
304 Not Modified. If the client has performed a conditional GET request and access is allowed, but the document has not been modified, the server SHOULD respond with this status code. The 304 response MUST NOT contain a message-body, and thus is always terminated by the first empty line after the header fields.
In other terms, what the browser may display is not neccessarily the same what the server has sent. eg. GSON would accept that JSON only with option lenient enabled, because the array has no name.
see RFC 2616.
How can i Parse url with curly brackets like
http://example.com/api/login/{username}/{password} in an android application.
Normal volley post request returns html.But i need JSON.
Integrating Login API in Android App
If I get you right, what you want to do is send a GET request for login.
The following code can help you (it is not recommended to use GET for login, use POST instead. I'm giving a GET ex because that's what your'e asking for):
final TextView mTextView = (TextView) findViewById(R.id.text);
// ...
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://example.com/api/login/your_username/your_password";
// 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!");
}
});
In my application, I am uploading images and text responses to my server. I want to show a progress dialog with percentage while uploading.
Here is my code ,
code to call volley function :
//look at send data to server
// Send to server .calling my volley function
new NetworkController(context).sendAuditData(row, URL_Config.SAVE_AUDIT);
My volley to code to send data to server,
public void sendAuditData(final HashMap<String,String> audit_data,final String url)
{
// HttpsTrustManager.allowAllSSL();
createProgressDialog();
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String val[] = response.split(",");
if(val[0].equalsIgnoreCase("success")){
Toast.makeText(context,"Data submitted successly",Toast.LENGTH_SHORT).show();
CheckSuiteDAOI dao = new CheckSuiteDAO(context);
ContentValues cv = new ContentValues();
cv.put("sync_status","true");
dao.update_data(cv,"date_time=?",new String[] {val[1]},"CONTAINER_MASTER");
successDialog(audit_data);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dismisProgressDialog();
}
}){
#Override
protected Map<String,String> getParams(){
return audit_data;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(context);
int socketTimeout = 5000;//7seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
I want to show a progress dialog -- Possible
With percentage while upload -- Not Possible. This is some thing multipart upload by chunks of data. Api support also required.
Think 10 mb file your uploading and you set up 5 threads which uploading 2 mb. So uploading 2 threads success happens 40% completed. It works like that.
I want to send data from android app to remote server in JSON format.
Below is my json format :-
{
"contacts": [
{
"name": "ritva",
"phone_no": "12345657890",
"user_id": "1"
},
{
"name": "jisa",
"phone_no": "12345657890",
"user_id": "1"
},
{
"name": "tithi",
"phone_no": "12345657890",
"user_id": "1"
}
]
}
Can any one tell me how do I send this data using Volley?
Make a volley request like bellow which takes method like POST/GET,
url, response & error listener. And For sending your json override
getBody() method in which pass the json you want to send.
Make a RequestQueue & add the request to it. You might start it by
calling start()
Try this :
// 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.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// your response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
}
}){
#Override
public byte[] getBody() throws AuthFailureError {
String your_string_json = ; // put your json
return your_string_json.getBytes();
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
requestQueue.start();
For more info see this
1. Add Volley and Gson Dependency into build.gradle:
'com.mcxiaoke.volley:library:1.0.19'
'com.google.code.gson:gson:2.7'
Note: If you have JSON data in String variable then just pass the String variable as third parameter in JsonObjectRequest.(Go to Step 6)
If you have JSON data in your classes then just pass the class in gson.toJson() of the third parameter of JsonObjectRequest.(Go to Step 6)
If you want to get the data in class then you need to create classes structure same as JSON data. (Go to step 2)
2. Then create the POJO classes for the above JSON Structure using http://www.jsonschema2pojo.org/
Example Shown in image:
Red marks showing the changes needed to make on site
Then you will get two classes as ContactsTop and Contact.
Note: ContactsTop is name provided at the time of creating POJO classes from jsonschema2pojo.com
3. Add above generated classes into your project
4. Create Volley RequestQueue object and gson object.
RequestQueue requestQueue = Volley.newRequestQueue(this);
Gson gson = new Gson();
5. Then add above JSON data to POJO Classes.
ContactsTop contactsTop=new ContactsTop();
List<Contact> contactList =new ArrayList();
Contact contact=new Contact();
contact.setPhoneNo("12345657890");
contact.setName("ritva");
contact.setUserId("1");
contactList.add(contact);
contactsTop.setContacts(contactList);
6. Create JSONObject to call web service with your data.
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, "www.your-web-service-url.com/sendContact.php", gson.toJson(contactsTop), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.v("Volley:Response ", ""+response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.v("Volley:ERROR ", error.getMessage().toString());
}
});
7. Add your jsonObjectRequest into requestQueue. (Don't forget to add this line. this is will add your request in RequestQueue and then only you will get JSON Response or Error from your Service). Don't forget to add INTERNET Permission in AndroidManifest.xml
requestQueue.add(jsonObjectRequest);
Then you will get Response or Error from your Remote Service in android Log monitor.
For sending JSON type data you should make a JSON request using volley
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.POST, url, obj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
requestQueue.start();
Where object is your JSONObject that you want to send. Ask if you want more clarification.
Mark this up if this helps you.
(Sorry for any english mistake its not my native language)
I'm trying to parse html using Volley and Jsoup.
while debugging / running the app, the StringRequest dosent invoke onResponse() or onErrorResponse(), basically there no response or Error from the Response.Listener (i guess).
so i cant "begin" parsing the html because the onResponse() is never invoked.
Ive searched for answer and nothing seems to get it fixed.
Could it be that the RequestQueue cache kicks in and its not trying to get the response? (just brain storming tried so many things).
--Im just trying to retrive data from html, so i could show the updated data from the url in my app, is Volly the way or should i use simpler mathods?
here is my volley StringRequest and RequestQueue:
String url = "http://www.fringeb7.co.il/";
final RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
// 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) {
response_utf8 = URLDecoder.decode(URLEncoder.encode(response, "iso8859-1"),"UTF-8");
doc = Jsoup.parse(response_utf8);
Log.d("logr=",response);
}
},
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);
took me long enough, but there was no problem.
the code works, while debugging there were no response,
but when i run the app the request complete and i got the wanted response.
so if anyone have a similier problem, from some reason while debugging I dident get response but while running the app its working fine.
(simpley dident know that)
try this first before wasting time in debugging like i did.
If you use Jsoup, you can get it and parse in very simple way:
Document doc = Jsoup.connect("http://www.fringeb7.co.il/").get();
If you still want to use Volley, below code works perfectly in my device:
String url = "http://www.fringeb7.co.il/";
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
// 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) {
try {
String response_utf8 = URLDecoder.decode(URLEncoder.encode(response, "iso8859-1"), "UTF-8");
Document doc = Jsoup.parse(response_utf8);
Log.d("logr=", "title = " + doc.title());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
},
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();
Output of the above code:
D/logr=: title = תיאטרון הפרינג' באר שבע
try 'https' instead of 'http' in your url