Headertab

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Wednesday 23 March 2016

Volley integration

Hi friends today we are learn about how to use Volley in android .this is a best approach for android api networking.

Before use Volley we know about What is volley and Why use this???

Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster. Volley is available through the open AOSP repository.
Volley offers the following benefits:

  • Automatic scheduling of network requests.
  • Multiple concurrent network connections.
  • Transparent disk and memory response caching with standard HTTP cache coherence.
  • Support for request prioritization.
  • Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel.
  • Ease of customization, for example, for retry and backoff.
  • Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network.
  • Debugging and tracing tools.

Now make a new android project and follow instructions 
I am doing very easy coding for understanding beginner and also experts  developers.

ActivityMain.java

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.samset.volleyintegration.R;
import com.samset.volleyintegration.adapter.RecyclerAdapter;
import com.samset.volleyintegration.model.Actor;
import com.samset.volleyintegration.model.DataModel;
import com.samset.volleyintegration.network.GsonRequest;
import com.samset.volleyintegration.network.VolleySingleton;
import com.samset.volleyintegration.utils.Utilities;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private Activity activity;
   private RecyclerView recyclerView;
    private LinearLayoutManager layoutManager;
    private RecyclerAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        activity = this;
        recyclerView= (RecyclerView) findViewById(R.id.recyclerview);
        if (Utilities.isConnected(this)) {
            callApiGson();
        } else {
            Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
        }

    }

    //set data in RecyclerView
   
private void setRecyclerView(List<Actor> data)
    {
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new RecyclerAdapter(this, data);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    public void callApiGson() {
    /*
      * In first line you pass input parameter like GsonRequest<YourParentModelclass> and in parameter which type of your api like POST/GET
      * and pass your URL and pass your ParentModel class and pass Successlistener and errorlisteners */

       
GsonRequest<DataModel> jsonRequest = new GsonRequest<DataModel>(Request.Method.GET,
                Utilities.URL, DataModel.class, successListener(), errorListener());

        /*
        * In second code is define when you call api and take more time responce then your api auto recall by setRetryPolicy*/

       
jsonRequest.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        /*
        * Bind your api in own volley queue */

       
VolleySingleton.getInstance(activity).addToRequestQueue(jsonRequest, "firstApi");


        /*
        * Show progress bar when call your api*/

       
Utilities.showProgressDialog(activity, "Loading..");
        //Log.e("MYPostDetails", " new url api " + strData);

   
}

    public Response.Listener successListener() {
        return new Response.Listener<DataModel>() {
            @Override
            public void onResponse(final DataModel response) {
                //Check your responce is null or not......This is prevent app crash
               
if (response != null) {

                    Utilities.dismissDialog();

                    // get all data in list
                   
List<Actor> data=response.getActors();

                    // set data in recyclerview method
                   
setRecyclerView(data);
                    Log.e("MainActivity", " Responce Success " + response.getActors().size());

                }
            }
        };
    }

    public Response.ErrorListener errorListener() {
        return new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //This code handle all expectd come volley errors
               
Utilities.handleVolleyError(error);

            }
        };

    }
}


activity_main.xml

<?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="wrap_content"
    tools:context=".activities.MainActivity">

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

</RelativeLayout>

RecyclerAdapter.java


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

import com.samset.volleyintegration.BaseApplication;
import com.samset.volleyintegration.R;
import com.samset.volleyintegration.model.Actor;
import com.samset.volleyintegration.model.DataModel;

import java.util.HashSet;
import java.util.List;

/**
 * Created by samset on 23/03/16.
 */
public class RecyclerAdapter  extends RecyclerView.Adapter<RecyclerAdapter.MyHolder> {
    Context context;
    List<Actor> itemList;
    String strDomain;
    public RecyclerAdapter(Context contectxxt, List<Actor> item) {
        this.context = contectxxt;
        this.itemList = item;


    }


    @Override
    public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        MyHolder holder = null;
        View v = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.list_item, parent, false);
        holder = new MyHolder(v);

        return holder;

    }


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

        Actor actor=itemList.get(position);
        String imgUrl=actor.getImage();

        //download image from server to using picasso
       
BaseApplication.picasso.load(imgUrl).placeholder(R.mipmap.ic_launcher).resize(100,100).error(R.mipmap.ic_launcher).into(holder.img);
        holder.name.setText(actor.getName());
        holder.dob.setText(actor.getDob());
        holder.country.setText(actor.getCountry());

    }


    @Override
    public int getItemCount() {

        if (itemList == null || itemList.size() == 0) {
            return 0;
        }

        // +1 for loader
       
return itemList.size();

    }

    public static class MyHolder extends RecyclerView.ViewHolder {
        public TextView name;
        public TextView dob;
        public TextView country;
        public ImageView img;


        public MyHolder(View itemView) {
            super(itemView);

            name = (TextView) itemView.findViewById(R.id.name);
            dob = (TextView) itemView.findViewById(R.id.dob);
            country = (TextView) itemView.findViewById(R.id.country);
            img = (ImageView) itemView.findViewById(R.id.img);



        }
    }


item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <RelativeLayout
        android:padding="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:layout_margin="10dp"
            android:id="@+id/img"
            android:scaleType="center"
            android:src="@mipmap/ic_launcher"
            android:layout_width="100dp"
            android:layout_height="100dp" />
        <LinearLayout
            android:orientation="vertical"
            android:layout_toRightOf="@+id/img"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/name"
                android:padding="5dp"
                android:text="Actor Name"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <TextView
                android:id="@+id/dob"
                android:padding="5dp"
                android:text="Actor Dob"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <TextView
                android:id="@+id/country"
                android:text="Actor Country"
                android:padding="5dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />


        </LinearLayout>


    </RelativeLayout>
</LinearLayout>

Thank you 
I hope this is helps you 

Full Source code here 


Live Sample











No comments:

Post a Comment