I will write about Android Volley Post Request With Parameters Example today.
You will learn to make volley post request with parameters in android studio.
If we do not need to pass parameters in volley request then we generally use GET request. It will simply make http call without any parameter and will give us JSON response.
For making volley GET request with parameters use,
https://demonuts.com/android-volley-get-request-with-parameters
Web Host Recommendation
If you are planning to buy best web hosting at an affordable prize then we recommend bluehost.
Click this link to see affordable plans.
(Disclaimer : If you sign up using the above link we may receive small commission without any addition cost to you)
See the Parameters
Following video demonstrate the working of this android volley post request example.
Step 1. Permission and dependencies Work
Make a new project in android studio and set the default activity as the “Empty activity.”
When we want to make http calls to remote server, we need to use internet of android device.
For this, we have to define INTERNET permission in our project.
Add the below line in AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET" />
- INTERNET permission is not harmful to user privacy so we do not need to ask for runtime permission in this example.
Now in your build.gradle(Module: app) file, add the below line
implementation 'com.android.volley:volley:1.1.1'
- Above line will enable us to use some classes of volley library and we can import them in our project.
Step 2. Making Hobby Activity
Create a new activity and give it a name “HobbyActivity.”
System will create two files : activity_hobby.xml and HobbyActivity.java
In the activity_hobby.xml file, write down the following code lines
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#edd712" android:gravity="center" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="40dp" android:id="@+id/tvusername" android:gravity="center_vertical" android:textSize="25sp" android:text="hello" android:layout_marginTop="10dp" android:layout_marginRight="20dp" android:layout_marginLeft="20dp" android:paddingLeft="5dp" android:background="#fff" android:hint="Enter Username" /> <TextView android:layout_width="match_parent" android:layout_height="40dp" android:id="@+id/tvpassword" android:gravity="center_vertical" android:textSize="25sp" android:layout_marginTop="10dp" android:layout_marginRight="20dp" android:layout_marginLeft="20dp" android:paddingLeft="5dp" android:background="#fff"/> </LinearLayout>
- There are two text views are there.
- When we call the web service, remote server will send us some data in JSON format. Among these data, we will parse first name and hobby.
- Above two text views will hold first name and hobby data.
Now in the HobbyActivity.java, add the below code structure
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class HobbyActivity extends AppCompatActivity { private TextView tvName, tvPass; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hobby); tvName = findViewById(R.id.tvusername); tvPass = findViewById(R.id.tvpassword); tvName.setText(MainActivity.firstName); tvPass.setText(MainActivity.hobby); } }
- As you can see that, I have taken two text views.
- These text views are getting their values with the help of two variables.
- One is firstName and other is hobby.
- These variables are defined in the MainActivity.java as the public identifier. Because these variables are public so we can use them in HobbyActivity.java file.
Step 3. Main Activity Files
When you have created new project in android studio, system must have created two files automatically.
One is activity_main.xml and other one is MainActivity.java
Source code for activity_main.xml is as the following
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#edd712" android:gravity="center" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="45sp" android:text="DemoNuts" android:textColor="#fff" android:layout_marginBottom="20dp"/> <EditText android:layout_width="match_parent" android:layout_height="40dp" android:id="@+id/etusername" android:layout_marginTop="10dp" android:layout_marginRight="20dp" android:layout_marginLeft="20dp" android:paddingLeft="5dp" android:background="#fff" android:hint="Enter Username" /> <EditText android:layout_width="match_parent" android:layout_height="40dp" android:id="@+id/etpassword" android:inputType="textPassword" android:layout_marginTop="10dp" android:layout_marginRight="20dp" android:layout_marginLeft="20dp" android:paddingLeft="5dp" android:background="#fff" android:hint="Enter Password" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/btn" android:text="Login" android:background="@color/colorPrimary" android:textColor="#fff" android:layout_marginTop="10dp" android:layout_marginLeft="20dp" android:layout_marginRight="20dp"/> </LinearLayout>
- Main XML file will create one login template. Here user will insert the login credentials.
- It includes One text view, two edit text and one button widget.
- Text view is static and it includes the header name.
- One edit text will receive the value of user name and other one will hold the value of password.
- When the user will click the button, we will make the POST http call with parameters using volley library.
Now write down the following code block in MainActivity.java file.
import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity { private String URLline = "https://demonuts.com/Demonuts/JsonTest/Tennis/simplelogin.php"; private EditText etUname, etPass; private Button btn; public static String firstName, hobby; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etUname = findViewById(R.id.etusername); etPass = findViewById(R.id.etpassword); btn = findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loginUser(); } }); } private void loginUser(){ final String username = etUname.getText().toString().trim(); final String password = etPass.getText().toString().trim(); StringRequest stringRequest = new StringRequest(Request.Method.POST, URLline, new Response.Listener<String>() { @Override public void onResponse(String response) { Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show(); parseData(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show(); } }){ @Override protected Map<String,String> getParams(){ Map<String,String> params = new HashMap<String, String>(); params.put("username",username); params.put("password",password); return params; } }; RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringRequest); } public void parseData(String response) { try { JSONObject jsonObject = new JSONObject(response); if (jsonObject.getString("status").equals("true")) { JSONArray dataArray = jsonObject.getJSONArray("data"); for (int i = 0; i < dataArray.length(); i++) { JSONObject dataobj = dataArray.getJSONObject(i); firstName = dataobj.getString("name"); hobby = dataobj.getString("hobby"); } Intent intent = new Intent(MainActivity.this,HobbyActivity.class); startActivity(intent); } } catch (JSONException e) { e.printStackTrace(); } } }
Looking Closely at Main Code
First of all, consider the below snippet
private String URLline = "https://demonuts.com/Demonuts/JsonTest/Tennis/simplelogin.php"; private EditText etUname, etPass; private Button btn; public static String firstName, hobby;
- First line is the string variable. It include the URL in string format.
- Second one is defining the objects of Edit text class and third one is giving us the object of Button class.
- Fourth code line is making two public string variables. We have used these public variables in Hobby Activity also.
Now read the below code structure
btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loginUser(); } });
- When the user clicks the button, compiler will call loginUser() method.
Coding lines for loginUser() method is as the following
private void loginUser(){ final String username = etUname.getText().toString().trim(); final String password = etPass.getText().toString().trim(); StringRequest stringRequest = new StringRequest(Request.Method.POST, URLline, new Response.Listener<String>() { @Override public void onResponse(String response) { Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show(); parseData(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show(); } }){ @Override protected Map<String,String> getParams(){ Map<String,String> params = new HashMap<String, String>(); params.put("username",username); params.put("password",password); return params; } }; RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringRequest); }
- Two string variables username and password are defined at the starting of this loginUser() method.
- username will get it’s value in string format from etUname which is an edit text.
- Other edit text etPass will give the value of password to the string variable password.
- After this, compiler will create the object of the StringRequest class.
Look at the below line
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLline,
- Here, Request.Method.POST will tell volley to make POST request.
- URLline is the string variable which holds the full URL structure.
Now read the following source code
@Override protected Map<String,String> getParams(){ Map<String,String> params = new HashMap<String, String>(); params.put("username",username); params.put("password",password); return params; }
- Above code will create one hash map. This map has two children.
- One is with key->”username” and value->string variable (username)
- Another is with key ->”password” and value -> string variable (password)
- This hash map will provide parameters to our URL.
- After successful call to the web service, compiler will execute onResponse() method.
- onResponse() method will create one Toast which will provide full JSON response.
- After Toast, compiler will call parseData() method. Parameter for this method is the JSON response in the string format.
Code structure for parseData() method is as the following
public void parseData(String response) { try { JSONObject jsonObject = new JSONObject(response); if (jsonObject.getString("status").equals("true")) { JSONArray dataArray = jsonObject.getJSONArray("data"); for (int i = 0; i < dataArray.length(); i++) { JSONObject dataobj = dataArray.getJSONObject(i); firstName = dataobj.getString("name"); hobby = dataobj.getString("hobby"); } Intent intent = new Intent(MainActivity.this,HobbyActivity.class); startActivity(intent); } } catch (JSONException e) { e.printStackTrace(); } }
- Here, compiler will first parse the JSON object.
- Then it will check the field “status“. If it’s value is true then it will parse one JSON array.
- Then it will create one for loop. Inside this for loop, compiler will parse first name and hobby.
- And then it will save this first name and hobby in public string variables.
- After for loop, system will open a new activity called “Hobby Activity”, which we have already created in Step 2.
Web Host Recommendation
If you are planning to buy best web hosting at an affordable prize then we recommend bluehost.
Click this link to see affordable plans.
(Disclaimer : If you sign up using the above link we may receive small commission without any addition cost to you)