Retrieve Data From Server in Android using Volley – EasyTechSolutions

Posted by

Hello everyone and welcome to easytechsolutions one place for all your queries, In today’s post we are going to implement Fetching Data from Server using Volley library in Android.

So without further due let’s get started implementing this :-

Steps you need to do:-



Step 1:- Open up Android Studio and make a new project name it whatever you want and select blank Activity and you are ready to go.

Step 2:- Open Gradle Scripts/build.gradle(Module:app) and inside Dependencies section add below dependencies and sync your project :-

build.gradle(Module:app)

compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.volley:volley:1.0.0'
compile 'com.squareup.picasso:picasso:2.5.2'

Note that we added CardView , RecyclerView , Volley and Picasso Dependencies because we need this dependencies to use inside our app.

Step 3:- Open up res/layout/main_activity.xml and paste the below code in it:-

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"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    tools:context="com.androidinterviewprepration.MainActivity">

  <android.support.v7.widget.RecyclerView
      android:id="@+id/recyclerview1"
      android:layout_width="match_parent"
      android:layout_height="wrap_content">

  </android.support.v7.widget.RecyclerView>

</LinearLayout>

Now we added RecyclerView in our layout now time to add CardView in layout and make a structue of how our data will look like

Step 4:- Make a new Layout file inside res/layout/item_list.xml and paste below code in it:-

item_list.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"
    android:orientation="vertical"
    android:layout_marginTop="16dp"
    android:layout_marginRight="16dp"
    android:layout_marginBottom="16dp"
    android:layout_marginLeft="16dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:id="@+id/cardview1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        app:cardCornerRadius="10dp">

        <LinearLayout
            android:id="@+id/linearlayout1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            >

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

        <TextView
            android:id="@+id/description"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="realname"
            />

            <TextView
                android:id="@+id/team"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="team"/>

            <TextView
                android:id="@+id/first"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="firstappearance"/>

            <TextView
                android:id="@+id/created"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="createdby"/>

            <TextView
                android:id="@+id/publisher"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="publisher"/>

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/image1"/>

            <TextView
                android:id="@+id/bio1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="bio" />


        </LinearLayout>
    </android.support.v7.widget.CardView>

</LinearLayout>

This above is the skeleton which show how in which sequence our data will come inside our app

Step 5:- Now as we make RecyclerView as well as CardView layout now its time to make a Java Modal class which will get data from Server and pass into Adapter which we will make next , So inside Package folder make a new class name it ListItem.java and paste below code in it :-

ListItem.java

package com.androidinterviewprepration;

/**
 * Created by AJAY THAKUR on 9/1/2017.
 */

public class ListItem {

    private String head;
    private String desc;
    private String team;
    private String firstappearance;
    private String createdby;
    private String publisher;
    private String imageUrl;
    private String bio;

    public ListItem(String head, String desc, String team, String firstappearance, String createdby, String publisher, String imageUrl, String bio) {
        this.head = head;
        this.desc = desc;
        this.team = team;
        this.firstappearance = firstappearance;
        this.createdby = createdby;
        this.publisher = publisher;
        this.imageUrl = imageUrl;
        this.bio = bio;
    }

    public String getHead() {
        return head;
    }

    public String getDesc() {
        return desc;
    }

    public String getTeam() {
        return team;
    }

    public String getFirstappearance() {
        return firstappearance;
    }

    public String getCreatedby() {
        return createdby;
    }

    public String getPublisher() {
        return publisher;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public String getBio() {
        return bio;
    }
}

Step 5:- Now we are going to Make an Adapter class in which we are going to Inflate custom layout , Binding Data and also View Data so make MyAdapter.java class and paste below code in it :-

MyAdapter.java

package com.androidinterviewprepration;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import java.util.List;

/**
 * Created by AJAY THAKUR on 9/1/2017.
 */

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    private List<ListItem> listItems;
    private Context context;

