Android Volley JsonObject Request Custom Adapter As BaseAdapter With Arraylist And Model Class

  1. Main Activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <Button
        android:text="Show Data"
        android:id="@+id/showbtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></ListView>


</LinearLayout>


2. mylist.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">
<TextView
    android:id="@+id/EmployeeID"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

    <TextView
    android:id="@+id/LastName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

    <TextView
    android:id="@+id/FirstName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
</LinearLayout>

3. Employee.java

package com.example.ppc.jsonarraycustomlistview;

public class Employee {


    String fname;
    String lname;

    public Employee() {
    }

    public Employee( String fname, String lname) {

        this.fname = fname;
        this.lname = lname;
    }



    public String getFname() {
        return fname;
    }

    public String getLname() {
        return lname;
    }


    public void setFname(String fname) {
        this.fname = fname;
    }

    public void setLname(String lname) {
        this.lname = lname;
    }
}

4. CustomAdapter.JAVA

package com.example.ppc.jsonarraycustomlistview;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class CustomAdapter extends BaseAdapter {
    private Context context;
private ArrayList<Employee> mylist;

    public CustomAdapter(Context context, ArrayList<Employee> mylist) {
        this.context = context;
        this.mylist = mylist;
    }

    @Override
    public int getCount() {
        return mylist.size();
    }

    @Override
    public Object getItem(int position) {
        return mylist.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view= layoutInflater.inflate(R.layout.mylist,null);
        TextView firstname = view.findViewById(R.id.FirstName);
        TextView lastname = view.findViewById(R.id.LastName);
        firstname.setText(mylist.get(position).fname);
        lastname.setText(mylist.get(position).lname);
        return view;
    }
}

5. AndroidManifest.xml Only Need Internet permission

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ppc.jsonarraycustomlistview">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

6. Add Volley Library

   implementation 'com.android.volley:volley:1.1.1'

7. MainActivity.java

package com.example.ppc.jsonarraycustomlistview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

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.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
private ListView listView;
private Button button;
private ArrayList<Employee> mylist = new ArrayList<Employee>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = findViewById(R.id.list);
        button = findViewById(R.id.showbtn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
String url = "https://api.myjson.com/bins/1b9qi3";
                JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        for(int i = 0;i<response.length();i++){
                            try {
                                JSONObject jsonObject = response.getJSONObject(i);
                                String fstname = (String) jsonObject.get("FirstName");
                                String lstname = (String) jsonObject.get("LastName");
                               mylist.add(new Employee(fstname,lstname));

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                        CustomAdapter  customAdapter = new CustomAdapter(MainActivity.this,mylist);
                        listView.setAdapter(customAdapter);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
                    requestQueue.add(jsonArrayRequest);

            }
        });


    }
}

Android Volley Json Object Data Show To List View Using Array Adapter

  1. Step 1: Add Volley Library To App Level Module.app Gradle File Like Below Way
   implementation 'com.android.volley:volley:1.1.1'

2. Step 2 : Add Internet Permission To Android Manifest File .

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

3. Step 3. Add List View And A Data Show Button To Activity_main.xml File .

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <Button
        android:text="Show Data"
        android:id="@+id/showbtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></ListView>

</LinearLayout>

Step 4: In MainActivity.java File Find List View And Button And Set Onclicklisener To Button And Work Like Below Way.

package com.example.ppc.jsonarraycustomlistview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

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.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
private ListView listView;
private Button button;
private ArrayList<String> mylist = new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = findViewById(R.id.list);
        button = findViewById(R.id.showbtn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
String url = "https://api.myjson.com/bins/1b9qi3";
                JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        for(int i = 0;i<response.length();i++){
                            try {
                                JSONObject jsonObject = response.getJSONObject(i);
                                String fstname = (String) jsonObject.get("FirstName");
                               mylist.add(fstname);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                        ArrayAdapter <String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,mylist);
                        listView.setAdapter(adapter);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
                    requestQueue.add(jsonArrayRequest);

            }
        });


    }
}

My Json Data On Server Like this

