Thursday, August 25, 2022

Working With Volley To Post And Get Data

 .


Get JSON Data

Create new empty project volleyGetJson

Add library in Graddle Dependencies

// volley library

implementation ‘com.android.volley:volley:1.1.1’

// image loading library

implementation ‘com.squareup.picasso:picasso:2.71828’

Add INTERNET permission in AndroidManifest

<!--permissions for INTERNET-->

<uses-permission android:name="android.permission.INTERNET"/>

Update activity_main layout

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context=".MainActivity">

 

    <androidx.cardview.widget.CardView

        android:id="@+id/idCVCourse"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_margin="10dp"

        android:elevation="10dp"

        android:visibility="gone"

        app:cardCornerRadius="8dp">

 

        <LinearLayout

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:orientation="vertical">

 

            <ImageView

                android:id="@+id/idIVCourse"

                android:layout_width="match_parent"

                android:layout_height="300dp"

                android:layout_margin="5dp" />

 

            <TextView

                android:id="@+id/idTVCourseName"

                android:layout_width="match_parent"

                android:layout_height="wrap_content"

                android:layout_margin="5dp"

                android:padding="5dp"

                android:text="Course Name "

                android:textColor="@color/black"

                android:textSize="18sp"

                android:textStyle="bold" />

 

            <LinearLayout

                android:layout_width="match_parent"

                android:layout_height="wrap_content"

                android:layout_margin="5dp"

                android:orientation="horizontal"

                android:weightSum="2">

 

                <TextView

                    android:id="@+id/idTVBatch"

                    android:layout_width="0dp"

                    android:layout_height="wrap_content"

                    android:layout_weight="1"

                    android:padding="5dp"

                    android:text="Batch"

                    android:textColor="@color/black" />

 

                <TextView

                    android:id="@+id/idTVTracks"

                    android:layout_width="0dp"

                    android:layout_height="wrap_content"

                    android:layout_weight="1"

                    android:padding="5dp"

                    android:text="Tracks"

                    android:textColor="@color/black" />

               

            </LinearLayout>

           

        </LinearLayout>

       

    </androidx.cardview.widget.CardView>

 

    <ProgressBar

        android:id="@+id/idLoadingPB"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_centerInParent="true"

        android:visibility="visible" />

     

</RelativeLayout>

Update MainActivity.java

import android.os.Bundle;

import android.view.View;

import android.widget.ImageView;

import android.widget.ProgressBar;

import android.widget.TextView;

import android.widget.Toast;

 

import androidx.appcompat.app.AppCompatActivity;

import androidx.cardview.widget.CardView;

 

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

import com.android.volley.toolbox.Volley;

import com.squareup.picasso.Picasso;

 

import org.json.JSONException;

import org.json.JSONObject;

 

public class MainActivity extends AppCompatActivity {

 

    // creating variables for our textview,

    // imageview,cardview and progressbar.

    private TextView courseNameTV, courseTracksTV, courseBatchTV;

    private ImageView courseIV;

    private ProgressBar loadingPB;

    private CardView courseCV;

     

    // below line is the variable for url from

    // where we will be querying our data.

    String url = "http://tutorial.razzi.my/android101/json/get/";

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

         

        // in below line we are initializing our all views.

        loadingPB = findViewById(R.id.idLoadingPB);

        courseCV = findViewById(R.id.idCVCourse);

        courseNameTV = findViewById(R.id.idTVCourseName);

        courseTracksTV = findViewById(R.id.idTVTracks);

        courseBatchTV = findViewById(R.id.idTVBatch);

        courseIV = findViewById(R.id.idIVCourse);

         

        // creating a new variable for our request queue

        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);

         

        // as our data is in json object format so we are using

        // json object request to make data request from our url.

        // in below line we are making a json object

        // request and creating a new json object request.

        // inside our json object request we are calling a

        // method to get the data, "url" from where we are

        // calling our data,"null" as we are not passing any data.

        // later on we are calling response listener method

        // to get the response from our API.

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

            @Override

            public void onResponse(JSONObject response) {

                // inside the on response method.

                // we are hiding our progress bar.

                loadingPB.setVisibility(View.GONE);

                 

                // in below line we are making our card

                // view visible after we get all the data.

                courseCV.setVisibility(View.VISIBLE);

                try {

                    // now we get our response from API in json object format.

                    // in below line we are extracting a string with its key

                    // value from our json object.

                    // similarly we are extracting all the strings from our json object.

                    String courseName = response.getString("courseName");

                    String courseTracks = response.getString("courseTracks");

                    String courseMode = response.getString("courseMode");

                    String courseImageURL = response.getString("courseimg");

                     

                    // after extracting all the data we are

                    // setting that data to all our views.

                    courseNameTV.setText(courseName);

                    courseTracksTV.setText(courseTracks);

                    courseBatchTV.setText(courseMode);

                     

                    // we are using picasso to load the image from url.

                    Picasso.get().load(courseImageURL).into(courseIV);

                } catch (JSONException e) {

                    // if we do not extract data from json object properly.

                    // below line of code is use to handle json exception

                    e.printStackTrace();

                }

            }

        }, new Response.ErrorListener() {

            // this is the error listener method which

            // we will call if we get any error from API.

            @Override

            public void onErrorResponse(VolleyError error) {

                // below line is use to display a toast message along with our error.

                Toast.makeText(MainActivity.this, "Fail to get data..", Toast.LENGTH_SHORT).show();

            }

        });

        // at last we are adding our json

        // object request to our request

        // queue to fetch all the json data.

        queue.add(jsonObjectRequest);

    }

}

