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.

android json parsing using volley

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.

android json parsing using volley

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();
	}
}
Subscribe
Notify of
guest
102 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
satyavrat95 Jha
satyavrat95 Jha
3 years ago

I am using jsonarrayrequest and it causes myapp keeps stopping

Ravi Tamada
3 years ago

Check the LogCat for errors.

zahra mohebi
zahra mohebi
3 years ago
Reply to  Ravi Tamada

plzz delete ad from your site
its distracting really

Ravi Tamada
3 years ago
Reply to  zahra mohebi

Ads pays the server bills and other expenditures to run the blog.

Anmol Jindal
Anmol Jindal
3 years ago

This app is not working.Showing empty toast.

arun
arun
3 years ago

i want to send paramters as json object to service.

public sub somefunction(o as classEmp)
End Sub

Mochamad Iqbal
Mochamad Iqbal
3 years ago

Hope this work ..

Thusitha Chanaka
Thusitha Chanaka
3 years ago

how to get this data recycle view

Ravi Tamada
3 years ago

There are bunch of tutorials about json and recycler view. Search in google by adding androidhive at the end.

Mücahid Bilgili
Mücahid Bilgili
3 years ago

Thanks…You were very helpful.

Shirisha Gangula
Shirisha Gangula
3 years ago

How to do ExpandableListview with json.Plz make tutorial on ExpandableListView with Json.

Prasad Vennam
Prasad Vennam
3 years ago

im getting error here

please help me

// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);

Yogesh Machhi
Yogesh Machhi
3 years ago
Reply to  Prasad Vennam

same error…..help plzz

javed
javed
2 years ago
Reply to  Yogesh Machhi

same error….

Ravi Tamada
2 years ago
Reply to  javed

Any error report?

Disha
Disha
2 years ago
Reply to  Ravi Tamada

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..

Ravi Tamada
2 years ago
Reply to  Disha

Add AppVolleyController to your manifest file.

Rajendra
Rajendra
3 years ago

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

Supriyanto
Supriyanto
3 years ago

How to fix this problem

Error:(62, 23) error: TAG has private access in FragmentActivity

Waseem
Waseem
3 years ago

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?

Ravi Tamada
3 years ago
Reply to  Waseem

What is the url you are trying to parse (I need to see the json data). Also print the error in onError method.

Dinesh
Dinesh
3 years ago

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

Ravi Tamada
3 years ago
Reply to  Dinesh

Do you know how to use Gson?

Dinesh
Dinesh
3 years ago
Reply to  Ravi Tamada

no

Ravi Tamada
3 years ago
Reply to  Dinesh

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/

Keima
Keima
2 years ago

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!

Ravi Tamada
2 years ago
Reply to  Keima

Hi Keima

Is your url accessible via Postman?

Monica
Monica
2 years ago

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

Ravi Tamada
2 years ago
Reply to  Monica

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/

Monica
Monica
2 years ago
Reply to  Ravi Tamada

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.

Ravi Tamada
2 years ago
Reply to  Monica

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/

Ban Midou
Ban Midou
2 years ago

Hello Ravi
is there any tutorial for Volley Json Parsing in Android Studio ? cause i don’t have Eclipse…..

David Iya
David Iya
2 years ago

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

Ravi Tamada
2 years ago
Reply to  David Iya

You can send the string value as param using getParams() method. Find more about volley here
https://www.androidhive.info/2014/05/android-working-with-volley-library-1/

Rivaldo Christian
Rivaldo Christian
2 years ago

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

Ravi Tamada
2 years ago

When are you getting 400 request? Requested from the mobile?

Rivaldo Christian
Rivaldo Christian
2 years ago
Reply to  Ravi Tamada

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}

Rivaldo Christian
Rivaldo Christian
2 years ago

I’m pretty sure the authentication are correct since I already tested from POSTMAN

Ravi Tamada
2 years ago

Its because of WAMP / MAMP configuration. Search for WAMP 400 bad request. You need to do few modifications in apache config.

Rivaldo Christian
Rivaldo Christian
2 years ago
Reply to  Ravi Tamada

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.

Rivaldo Christian
Rivaldo Christian
2 years ago
Reply to  Ravi Tamada

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

Ravi Tamada
2 years ago

Yup sometime it takes years 🙂

Shubham Kumar
Shubham Kumar
2 years ago

what is the use of singleton class?

Pritom Sarker
Pritom Sarker
2 years ago

I am facing this problem

Error:Execution failed for task ‘:app:transformDexArchiveWithExternalLibsDexMergerForDebug’.
> com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

Ravi Tamada
2 years ago
Reply to  Pritom Sarker

It might be because of multiple libraries added in build.gradle. Search for ‘Android MultiDex support’.

Joseph Kiran
Joseph Kiran
2 years ago
Reply to  Pritom Sarker

If you added any volley library remove it from your app level build.gradle .It just worked for me..!

Neville Narcis
Neville Narcis
2 years ago

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

Lakshay
Lakshay
2 years ago

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

Ravi Tamada
2 years ago
Reply to  Lakshay

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.

akshay vyash
akshay vyash
2 years ago

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??

