My previous article Android JSON Parsing Tutorial explains parsing json in a simple manner which got very good feedback and good ranking in search engines. In this tutorial I want to explain the same but in a easy & robust way using volley library.
If you want to know more about Volley and it’s benefits, go through Android working with Volley Library.
So let’s start this with a simple project.
Creating New Project
1. Create a new project in Eclipse from File ⇒ New ⇒ Android Application Project and fill all the required details.
I gave my project name as VolleyJson and package name as info.androidhive.volleyjson
2. Now create a new package under src folder by Right clicking on src ⇒ New ⇒ Package and give the package name as app. So my new package name will be info.androidhive.volleyjson.app
3. Download volley.jar and paste it in project’s libs folder.
4. Create a new class named AppController.java under app package. This is going to be a singleton class where we initialize all the volley core objects.
package info.androidhive.volleyjson.app; import android.app.Application; import android.text.TextUtils; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; public class AppController extends Application { public static final String TAG = AppController.class.getSimpleName(); private RequestQueue mRequestQueue; private static AppController mInstance; @Override public void onCreate() { super.onCreate(); mInstance = this; } public static synchronized AppController getInstance() { return mInstance; } public RequestQueue getRequestQueue() { if (mRequestQueue == null) { mRequestQueue = Volley.newRequestQueue(getApplicationContext()); } return mRequestQueue; } public <T> void addToRequestQueue(Request<T> req, String tag) { req.setTag(TextUtils.isEmpty(tag) ? TAG : tag); getRequestQueue().add(req); } public <T> void addToRequestQueue(Request<T> req) { req.setTag(TAG); getRequestQueue().add(req); } public void cancelPendingRequests(Object tag) { if (mRequestQueue != null) { mRequestQueue.cancelAll(tag); } } }
5. AppController.java has to be executed when the app is launched. So add this class in your AndroidManifest.xml using name attribute for <application> tag.
Also add INTERNET permission as we need to make internet calls from the app.
<application android:name="info.androidhive.volleyjson.app.AppController">
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="info.androidhive.volleyjson" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21" /> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" android:name="info.androidhive.volleyjson.app.AppController"> <activity android:name="info.androidhive.volleyjson.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
6. Open the layout file of main activity and add below code. (In my case my main activity layout file is activity_main.xml).
In this layout we are adding two Buttons and a TextView. In two Button, one is to invoke json object request and other is to invoke json array request. The TextView is used to display the parsed json response.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="${relativePackage}.${activityClass}" > <Button android:id="@+id/btnObjRequest" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:paddingLeft="15dp" android:paddingRight="15dp" android:text="Make JSON Object Request" /> <Button android:id="@+id/btnArrayRequest" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:paddingLeft="15dp" android:paddingRight="15dp" android:text="Make JSON Array Request" android:layout_below="@id/btnObjRequest" /> <TextView android:id="@+id/txtResponse" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/btnArrayRequest" android:layout_marginTop="40px" android:padding="20dp" /> </RelativeLayout>
7. Now open main activity class MainActivity.java and add basic code like importing UI elements, adding button click events and initializing other objects.
Below you can notice two methods makeJsonObjectRequest() and makeJsonArrayRequest(). But these methods left empty for now, we’ll add code for these methods in next steps.
package info.androidhive.volleyjson; import info.androidhive.volleyjson.R; import info.androidhive.volleyjson.app.AppController; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request.Method; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.JsonObjectRequest; public class MainActivity extends Activity { // json object response url private String urlJsonObj = "https://api.androidhive.info/volley/person_object.json"; // json array response url private String urlJsonArry = "https://api.androidhive.info/volley/person_array.json"; private static String TAG = MainActivity.class.getSimpleName(); private Button btnMakeObjectRequest, btnMakeArrayRequest; // Progress dialog private ProgressDialog pDialog; private TextView txtResponse; // temporary string to show the parsed response private String jsonResponse; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnMakeObjectRequest = (Button) findViewById(R.id.btnObjRequest); btnMakeArrayRequest = (Button) findViewById(R.id.btnArrayRequest); txtResponse = (TextView) findViewById(R.id.txtResponse); pDialog = new ProgressDialog(this); pDialog.setMessage("Please wait..."); pDialog.setCancelable(false); btnMakeObjectRequest.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // making json object request makeJsonObjectRequest(); } }); btnMakeArrayRequest.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // making json array request makeJsonArrayRequest(); } }); } /** * Method to make json object request where json response starts wtih { * */ private void makeJsonObjectRequest() { } /** * Method to make json array request where response starts with [ * */ private void makeJsonArrayRequest() { } private void showpDialog() { if (!pDialog.isShowing()) pDialog.show(); } private void hidepDialog() { if (pDialog.isShowing()) pDialog.dismiss(); } }
Normally json response will be of two types. It can be either json object or json array. If the json starts with {, it is considered to be JSON Object. As well if the json starts with [, then it is JSON Array.
Now we’ll see how to make these requests individually.
Making JSON Object Request
8. Volley provides JsonObjectRequest class to make json object request. Add the below code in makeJsonObjectRequest() method. Here we are fetching the json by making a call to below url and parsing it. Finally the parsed response is appended to a string and displayed on the screen.
Sample JSON Object Response
URL: https://api.androidhive.info/volley/person_object.json
{ "name" : "Ravi Tamada", "email" : "ravi8x@gmail.com", "phone" : { "home" : "08947 000000", "mobile" : "9999999999" } }
/** * Method to make json object request where json response starts wtih { * */ private void makeJsonObjectRequest() { showpDialog(); JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, urlJsonObj, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d(TAG, response.toString()); try { // Parsing json object response // response will be a json object String name = response.getString("name"); String email = response.getString("email"); JSONObject phone = response.getJSONObject("phone"); String home = phone.getString("home"); String mobile = phone.getString("mobile"); jsonResponse = ""; jsonResponse += "Name: " + name + "\n\n"; jsonResponse += "Email: " + email + "\n\n"; jsonResponse += "Home: " + home + "\n\n"; jsonResponse += "Mobile: " + mobile + "\n\n"; txtResponse.setText(jsonResponse); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } hidepDialog(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); // hide the progress dialog hidepDialog(); } }); // Adding request to request queue AppController.getInstance().addToRequestQueue(jsonObjReq); }
Making JSON Array Request
9. Volley provides JsonArrayRequest class to make json array request. Add the below code in makeJsonArrayRequest() method.
Sample JSON Array Response
URL: https://api.androidhive.info/volley/person_array.json
[ { "name" : "Ravi Tamada", "email" : "ravi8x@gmail.com", "phone" : { "home" : "08947 000000", "mobile" : "9999999999" } }, { "name" : "Tommy", "email" : "tommy@gmail.com", "phone" : { "home" : "08946 000000", "mobile" : "0000000000" } } ]
/** * Method to make json array request where response starts with [ * */ private void makeJsonArrayRequest() { showpDialog(); JsonArrayRequest req = new JsonArrayRequest(urlJsonArry, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d(TAG, response.toString()); try { // Parsing json array response // loop through each json object jsonResponse = ""; for (int i = 0; i < response.length(); i++) { JSONObject person = (JSONObject) response .get(i); String name = person.getString("name"); String email = person.getString("email"); JSONObject phone = person .getJSONObject("phone"); String home = phone.getString("home"); String mobile = phone.getString("mobile"); jsonResponse += "Name: " + name + "\n\n"; jsonResponse += "Email: " + email + "\n\n"; jsonResponse += "Home: " + home + "\n\n"; jsonResponse += "Mobile: " + mobile + "\n\n\n"; } txtResponse.setText(jsonResponse); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } hidepDialog(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); hidepDialog(); } }); // Adding request to request queue AppController.getInstance().addToRequestQueue(req); }
Now run the project and test it once. You should able to see the parsed json displayed on the screen upon tapping the json request buttons.
Complete Code
Here is the complete code of MainActivity.java
package info.androidhive.volleyjson; import info.androidhive.volleyjson.R; import info.androidhive.volleyjson.app.AppController; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request.Method; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.JsonObjectRequest; public class MainActivity extends Activity { // json object response url private String urlJsonObj = "https://api.androidhive.info/volley/person_object.json"; // json array response url private String urlJsonArry = "https://api.androidhive.info/volley/person_array.json"; private static String TAG = MainActivity.class.getSimpleName(); private Button btnMakeObjectRequest, btnMakeArrayRequest; // Progress dialog private ProgressDialog pDialog; private TextView txtResponse; // temporary string to show the parsed response private String jsonResponse; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnMakeObjectRequest = (Button) findViewById(R.id.btnObjRequest); btnMakeArrayRequest = (Button) findViewById(R.id.btnArrayRequest); txtResponse = (TextView) findViewById(R.id.txtResponse); pDialog = new ProgressDialog(this); pDialog.setMessage("Please wait..."); pDialog.setCancelable(false); btnMakeObjectRequest.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // making json object request makeJsonObjectRequest(); } }); btnMakeArrayRequest.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // making json array request makeJsonArrayRequest(); } }); } /** * Method to make json object request where json response starts wtih { * */ private void makeJsonObjectRequest() { showpDialog(); JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, urlJsonObj, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d(TAG, response.toString()); try { // Parsing json object response // response will be a json object String name = response.getString("name"); String email = response.getString("email"); JSONObject phone = response.getJSONObject("phone"); String home = phone.getString("home"); String mobile = phone.getString("mobile"); jsonResponse = ""; jsonResponse += "Name: " + name + "\n\n"; jsonResponse += "Email: " + email + "\n\n"; jsonResponse += "Home: " + home + "\n\n"; jsonResponse += "Mobile: " + mobile + "\n\n"; txtResponse.setText(jsonResponse); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } hidepDialog(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); // hide the progress dialog hidepDialog(); } }); // Adding request to request queue AppController.getInstance().addToRequestQueue(jsonObjReq); } /** * Method to make json array request where response starts with [ * */ private void makeJsonArrayRequest() { showpDialog(); JsonArrayRequest req = new JsonArrayRequest(urlJsonArry, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d(TAG, response.toString()); try { // Parsing json array response // loop through each json object jsonResponse = ""; for (int i = 0; i < response.length(); i++) { JSONObject person = (JSONObject) response .get(i); String name = person.getString("name"); String email = person.getString("email"); JSONObject phone = person .getJSONObject("phone"); String home = phone.getString("home"); String mobile = phone.getString("mobile"); jsonResponse += "Name: " + name + "\n\n"; jsonResponse += "Email: " + email + "\n\n"; jsonResponse += "Home: " + home + "\n\n"; jsonResponse += "Mobile: " + mobile + "\n\n\n"; } txtResponse.setText(jsonResponse); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } hidepDialog(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); hidepDialog(); } }); // Adding request to request queue AppController.getInstance().addToRequestQueue(req); } private void showpDialog() { if (!pDialog.isShowing()) pDialog.show(); } private void hidepDialog() { if (pDialog.isShowing()) pDialog.dismiss(); } }
Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: ravi@androidhive.info
I am using jsonarrayrequest and it causes myapp keeps stopping
Check the LogCat for errors.
plzz delete ad from your site
its distracting really
Ads pays the server bills and other expenditures to run the blog.
This app is not working.Showing empty toast.
i want to send paramters as json object to service.
public sub somefunction(o as classEmp)
End Sub
Hope this work ..
how to get this data recycle view
There are bunch of tutorials about json and recycler view. Search in google by adding androidhive at the end.
Thanks…You were very helpful.
How to do ExpandableListview with json.Plz make tutorial on ExpandableListView with Json.
im getting error here
please help me
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
same error…..help plzz
same error….
Any error report?
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void com.example.admin.litebulb.AppVolleyController.addToRequestQueue(com.android.volley.Request, java.lang.String)’ on a null object reference
This is the error here
Please help..
Add AppVolleyController to your manifest file.
Some time Error in Volly like as com.android.volley.TimeoutError to get the data from the server.
So Please Kindly Help this regarding Solve this error
How to fix this problem
Error:(62, 23) error: TAG has private access in FragmentActivity
Hi,
I used your method with some modification (makeJsonObject),
But programe going inside to the method makeJsonObject and
not going in site to
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
urlJsonObj+id, null, new Response.Listener() {
}
may know why this happening?
What is the url you are trying to parse (I need to see the json data). Also print the error in onError method.
Hello Ravi,
I want to print my error from “onErrorResponse”. I know how to print but i want to print separately on different text view.
my error :- “error”:{“name”:[“name field is required”], “email”:[“email field is required “], “password”:[“password field is required”]}– so i want to print them separately i mean-“name field is required” in one textview, “email field is required ” in 2nd textview, hope You can help me. thanks
Do you know how to use Gson?
no
Ok learn Gson serialization and refer this article to see how to use it with Volley.
https://www.androidhive.info/2017/11/android-recyclerview-with-search-filter-functionality/
Good day Ravi, i would just like to ask. What is the problem with my connection?
@Override
protected String doInBackground(String… params) {
try {
// Enter URL address where your php file resides
url = new URL(“http://mysite/sitepath/login.php”);
//url = new URL(“http://192.168.56.1/login/login.php”);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return “exception”;
}
I am not having problem when i’m connected to my localhost but when i used the website url it doesnt show any message and my login path isnt working. Hope you can help me regarding this. MORE POWER TO YOU MAN!
Hi Keima
Is your url accessible via Postman?
Hi Ravi,
The above code tells about accessing an API at the server and retrieving the data either as an object or an array.
My need is to send send the data to an API, that in turn saves the data on to a database and returns status. How to do this with Volley
Hi Monica
Once you are good with Volley, move to Retrofit. Retrofit is best for your case. Volley is not actively developed and Retrofit offers more options than volley.
Get started with Retrofit here
https://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/
Thanks for the reply Ravi.
But my query still remains unanswered. I’ll elaborate slightly.
I want to send a record(name, contact no, location) to a php file running on server. In return my app will receive raw data such as 1 or 0 in case of successful or unsuccessful respectively.
Okay. Refer the article below. You can use
getParams()
method to send params (4th section in the article)https://www.androidhive.info/2014/05/android-working-with-volley-library-1/
Hello Ravi
is there any tutorial for Volley Json Parsing in Android Studio ? cause i don’t have Eclipse…..
Hello Ravi thank you for your tutorial i have question
How I can post a string to a PHP web server and get JSONArray in response using Volley library in Android
You can send the string value as param using
getParams()
method. Find more about volley herehttps://www.androidhive.info/2014/05/android-working-with-volley-library-1/
Hello Ravi
I’m frustration with my code. I already got some reference from stack overflow but no luck.
This is regarding passing the data with authentication header. Please note I’ve been tested POSTMAN and no issue. The data success to record (using unique ID as authentication key)
See my code
Please advice if you see something wrong. For the record I got error : Volley : Unexpected response code 400
anyway if you have any reference please let me know.
@Override
public String getBodyContentType(){
return “application/json”;
}
@Override
public Map getHeaders() throws AuthFailureError{
// Posting params to register url
// data you want to save to SQL
//once validation completed
Log.d(TAG, “getHeaders with unique ” + apiKey);
HashMap headers = new HashMap();
String auth = apiKey; Log.d(TAG, “getHeaders with unique ” + apiKey);
headers.put(“Authorization “, apiKey);
System.out.println(“selesai jalankan headers”);
return headers;
}
@Override
public Map getParams() throws AuthFailureError{
// Posting params to register url
// data you want to save to SQL
HashMap params = new HashMap();
params.put(“kostName”, kostname);
params.put(“kostAddress”, kostaddress);
System.out.println(“selesai jalankan params”);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
When are you getting 400 request? Requested from the mobile?
I’m running the application through geany motion. See the logcat:
01-31 07:58:13.888 D/AddKostActivity( 1499): ID Unique292 d2803a15284826cf2e32bd4fdc20c655
01-31 07:58:13.889 D/AddKostActivity( 1499): URL http://192.168.56.1:81/crystal/v1/addkost
01-31 07:58:13.944 D/AddKostActivity( 1499): getHeaders with unique d2803a15284826cf2e32bd4fdc20c655
01-31 07:58:13.944 D/AddKostActivity( 1499): getHeaders with unique d2803a15284826cf2e32bd4fdc20c655
01-31 07:58:13.944 I/System.out( 1499): selesai jalankan headers
01-31 07:58:13.944 D/NetworkSecurityConfig( 1499): No Network Security Config specified, using platform default
01-31 07:58:13.959 I/System.out( 1499): selesai jalankan params
01-31 07:58:14.622 E/Volley ( 1499): [120] BasicNetwork.performRequest: Unexpected response code 400 for http://192.168.56.1:81/crystal/v1/addkost
01-31 07:58:14.677 E/AddKostActivity( 1499): Error is: null
01-31 07:58:15.284 I/ActivityManager( 558): Waited long enough for: ServiceRecord{7973028 u0 com.android.calendar/.alerts.InitAlarmsService}
I’m pretty sure the authentication are correct since I already tested from POSTMAN
Its because of WAMP / MAMP configuration. Search for WAMP 400 bad request. You need to do few modifications in apache config.
Hi Ravi,
I’m trying to figure out regards what you mention before for couple day but still stuck to get what’s wrong with this :
01-31 07:58:14.622 E/Volley ( 1499): [120] BasicNetwork.performRequest: Unexpected response code 400 for http://192.168.56.1:81/crystal/v1/addkost
so there are some log from my web server but I don’t understand (already see stackoverflow)
–access log–
192.168.56.1 – – [02/Feb/2018:15:38:32 +0800] “POST /crystal/v1/addkost HTTP/1.1” 400 226
192.168.56.1 – – [02/Feb/2018:15:38:34 +0800] “POST /crystal/v1/addkost HTTP/1.1” 400 226
192.168.56.1 – – [02/Feb/2018:15:38:35 +0800] “POST /crystal/v1/addkost HTTP/1.1” 400 226
192.168.56.1 – – [02/Feb/2018:15:57:03 +0800] “POST /phpmyadmin/index.php HTTP/1.1” 200 1367
how about my error log ? kindly see
–error log–
[Thu Feb 01 20:48:39.801011 2018] [core:notice] [pid 7332:tid 272] AH00094: Command line: ‘C:\Bitnami\WAMPST~1.23-\apache2\bin\httpd.exe -d C:/Bitnami/wampstack-7.0.23-0/apache2 -f C:\Bitnami\WAMPST~1.23-\apache2\conf\httpd.conf’
[Thu Feb 01 20:48:39.819013 2018] [mpm_winnt:notice] [pid 7332:tid 272] AH00418: Parent: Created child process 5480
[Thu Feb 01 20:48:40.633116 2018] [ssl:warn] [pid 5480:tid 156] AH01909: localhost:443:0 server certificate does NOT include an ID which matches the server name
[Thu Feb 01 20:48:40.966159 2018] [ssl:warn] [pid 5480:tid 156] AH01909: localhost:443:0 server certificate does NOT include an ID which matches the server name
and truly I don’t understand. If you have any reference for my code please help to provide.
Is this something related to your problem
https://community.bitnami.com/t/apache-error-server-certificate-does-not-include-an-id-which-matches-the-server-name/52679/2
https://community.bitnami.com/t/apache-failed-to-start-mydomain-net-443-0-server-certificate-does-not-include-an-id-which-matches-the-server-name/30641
Hi Ravi thank for reference but the issue isn’t from SSL
so I decide to debug using Fiddler and found the issue. So authentication success to pass but Apache not count as Authentication key. I attempt to use Proxy Authentication and is detected and success. Getting frustration but need to resolve it. hehehe
In case you have one similar this issue, please share with me
I still do research for this cases. Two weeks has passed for this case. hiks
Yup sometime it takes years 🙂
what is the use of singleton class?
I am facing this problem
Error:Execution failed for task ‘:app:transformDexArchiveWithExternalLibsDexMergerForDebug’.
> com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
It might be because of multiple libraries added in build.gradle. Search for ‘Android MultiDex support’.
If you added any volley library remove it from your app level build.gradle .It just worked for me..!
Hi Ravi,
My issue is a bit different from this blog. its that i’m using a post request and i’m sending authorization in header and a single parameter but in getting a Volly.serverError something like that can you tell me the reason ?????? Please help with this issue
Hello. Just wanted to ask that why did you use .json file to get json data. And also can’t we use a .php file which echo’s json encode
I used static .json file to reduce burden on server. As running php file takes some CPU and other resources, I kept direct static json file. You can use php echo to do the same.
Thank you sir for this tutorial but i hv one problem, i hv large amount of json data can i parse smoothly those json data using this tutorial??
Try retrofit with Gson. What could be size of your JSON?
around 5-6mb and 10000+ json data
http://appdevbuild.com/json/allvideos/data.json
above is my one json file , i hv 50+ more json file to parse
please give tutorial link that u mentioned retrofit
Thanx in Advance. 🙂
5-6 MB is problematic if user is on slower network connection. Try splitting the json into smaller chunks or download it when necessary. You can add pagination to your JSON.
Here is the Retrofit tutorial
https://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/
Hi Ravi,
Will it be possible to call the request from a second activity and display the output on the main activity? any command line that I need to add?
You can use Intent to send the data between activities.
Is there any error in LogCat? Also this line is wrong.
countries.add(“india”); (you are not adding the variable instead adding the string “india”)
Should be
countries.add(india);
My mistake, I forgot to add arrayAdapter.notifyDataSetChanged(); Now its ok and displaying properly.
I’m completing a simple json parsing using 2 activity and Thanks to your codes above, I was able to patch up some of my missing code, It was helpful. Good job Ravi.
Thanks Joel. Now you try parsing the JSON using a serializer like Gson. Try learning these
JSON parsing using Gson
https://www.androidhive.info/2018/01/android-content-placeholder-animation-like-facebook-using-shimmer/
https://www.androidhive.info/2017/12/android-working-with-bottom-navigation/
Using Retrofit and Gson
https://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/
I will check it out, thanks for the reference, may I ask do you have a topic about hashmap/floats, I’m just wandering if I have a string and my float value comes from json is it possible to do? Map
Thanks in advanced. Sorry for the off topic question.
You can create a POJO class for that.
Hi,
I need to send json parameters like the image … How can i send this kind of json parameters?
Like this :
{“LoginRequest”: {
“request_datetime”: null,
“SeguridadManager”: {
“usuario”: “jfloresn”,
“password”: “Peru123456”,
“IMEI”: “4564646464646”,
“numero_celular”: “940717493”
}
}
}
helpme please
Hi,
i want to use the jsonObject Request but there is one problem:
when i click on the Button “MAKE JSON OBJECT REQUEST” my app close.
did anybody had the same problem and found any solution??
or can anybody help me here with this?
please help
Is there any error in LogCat?
how to pass Headers in volley?
got solution by adding this
@Override
public Map getHeaders() throws AuthFailureError {
Map headers = new HashMap();
/*String credentials = “username:password”;
String auth = “Basic ”
+ Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headers.put(“Content-Type”, “application/json”);
headers.put(“Authorization”, auth);*/
headers.put(“header-key”, “header-value”);
return headers;
}
hi, why my add toRequestQueue is null? I follow your instruction but my cide not working.
‘void com.example.simplevolley.simplevolley.AppController.addToRequestQueue(com.android.volley.Request)’ on a null object reference.
can give me some assist…
well, I forget to put android:name=”com.example.simplevolley.simplevolley.AppController” in manifest.xml. Thank you for the tutorial
Cheers!
Nice article.
How can I use this whit AsyncTask? Or it not needed?
Volley internally uses AsyncTask to make the calls. So you don’t have to write again.
hello perfect work I have some problem i want to call jsonArray method inside jsonObject mothed.
when I call it my response goes for NORMAL null and wait when jsonObect finished
Can you post your code?
private void parseJson(String url) {
if (page_id > last_page && last_page>0)
return;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url + page_id, null,
new Response.Listener() {
@Override
public void onResponse(JSONObject response) {
try {
mPostView= new ArrayList();
page_id++;
JSONArray jsonArray = response.getJSONArray(“data”);
last_page = response.getInt(“last_page”);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject data = jsonArray.getJSONObject(i);
int id = data.getInt("id");
String title =data.getString("title");
int o = 60;
String content = data.getString("content");
sliderImgValue = new ArrayList();
sendRequest(request_url,id);
// sliderImgResult.addAll(sliderImgValue);
mPostView.add(new postView(sliderImgValue, title, o, id, content));
}
mPostAdapter.addData(mPostView);
mPostAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
AppController.getInstance().addToRequestQueue(request);
}
public void sendRequest(String url,int id){
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url+id , null, new Response.Listener() {
@Override
public void onResponse(JSONArray response) {
List sliderImg = new ArrayList();
for(int i = 0; i < response.length(); i++){
try {
JSONObject jsonObject = response.getJSONObject(i);
sliderImg.add(jsonObject.getString("content"));
} catch (JSONException e) {
e.printStackTrace();
}
}
sliderImgValue.addAll(sliderImg);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
// CustomVolleyRequest.getInstance(getContext()).addToRequestQueue(jsonArrayRequest);
AppController.getInstance().addToRequestQueue(request);
}
private void parseJson(String url) {
if (page_id > last_page && last_page>0)
return;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url + page_id, null,
new Response.Listener() {
@Override
public void onResponse(JSONObject response) {
try {
mPostView= new ArrayList();
page_id++;
JSONArray jsonArray = response.getJSONArray(“data”);
last_page = response.getInt(“last_page”);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject data = jsonArray.getJSONObject(i);
int id = data.getInt("id");
String title =data.getString("title");
int o = 60;
String content = data.getString("content");
sliderImgValue = new ArrayList();
sendRequest(request_url,id);
// sliderImgResult.addAll(sliderImgValue);
mPostView.add(new postView(sliderImgValue, title, o, id, content));
}
mPostAdapter.addData(mPostView);
mPostAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
AppController.getInstance().addToRequestQueue(request);
}
public void sendRequest(String url,int id){
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url+id , null, new Response.Listener() {
@Override
public void onResponse(JSONArray response) {
List sliderImg = new ArrayList();
for(int i = 0; i < response.length(); i++){
try {
JSONObject jsonObject = response.getJSONObject(i);
sliderImg.add(jsonObject.getString("content"));
} catch (JSONException e) {
e.printStackTrace();
}
}
sliderImgValue.addAll(sliderImg);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
// CustomVolleyRequest.getInstance(getContext()).addToRequestQueue(jsonArrayRequest);
AppController.getInstance().addToRequestQueue(request);
}
hello I found the error only ordering code just access the adapter from the second not from the first method
Okay.
private void parseJson(String url) {
if (page_id > last_page && last_page>0)
return;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url + page_id, null,
new Response.Listener() {
@Override
public void onResponse(JSONObject response) {
try {
mPostView= new ArrayList();
page_id++;
JSONArray jsonArray = response.getJSONArray(“data”);
last_page = response.getInt(“last_page”);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject data = jsonArray.getJSONObject(i);
int id = data.getInt("id");
String title =data.getString("title");
int o = 60;
String content = data.getString("content");
sliderImgValue = new ArrayList();
sendRequest(request_url,id);
// sliderImgResult.addAll(sliderImgValue);
mPostView.add(new postView(sliderImgValue, title, o, id, content));
}
mPostAdapter.addData(mPostView);
mPostAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
AppController.getInstance().addToRequestQueue(request);
}
public void sendRequest(String url,int id){
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url+id , null, new Response.Listener() {
@Override
public void onResponse(JSONArray response) {
List sliderImg = new ArrayList();
for(int i = 0; i < response.length(); i++){
try {
JSONObject jsonObject = response.getJSONObject(i);
sliderImg.add(jsonObject.getString("content"));
} catch (JSONException e) {
e.printStackTrace();
}
}
sliderImgValue.addAll(sliderImg);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
// CustomVolleyRequest.getInstance(getContext()).addToRequestQueue(jsonArrayRequest);
AppController.getInstance().addToRequestQueue(request);
}
hello sir
in volley library i have added volley dependencies so now volly.jar is compulsory to add or not?
Not needed. Adding .jar is older way of doing it.
yes compulsry
how to send json data to server with header authentication ?? help me sir
Volley provides getHeaders method to send the headers. Read the below article
https://www.androidhive.info/2014/05/android-working-with-volley-library-1/
hello sir,
I’m getting the data from JSON file into the Strigns
but they are not adding into the List.
please help me out !!!
Any error in LogCat? Post your code.
No error
if I add to the list from outside the for loop it is adding
but if i add the data from inside the loop it is not adding
Code?
After the for the loop you need to call notify data changed on adapter to refresh the list. Are you doing it?
i have called it
the data from JSON file is fetched into two strings but they are not adding into the list
if i try to add dummy items into the list from a seperate loop then they are adding
Why Attempt to invoke virtual method ‘com.android.volley.Request com.android.volley.RequestQueue.add(com.android.volley.Request)’ on a null object reference ?
I have extends class with Application and add name to Application in Manifest already.
excelente post, te lo agradezco, tengo una duda
¿Como se cuando la pila ya ejecuto todas las peticiones? Quiero hacer muchas peticiones a un servidor y que cuando ya haya de responder a todas ejecutar otro código, lo que pasa es que las peticiones se ejecutan en otro hilo y como obtengo respuesta de este que ya realizo su tarea
why is this AppController class added?? The code is also working without the AppController class
I want to get data from server and data format is in an object How i will get it from URL please help me
{
“success”:true,
“timestamp”:1533875487,
“base”:”EUR”,
“date”:”2018-08-10″,
“rates”:{
“AED”:4.235626,
“AFN”:84.799019,
“ALL”:125.724519,
“AMD”:558.558733,
“ANG”:2.140242,
“AOA”:299.350794,
“ZWL”:371.71291
}
}
How to parse this nested JSON array in android
{
“prodCat_list”: [
{
“prods”: [
{
“cat_id”: “9”,
“position”: “1”,
“sku”: “wwww345”
},
{
“cat_id”: “9”,
“position”: “2”,
“sku”: “coof23”
},
{
“cat_id”: “9”,
“position”: “3”,
“sku”: “dde45”
},
{
“cat_id”: “9”,
“position”: “4”,
“sku”: “5555”
}
]
},
{
“prods”: [
{
“cat_id”: “9”,
“position”: “1”,
“sku”: “wwww345”
},
{
“cat_id”: “9”,
“position”: “2”,
“sku”: “coof23”
},
{
“cat_id”: “9”,
“position”: “3”,
“sku”: “dde45”
},
{
“cat_id”: “9”,
“position”: “4”,
“sku”: “5555”
}
]
},
]
}
how to pass the data in raw in post api
i have this type json format how to display on trs Value?
and one thing can i display
first i – n. घुमाव; चक्रण; झुकाव
second i. v. घूमना; कातना
to Only first word = n. घुमाव, घूमना
{
“data”: {
“eh”: {
“”: “spɪn”,
“ukphone”: “spɪn”,
“ukspeech”: “spin&type=1”,
“trs”: [
{
“i”: “n. घुमाव; चक्रण; झुकाव”
},
{
“i”: “v. घूमना; कातना”
}
],
how to parsing to database if the type was string?
Sir If data are in String form then how i get it kindly plz help
Pls post the sample data.
I’m looking for Json array request parsing which allows getParams to send POST to the php. Please help. Thank You
i am fresher in android so please help me to parse JSON
link(http://kwebmakerdigitalagency.com/isrc/services/audioList)
Hello Subodh please open this link and read briefly
https://www.androidhive.info/2012/01/android-json-parsing-tutorial/