[
  {
    "EmployeeID": 1,
    "LastName": "Davolio",
    "FirstName": "Nancy",
    "Address": "507 - 20th Ave. E. Apt. 2A",
    "City": "Seattle",
    "Region": "WA",
    "PostalCode": "98122",
    "Country": "USA",
    "HomePhone": "(206) 555-9857",
    "ResumeID": 1,
    "Resume": {
      "__deferred": {
        "uri": "/here/goes/your/serviceUrl/Employees(1)/Resume"
      }
    }
  },
  {
    "EmployeeID": 2,
    "LastName": "Fuller",
    "FirstName": "Andrew",
    "Address": "908 W. Capital Way",
    "City": "Tacoma",
    "Region": "WA",
    "PostalCode": "98401",
    "Country": "USA",
    "HomePhone": "(206) 555-9482",
    "ResumeID": 2,
    "Resume": {
      "__deferred": {
        "uri": "/here/goes/your/serviceUrl/Employees(2)/Resume"
      }
    }
  },
  {
    "EmployeeID": 3,
    "LastName": "Leverling",
    "FirstName": "Janet",
    "Address": "722 Moss Bay Blvd.",
    "City": "Kirkland",
    "Region": "WA",
    "PostalCode": "98033",
    "Country": "USA",
    "HomePhone": "(206) 555-3412",
    "ResumeID": 3,
    "Resume": {
      "__deferred": {
        "uri": "/here/goes/your/serviceUrl/Employees(3)/Resume"
      }
    }
  },
  {
    "EmployeeID": 4,
    "LastName": "Peacock",
    "FirstName": "Margaret",
    "Address": "4110 Old Redmond Rd.",
    "City": "Redmond",
    "Region": "WA",
    "PostalCode": "98052",
    "Country": "USA",
    "HomePhone": "(206) 555-8122",
    "ResumeID": 4,
    "Resume": {
      "__deferred": {
        "uri": "/here/goes/your/serviceUrl/Employees(4)/Resume"
      }
    }
  },
  {
    "EmployeeID": 5,
    "LastName": "Buchanan",
    "FirstName": "Steven",
    "Address": "14 Garrett Hill",
    "City": "London",
    "Region": null,
    "PostalCode": "SW1 8JR",
    "Country": "UK",
    "HomePhone": "(71) 555-4848",
    "ResumeID": 5,
    "Resume": {
      "__deferred": {
        "uri": "/here/goes/your/serviceUrl/Employees(5)/Resume"
      }
    }
  },
  {
    "EmployeeID": 6,
    "LastName": "Suyama",
    "FirstName": "Michael",
    "Address": "Coventry House Miner Rd.",
    "City": "London",
    "Region": null,
    "PostalCode": "EC2 7JR",
    "Country": "UK",
    "HomePhone": "(71) 555-7773",
    "ResumeID": 6,
    "Resume": {
      "__deferred": {
        "uri": "/here/goes/your/serviceUrl/Employees(6)/Resume"
      }
    }
  },
  {
    "EmployeeID": 7,
    "LastName": "King",
    "FirstName": "Robert",
    "Address": "Edgeham Hollow Winchester Way",
    "City": "London",
    "Region": null,
    "PostalCode": "RG1 9SP",
    "Country": "UK",
    "HomePhone": "(71) 555-5598",
    "ResumeID": 7,
    "Resume": {
      "__deferred": {
        "uri": "/here/goes/your/serviceUrl/Employees(7)/Resume"
      }
    }
  },
  {
    "EmployeeID": 8,
    "LastName": "Callahan",
    "FirstName": "Laura",
    "Address": "4726 - 11th Ave. N.E.",
    "City": "Seattle",
    "Region": "WA",
    "PostalCode": "98105",
    "Country": "USA",
    "HomePhone": "(206) 555-1189",
    "ResumeID": 8,
    "Resume": {
      "__deferred": {
        "uri": "/here/goes/your/serviceUrl/Employees(8)/Resume"
      }
    }
  },
  {
    "EmployeeID": 9,
    "LastName": "Dodsworth",
    "FirstName": "Anne",
    "Address": "7 Houndstooth Rd.",
    "City": "London",
    "Region": null,
    "PostalCode": "WG2 7LT",
    "Country": "UK",
    "HomePhone": "(71) 555-4444",
    "ResumeID": 9,
    "Resume": {
      "__deferred": {
        "uri": "/here/goes/your/serviceUrl/Employees(9)/Resume"
      }
    }
  }
]

ANDROID PHP MYSQL WITH Volley Library

In this tutorial, you will learn how to populate MySQL database using POST request method. You will also learn the utilization of the Volley Library in Android.

Introduction to Volley

The Volley is a modern HTTP networking library for Android which provides a faster and an easier way of communication with the web server for data synchronization.

How it Works?

In Android, the Volley library makes a request to the web server for data synchronization. It is similar to the three-way handshake; the Android application makes some HTTP request, and the server sends some response in return.

Getting Started with Volley

As we want to send some data to the webserver using POST request and store the data in MySQL. So the first thing you will need is MySQL Database on the web server.

There are multiple free web servers available. Hostinger.co.uk provides the best free domains and hosting, but unfortunately, it is not providing its services in Pakistan. Many of you think of going toward the base.pk for free domain and hosting. I suggest you not to use base.pk as it generates an unknown JavaScript error. It may waste a lot of your time. This JavaScript error is generated due to Ads as well as some data parsing which comes as a response from the web server. A better option is to buy your domain and hosting to save time.

Creating MySQL Database

After logging into your hosting CPanel, find and open MySQL Databases and create a new database as required. Also, set up and assign a privileged user to perform operations on the database.

Create and assign users to the database
Create and assign users to the database

Now add tables to the database and add columns/fields to the tables in MySQL from phpMyAdmin. 

Add Columns to MySQL Database
Add Columns to MySQL Database

Create a Database Connection File

You have successfully created the database. You need a PHP connection file which will help you to connect to the database to perform CRUD operations.

dbConnect.php

1234567

Right now you need the insertion of data in MySQL so only implement the Insert operation in a separate file which checks whether the requested method is a post method or not. If the requested method is POST, it gets the variables from the request and updates them in the database.