Post JSON Data

Create new empty project volleyPostJson

Add library in Graddle Dependencies

// volley library

implementation ‘com.android.volley:volley:1.1.1’

Add INTERNET permission in AndroidManifest

<!--permissions for INTERNET-->

<uses-permission android:name="android.permission.INTERNET"/>

Update activity_main layout

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout

    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"

    android:orientation="vertical"

    tools:context=".MainActivity">

 

    <!--edit text field for adding name-->

    <EditText

        android:id="@+id/idEdtName"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_margin="10dp"

        android:layout_marginTop="40dp"

        android:hint="Enter your name" />

 

    <!--edit text for adding email-->

    <EditText

        android:id="@+id/idEdtEmail"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_margin="10dp"

        android:hint="Enter your email" />

 

    <!--button for adding data-->

    <Button

        android:id="@+id/idBtnPost"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_margin="20dp"

        android:text="Send Data to API"

        android:textAllCaps="false" />

 

    <!--text view for displaying our API response-->

    <TextView

        android:id="@+id/idTVResponse"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_margin="10dp"

        android:gravity="center_horizontal"

        android:text="Response"

        android:textAlignment="center"

        android:textSize="15sp" />

 

    <!--progress bar for loading -->

    <ProgressBar

        android:id="@+id/idLoadingPB"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_gravity="center"

        android:visibility="gone" />

 

</LinearLayout>

Update MainActivity.java

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.ProgressBar;

import android.widget.TextView;

import android.widget.Toast;

 

import androidx.appcompat.app.AppCompatActivity;

 

import com.android.volley.Request;

import com.android.volley.RequestQueue;

import com.android.volley.VolleyError;

import com.android.volley.toolbox.StringRequest;

import com.android.volley.toolbox.Volley;

 

import org.json.JSONException;

import org.json.JSONObject;

 

import java.util.HashMap;

import java.util.Map;

 

public class MainActivity extends AppCompatActivity {

 

    // creating variables for our edittext,

    // button, textview and progressbar.

    private EditText nameEdt, emailEdt;

    private Button postDataBtn;

    private TextView responseTV;

    private ProgressBar loadingPB;

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

         

        // initializing our views

        nameEdt = findViewById(R.id.idEdtName);

        emailEdt = findViewById(R.id.idEdtEmail);

        postDataBtn = findViewById(R.id.idBtnPost);

        responseTV = findViewById(R.id.idTVResponse);

        loadingPB = findViewById(R.id.idLoadingPB);

         

        // adding on click listener to our button.

        postDataBtn.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                // validating if the text field is empty or not.

                if (nameEdt.getText().toString().isEmpty() && emailEdt.getText().toString().isEmpty()) {

                    Toast.makeText(MainActivity.this, "Please enter both the values", Toast.LENGTH_SHORT).show();

                    return;

                }

                // calling a method to post the data and passing name and email.

                postDataUsingVolley(nameEdt.getText().toString(), emailEdt.getText().toString());

            }

        });

    }

 

    private void postDataUsingVolley(String name, String email) {

        // url to post data

        String url = "http://tutorial.razzi.my/android101/json/post/register.php";

        loadingPB.setVisibility(View.VISIBLE);

         

        // creating a new variable for request queue

        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);

         

        // calling a string

        // request method to post the data to API

        // i.e. calling a post method.

        StringRequest request = new StringRequest(Request.Method.POST, url, new com.android.volley.Response.Listener<String>() {

            @Override

            public void onResponse(String response) {

                // inside on response method we are

                // hiding our progress bar

                // and setting data to edit text as empty

                loadingPB.setVisibility(View.GONE);

                nameEdt.setText("");

                emailEdt.setText("");

                 

                // on below line we are displaying a success toast message.

                Toast.makeText(MainActivity.this, "Data added to API", Toast.LENGTH_SHORT).show();

                try {

                    // on below line we are parsing the response

                    // to json object to extract data from it.

                    JSONObject respObj = new JSONObject(response);

                     

                    // below are the strings which we

                    // extract from our json object.

                    String name = respObj.getString("name");

                    String email = respObj.getString("email");

                     

                    // setting the strings to text view.

                    responseTV.setText("Name : " + name + "\n" + "Email : " + email);

                } catch (JSONException e) {

                    e.printStackTrace();

                }

            }

        }, new com.android.volley.Response.ErrorListener() {

            @Override

            public void onErrorResponse(VolleyError error) {

                // method to handle errors.

                Toast.makeText(MainActivity.this, "Fail to get response = " + error, Toast.LENGTH_SHORT).show();

            }

        }) {

            @Override

            protected Map<String, String> getParams() {

                // below line we are creating a map for

                // storing our values in key and value pair.

                Map<String, String> params = new HashMap<String, String>();

                 

                // passing key

                // and value pair to parameters.

                params.put("name", name);

                params.put("email", email);

                 

                // returning params.

                return params;

            }

        };

        // make

        // a json object request.

        queue.add(request);

    }

}


index.php

-----

<?php

$output = '{"courseName":"Android Development","courseimg":"https://i.ibb.co/XZPvkqd/bookandroid.png","courseMode":"Online","courseTracks":"50 Tracks"}';
echo $output;

?>



register.php

-----

<?php

$myObj = new stdClass();

$myObj->name=$_POST["name"];

$myObj->email=$_POST["email"];

$myJSON = json_encode($myObj);

echo $myJSON;

?>



apply.html

-----

<form method="post" action="register.php">

    <input name="name" />

    <br/>

    <input name="email" />

    <br/>

    <button type="submit">OK</button>

</form>



.