Skip to main content

Volley Library in Android

What is Volley Library In Android 



Volley is used to call REST API under android application with better security and performance as compared to normal web requests.


Volley is also used to call multiple web services simultaneously using asynchronous call operation.


1)  Add volley library in  Project


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

2)  Mainfest internet permission

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

3)  Create POJO CLASS or Property Class

package com.example.webviewexample;

public class Hero {
String name, imageUrl;

public Hero(String name, String imageUrl) {
this.name = name;
this.imageUrl = imageUrl;
}

public String getName() {
return name;
}

public String getImageUrl() {
return imageUrl;
}
}


4)  Create CustomAdapter using LisViewAdapter

package com.example.webviewexample;

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

import java.util.List;

public class ListViewAdapter extends ArrayAdapter<Hero> {

//the hero list that will be displayed
private List<Hero> heroList;

//the context object
private Context mCtx;

//here we are getting the herolist and context
//so while creating the object of this adapter class we need to give herolist and context
public ListViewAdapter(List<Hero> heroList, Context mCtx) {
super(mCtx, R.layout.list_items, heroList);
this.heroList = heroList;
this.mCtx = mCtx;
}

//this method will return the list item
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//getting the layoutinflater
LayoutInflater inflater = LayoutInflater.from(mCtx);

//creating a view with our xml layout
View listViewItem = inflater.inflate(R.layout.list_items, null, true);

//getting text views
TextView textViewName = listViewItem.findViewById(R.id.textViewName);
TextView textViewImageUrl = listViewItem.findViewById(R.id.textViewImageUrl);

//Getting the hero for the specified position
Hero hero = heroList.get(position);

//setting hero values to textviews
textViewName.setText(hero.getName());
textViewImageUrl.setText(hero.getImageUrl());

//returning the listitem
return listViewItem;
}
}


5)

package com.example.webviewexample;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
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.ArrayList;
import java.util.List;

public class VolleyExample extends AppCompatActivity {

private static final String JSON_URL = "https://simplifiedcoding.net/demos/view-flipper/heroes.php";



//the hero list where we will store all the hero objects after parsing json
List<Hero> heroList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_volley_example);
listView = (ListView) findViewById(R.id.listView);
heroList = new ArrayList<>();

//this method will fetch and parse the data
loadHeroList();
}

private void loadHeroList() {
//getting the progressbar
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);

//making the progressbar visible
progressBar.setVisibility(View.VISIBLE);

//creating a string request to send request to the url
StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//hiding the progressbar after completion
progressBar.setVisibility(View.INVISIBLE);


try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);

//we have the array named hero inside the object
//so here we are getting that json array
JSONArray heroArray = obj.getJSONArray("heroes");

//now looping through all the elements of the json array
for (int i = 0; i < heroArray.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject heroObject = heroArray.getJSONObject(i);

//creating a hero object and giving them the values from json object
Hero hero = new Hero(heroObject.getString("name"), heroObject.getString("imageurl"));

//adding the hero to herolist
heroList.add(hero);
}

//creating custom adapter object
ListViewAdapter adapter = new ListViewAdapter(heroList, getApplicationContext());

//adding the adapter to listview
listView.setAdapter(adapter);

} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});

//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);

//adding the string request to request queue
requestQueue.add(stringRequest);
}
}





Layout File


<?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=".VolleyExample">

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

<ProgressBar
android:visibility="gone"
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />

</RelativeLayout>


7)   Design File
<?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:padding="16dp"
android:orientation="vertical">

<TextView
android:id="@+id/textViewName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />

<TextView
android:id="@+id/textViewImageUrl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autoLink="web"
android:textColor="#08308e" />

</LinearLayout>


Call Registration API using Volley Library?

Volley library provide simple approach to registartion page?


package com.example.webviewexample;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
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.ArrayList;
import java.util.List;

public class VolleyExample extends AppCompatActivity {

private static String JSON_URL = "https://shivaconceptsolution.com/webservices/reg.php";

//listview object
ListView listView;

//the hero list where we will store all the hero objects after parsing json
List<Hero> heroList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_volley_example);
listView = (ListView) findViewById(R.id.listView);
heroList = new ArrayList<>();

//this method will fetch and parse the data
loadHeroList();
}

private void loadHeroList() {
//getting the progressbar
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);

//making the progressbar visible
progressBar.setVisibility(View.VISIBLE);

//creating a string request to send request to the url
StringRequest stringRequest = new StringRequest(Request.Method.POST, JSON_URL+= "?name="+"check"+"&pwd="+"chk123"+"&email="+"chk@gmail.com",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//hiding the progressbar after completion
progressBar.setVisibility(View.INVISIBLE);


try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);

//we have the array named hero inside the object
//so here we are getting that json array
int st = obj.getInt("status");
if(st!=0)
{
Toast.makeText(getApplicationContext(),"Success", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),"Fail", Toast.LENGTH_SHORT).show();
}

} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});

//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);

//adding the string request to request queue
requestQueue.add(stringRequest);
}
}








   



Comments

Popular posts from this blog

Uncontrolled form input in React-JS

  Uncontrolled form input in React-JS? If we want to take input from users without any separate event handling then we can uncontrolled the data binding technique. The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM. Example of Uncontrolled Form Input:- import React from "react" ; export class Info extends React . Component {     constructor ( props )     {         super ( props );         this . fun = this . fun . bind ( this ); //event method binding         this . input = React . createRef ();...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...

JDBC using JSP and Servlet

JDBC means Java Database Connectivity ,It is intermediates from Application to database. JDBC has different type of divers and provides to communicate from database server. JDBC contain four different type of approach to communicate with Database Type 1:- JDBC-ODBC Driver Type2:- JDBC Vendor specific Type3 :- JDBC Network Specific Type4:- JDBC Client-Server based Driver  or JAVA thin driver:- Mostly we prefer Type 4 type of Driver to communicate with database server. Step for JDBC:- 1  Create Database using MYSQL ,ORACLE ,MS-SQL or any other database 2   Create Table using database server 3   Create Form according to database table 4  Submit Form and get form data into servlet 5  write JDBC Code:-     5.1)   import package    import java.sql.*     5.2)  Add JDBC Driver according to database ide tools     5.3)  call driver in program         ...