DatabaseConnection.php

 <?php
     define('HOST','localhost'); // Here Your Host Name Or Url
     define('USER','database_username'); // Here Your Host Database server User Name
     define('PASS','database_password'); // Here Your Host Database server Password    define('DB','database_name');
 
     $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');

insertData.php

<?php    require_once('dbConnect.php');     if($_SERVER['REQUEST_METHOD']=='POST'){        $username = $_POST['username'];        $email = $_POST['email'];                   $get_result = $con->query("INSERT INTO user(username,email) VALUES ('$username','$email')");          if($get_result === true){        echo "Successfully Registered";        }else{        echo $username."Not Registered";        }    }else{        echo 'error';    }?>
123456789101112131415161718

You have completed with the server side configurations; The directory path on the server for the insertData.php will act as the responder for the requests from Android application, as it checks the request method and executes the server side query for data insertion in the database. In my case the URL is

http://oleetech.com/android/insertData.php

Keep in mind that if your website has SSL certificate even then you must keep the URL http://example.com/insertData.php. Otherwise, it will generate the error.

Now move toward the Android Application.

Populate MySQL from Android Application using Volley

Before you start building the components of Android application, you must configure Volley library and its dependencies immediately after creating your Android application.

Adding Internet Permissions to Android Application

In the AndroidManifest.xml file, place the <uses-permission /> self closing tag between the <manifest> </manifest> tags, add internet permission.

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

 Including Volley Library to Android Application

Open the build.gradle (Module: App) add a dependency for Volley Library, inside dependencies block place a Volley library compile code.

compile 'com.mcxiaoke.volley:library-aar:1.0.0'

The complete dependencies code will be.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.1.0'
    compile 'com.mcxiaoke.volley:library-aar:1.0.0'
}

You have setup Volley, Sync Project to synchronize your build.gradle file with your project.

Setup User Interface for Getting Data from the User

Create the required User; I took username and email address as an example to send two Strings as a POST request.

Create text fields as required and a button to send the POST request for saving data in MySql.

Volley Project TextFields and Button
Volley Project TextFields and Button

The Complete Code for User Interface of Volley Project

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.muneeb.volleyproject.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Name"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="99dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Email"
        android:id="@+id/textView2"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="46dp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/username"
        android:layout_alignTop="@+id/textView"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_toRightOf="@+id/textView"
        android:layout_toEndOf="@+id/textView" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:id="@+id/useremail"
        android:layout_alignTop="@+id/textView2"
        android:layout_alignRight="@+id/username"
        android:layout_alignEnd="@+id/username"
        android:layout_toRightOf="@+id/textView"
        android:layout_toEndOf="@+id/textView" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Register Data"
        android:id="@+id/button"
        android:layout_below="@+id/useremail"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="96dp"
        android:onClick="SendData"/>
</RelativeLayout>

Implement the onClick method for the button

public void SendData(View v){}

Use private static final fields for the URL and the column names as these fields must not change throughout the project.

I declared username and email as the column/fields name. So, I will declare URL, USERNAME and USEREMAIL as public static final with the class level scope.

private static final String URL = "http://beginnersheap.com/android/insertData.php";
public static final String USERNAME = "username";
public static final String USEREMAIL = "email";

Get Data From Text Fields

Before moving further you must get the values from the text fields which user entered.

Request Methods

final EditText userName=(EditText) findViewById(R.id.username);
final EditText userEmail=(EditText) findViewById(R.id.useremail);
final String username = userName.getText().toString().trim();
final String email = userEmail.getText().toString().trim();

Create a StringRequest listener which will override onResponse() and onErrorResponse() methods along with getParams() method which return a HashMap containing key-value pair.

          StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println(response);
                        Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
                    }
                },
                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(USEREMAIL, email);
                return params;
            }

        };

onResponse() method will returns the response from the web server and onErrorResponse() method will return the Volley errors.

Generate Requests and Add Request to the Queue

Generate the requests and add to RequestQueue

RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
Working Volley Library POST Request
Working Volley Library POST Request

These user credentials will be saved into MySQL database.

Data from Android in MySQL
Data from Android in MySQL

Complete Code for ActivityMain.java

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667package com.example.muneeb.volleyproject; import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;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 java.util.HashMap;import java.util.Map; public class MainActivity extends AppCompatActivity {     private static final String URL = “http://beginnersheap.com/android/insertData.php&#8221;;    public static final String USERNAME = “username”;    public static final String USEREMAIL = “email”;     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }      public void SendData(View v)    {        final EditText userName=(EditText) findViewById(R.id.username);        final EditText userEmail=(EditText) findViewById(R.id.useremail);        final String username = userName.getText().toString().trim();        final String email = userEmail.getText().toString().trim();         StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,                new Response.Listener<String>() {                    @Override                    public void onResponse(String response) {                        System.out.println(response);                        Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();                    }                },                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(USEREMAIL, email);                return params;            }         };         RequestQueue requestQueue = Volley.newRequestQueue(this);        requestQueue.add(stringRequest);    } }