    public MyAdapter(List<ListItem> listItems, Context context) {
        this.listItems = listItems;
        this.context = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_list, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        final ListItem listItem = listItems.get(position);
        holder.textViewHead.setText(listItem.getHead());
        holder.textViewDesc.setText(listItem.getDesc());
        holder.team.setText(listItem.getTeam());
        holder.firstAppearance.setText(listItem.getFirstappearance());
        holder.createdBy.setText(listItem.getCreatedby());
        holder.publisher.setText(listItem.getPublisher());

        Picasso.with(context)
                .load(listItem.getImageUrl())
                .into(holder.imageView);
        holder.biography.setText(listItem.getBio());

        //Setting OnClickListner on Views:-

        holder.linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context, "You Clicked on "+ listItem.getHead(), Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    public int getItemCount() {
        return listItems.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        public TextView textViewHead;
        public TextView textViewDesc;
        public TextView team;
        public TextView firstAppearance;
        public TextView createdBy;
        public TextView publisher;
        public TextView biography;
        public ImageView imageView;
        public LinearLayout linearLayout;

        public ViewHolder(View itemView) {
            super(itemView);
            context = itemView.getContext();

            textViewHead = (TextView) itemView.findViewById(R.id.heading);
            textViewDesc = (TextView) itemView.findViewById(R.id.description);
            team = (TextView) itemView.findViewById(R.id.team);
            firstAppearance = (TextView) itemView.findViewById(R.id.first);
            createdBy = (TextView) itemView.findViewById(R.id.created);
            publisher = (TextView) itemView.findViewById(R.id.publisher);
            biography = (TextView) itemView.findViewById(R.id.bio1);
            imageView = (ImageView) itemView.findViewById(R.id.image1);
            linearLayout = (LinearLayout) itemView.findViewById(R.id.linearlayout1);
        }

    }
}

Step 6:- Now open up MainActivity.java file and paste below code in it:-

MainActivity.java

package com.androidinterviewprepration;

import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.LinearLayout;

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;

import static android.R.attr.data;
import static android.provider.ContactsContract.CommonDataKinds.Website.URL;

public class MainActivity extends AppCompatActivity {

    //Defining Varibales:-
    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;

    //Defining JSON Data url link:-
    private static final String URL_DATA = "https://simplifiedcoding.net/demos/marvel/";

    //Defining List variable:-
    private List<ListItem> listItems;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Finding ViewById:-
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        //Initializing list object:-
        listItems = new ArrayList<>();

        loadRecyclerViewData();
    }

     private void loadRecyclerViewData(){

        //Setting ProgressDialog which will show while data is loading from server:-
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Loading Data....");
        progressDialog.show();

         //Request type Defining:-
         StringRequest stringRequest = new StringRequest(Request.Method.GET,
                 URL_DATA,
                 new Response.Listener<String>() {
                     @Override
                     public void onResponse(String response) {
                         //Dismissing ProgressDialog:-
                         progressDialog.dismiss();

                         //Here we define JSON object and array which will help to fetch data:
                         try {
                             //JSONObject jsonObject = new JSONObject(response);
                             JSONArray array = new JSONArray(response);

                             //Looping to fetch all data inside the array:-
                             for(int i=0; i<array.length(); i++){
                                 JSONObject o = array.getJSONObject(i);
                                 ListItem item = new ListItem(
                                         o.getString("name"),
                                         o.getString("realname"),
                                         o.getString("team"),
                                         o.getString("firstappearance"),
                                         o.getString("createdby"),
                                         o.getString("publisher"),
                                         o.getString("imageurl"),
                                         o.getString("bio")
                                 );
                                 listItems.add(item);
                             }

                             //Now Making Adapter object and Setting Adapter object in RecyclerView:-
                             adapter = new MyAdapter(listItems,getApplicationContext());
                             recyclerView.setAdapter(adapter);

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

                     }
                 },
                 new Response.ErrorListener() {
                     @Override
                     public void onErrorResponse(VolleyError error) {

                     }
                 });

         //To Request above response we will create a RequestQueue:-
         RequestQueue requestQueue = Volley.newRequestQueue(this);
         requestQueue.add(stringRequest);
    }
}

Now just save above code and run it and you will get to see server fetched data inside your android app


Note:- Useful links to go through :-

1.Picasso http://square.github.io/picasso/
2.Volley https://bintray.com/android/android-utils/com.android.volley.volley

Leave a Reply

Your email address will not be published. Required fields are marked *