Ravi Tamada
2 years ago
Reply to  akshay vyash

Try retrofit with Gson. What could be size of your JSON?

akshay vyash
akshay vyash
2 years ago
Reply to  Ravi Tamada

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. 🙂

Ravi Tamada
2 years ago
Reply to  akshay vyash

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/

Joel Cotto
Joel Cotto
2 years ago

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?

Ravi Tamada
2 years ago
Reply to  Joel Cotto

You can use Intent to send the data between activities.

Ravi Tamada
2 years ago

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

Joel Cotto
Joel Cotto
2 years ago
Reply to  Ravi Tamada

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.

Joel Cotto
Joel Cotto
2 years ago
Reply to  Ravi Tamada

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.

Ravi Tamada
2 years ago
Reply to  Joel Cotto

You can create a POJO class for that.

Rafael Raymundes
Rafael Raymundes
2 years ago

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

Adnan Tuhcic
Adnan Tuhcic
2 years ago

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

Ravi Tamada
2 years ago
Reply to  Adnan Tuhcic

Is there any error in LogCat?

Mitesh Makwana
Mitesh Makwana
2 years ago

how to pass Headers in volley?

Mitesh Makwana
Mitesh Makwana
2 years ago
Reply to  Mitesh Makwana

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

Syahmi Shafawi
Syahmi Shafawi
2 years ago

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…

Syahmi Shafawi
Syahmi Shafawi
2 years ago
Reply to  Syahmi Shafawi

well, I forget to put android:name=”com.example.simplevolley.simplevolley.AppController” in manifest.xml. Thank you for the tutorial

Ravi Tamada
2 years ago
Reply to  Syahmi Shafawi

Cheers!

Daniel Beltrami
2 years ago

Nice article.
How can I use this whit AsyncTask? Or it not needed?

Ravi Tamada
2 years ago

Volley internally uses AsyncTask to make the calls. So you don’t have to write again.

datapoint solution
datapoint solution
2 years ago

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

Ravi Tamada
2 years ago

Can you post your code?

datapoint solution
datapoint solution
2 years ago
Reply to  Ravi Tamada

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

datapoint solution
datapoint solution
2 years ago
Reply to  Ravi Tamada

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

datapoint solution
datapoint solution
2 years ago

hello I found the error only ordering code just access the adapter from the second not from the first method

Ravi Tamada
2 years ago

Okay.

datapoint solution
datapoint solution
2 years ago

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

Jayesh Pansheriya
Jayesh Pansheriya
2 years ago

hello sir
in volley library i have added volley dependencies so now volly.jar is compulsory to add or not?

Ravi Tamada
2 years ago

Not needed. Adding .jar is older way of doing it.

Rakib Shaikh
Rakib Shaikh
1 year ago

yes compulsry

IDREAM SANKAR
IDREAM SANKAR
2 years ago

how to send json data to server with header authentication ?? help me sir

Ravi Tamada
2 years ago
Reply to  IDREAM SANKAR

Volley provides getHeaders method to send the headers. Read the below article
https://www.androidhive.info/2014/05/android-working-with-volley-library-1/

Manohar
Manohar
2 years ago

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 !!!

Ravi Tamada
2 years ago
Reply to  Manohar

Any error in LogCat? Post your code.

Manohar
Manohar
2 years ago
Reply to  Ravi Tamada

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

Ravi Tamada
2 years ago
Reply to  Manohar

Code?

Ravi Tamada
2 years ago

After the for the loop you need to call notify data changed on adapter to refresh the list. Are you doing it?

Manohar
Manohar
2 years ago
Reply to  Ravi Tamada

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

Yin SoThearith
Yin SoThearith
2 years ago

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.

Jose A. Huanca Ancajima
Jose A. Huanca Ancajima
2 years ago

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

Nimit Goyal
Nimit Goyal
2 years ago

why is this AppController class added?? The code is also working without the AppController class

IHSAN ULLAH
IHSAN ULLAH
2 years ago

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
}
}

Ahi
Ahi
2 years ago

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”

}
]
},
]
}

Himanshu kesarwani
Himanshu kesarwani
1 year ago

how to pass the data in raw in post api

Mukesh Yadav
Mukesh Yadav
1 year ago

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. घूमना; कातना”
}
],

xylinx Zevyn
xylinx Zevyn
1 year ago

how to parsing to database if the type was string?

Ali Hassan
Ali Hassan
1 year ago

Sir If data are in String form then how i get it kindly plz help

Ravi Tamada
1 year ago
Reply to  Ali Hassan

Pls post the sample data.

David Kariuki
1 year ago

I’m looking for Json array request parsing which allows getParams to send POST to the php. Please help. Thank You

SUBODH KUMAR GUPTA
SUBODH KUMAR GUPTA
3 years ago

i am fresher in android so please help me to parse JSON
link(http://kwebmakerdigitalagency.com/isrc/services/audioList)

Shekhar Saini
Shekhar Saini
3 years ago

Hello Subodh please open this link and read briefly
https://www.androidhive.info/2012/01/android-json-parsing-tutorial/

102
0
Would love your thoughts, please comment.x
()
x