Skip to main content

Volley Library Example - Android Tutorial

What is Volley library exactly for?

Android volley is a networking library was introduced to make networking calls much easier, faster without writing tons of code. By default all the volley network calls works asynchronously, so we don’t have to worry about using asynctask anymore.


Advantages of using Volley:


  • Volley automatically schedule all network requests. It means that Volley will be taking care of all the network requests your app executes for fetching response or image from web.
  • Volley provides transparent disk and memory caching.
  • Volley provides powerful cancellation request API. It means that you can cancel a single request or you can set blocks or scopes of requests to cancel.
  • Volley provides powerful customization abilities.
  • Volley provides Debugging and tracing tools.

How to add Volley Library?

Open build.gradle located under your app module and add below dependencies.

compile 'com.mcxiaoke.volley:library:1.0.19'

After adding the dependencies Sync the project.

Now let’s see this in action by creating a new project.


1. Add dependencies


In this example, we gave request via Volley and got Images and Texts as a response.
To display Images in RecyclerView and CardView we have to add required dependencies, now it looks as,

build.gradle
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar']
compile 'com.android.support:appcompat-v7:23.1.0'
compile 'com.mcxiaoke.volley:library:1.0.19'
compile 'com.android.support:recyclerview-v7:23.1.1'
compile 'com.android.support:cardview-v7:23.1.1'
compile 'com.github.bumptech.glide:glide:3.7.0'
}

2. Open activity_main.xml and replace with the following

<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"
    tools:context="com.mrbrown.volley_sample.MainActivity">

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

3. Now create the new xml file to implement CardView, here used as card_view.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="1dp">
    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/card_view">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="5dp">
            <ImageView
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:id="@+id/person_photo"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:layout_marginRight="16dp" />
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/person_name"
                android:layout_toRightOf="@+id/person_photo"
                android:layout_alignParentTop="true" />
        </RelativeLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>

4. Open the MainActivity.java

There are 2 main classes:
1. Request queue
2. Request

Replace the MainActivity.java with the following


public class MainActivity extends AppCompatActivity {

    String JsonURL ="ENTER YOUR URL HERE";
    RequestQueue requestQueue;
    public static String TAG_IMAGE_URL = "Image";
    public static String TAG_CONTENT = "content";
    String strTesti;
    String strUrl;
    ArrayList<HashMap<String, String>> arraySend = new ArrayList<>();
    static ProgressDialog pDialog;
    private static RecyclerView recyclerView;
    private RecyclerView.LayoutManager m_LayoutManager;
    CustomAdapter customAdapter;

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

        //Request queue
        requestQueue = Volley.newRequestQueue(this);

        recyclerView = (RecyclerView)findViewById(R.id.idRecycler);
        recyclerView.setHasFixedSize(true);
        m_LayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(m_LayoutManager);

        //Request
        JsonArrayRequest arrreq = new JsonArrayRequest(Request.Method.GET, JsonURL,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        showDialog(MainActivity.this, "Loading");

                        try{
                            for (int i = 0; i < response.length(); i++) {
                                JSONObject nmcdata = response.getJSONObject(i);

                                strUrl = nmcdata.getString(TAG_IMAGE_URL);
                                strTesti = nmcdata.getString(TAG_CONTENT);

                                HashMap<String, String> objMap = new HashMap<>();
                                objMap.put(TAG_IMAGE_URL, strUrl);
                                objMap.put(TAG_CONTENT, strTesti);

                                arraySend.add(objMap);
                            }
                            dismissDialog();
                        } catch(  JSONException e){
                            e.printStackTrace();
                        }

                        if (arraySend.size() > 0) {
                            customAdapter = new CustomAdapter(MainActivity.this, arraySend, recyclerView);
                            recyclerView.setAdapter(customAdapter);

                        }
                    }
                },

        new Response.ErrorListener(){

            @Override
            public void onErrorResponse(VolleyError error) {
                dismissDialog();
                Log.e("error",error.toString());
            }
        }
        );
        requestQueue.add(arrreq);
    }

    public static void showDialog(Context mContext, String strMessage) {
        try {
            if (pDialog != null)
                if (pDialog.isShowing())
                    pDialog.dismiss();
            pDialog = ProgressDialog.show(mContext, "", strMessage, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void dismissDialog() {
        try {
            if (pDialog.isShowing())
                pDialog.dismiss();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

URL used here gave the response like this 


5. Create a new class CustomAdapter.java to set the images using Recycler View



public class CustomAdapter extends RecyclerView.Adapter{
    RecyclerView mrecyclerview;
    static Context context;
    ArrayList<HashMap<String, String>> Items = new ArrayList<>();

    public CustomAdapter(MainActivity context, ArrayList<HashMap<String, String>> arraySend, RecyclerView recyclerView) {
        this.context = context;
        mrecyclerview = recyclerView;
        Items = arraySend;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder vh;
        View itemLayoutView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_view, null);

        vh = new ViewHolder(itemLayoutView);
        return vh;
    }

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

        try {

            final HashMap<String, String> tempMap = Items.get(position);

            ((ViewHolder) holder).txtConten.setText(tempMap
                    .get(MainActivity.TAG_CONTENT));

            String urlImg = tempMap
                    .get(MainActivity.TAG_IMAGE_URL);
            Glide.with(context)
                    .load(urlImg)
                    .into(((ViewHolder) holder).imgUrl);

        }catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

    private class ViewHolder extends RecyclerView.ViewHolder {
        public TextView txtConten;
        ImageView imgUrl;
        CardView cardview;

        public ViewHolder(View itemLayoutView) {
            super(itemLayoutView);

            cardview = (CardView) itemLayoutView.findViewById(R.id.card_view);
            imgUrl = (ImageView) itemLayoutView.findViewById(R.id.person_photo);
            txtConten = (TextView) itemLayoutView.findViewById(R.id.person_name);

        }
    }
}

6. Give permissions in Manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Now run the application and get the response output as,
__________________________________________________________________
Source code for Volley Library.zip

Happy Coding...



Comments

Popular posts from this blog

Get Phone Number from Contact List - Android Tutorial

When you create an application to send sms or an application to make calls, getting a destination number from the contacts list is a common task. In this Android tip, I am going to show the code to fetch a number from the contacts list. Now let me tell you how to achieve the goal. First, you need to create an Intent object for the PICK_ACTION action. To open the contacts list, the table that contains the contacts information must be specified as a parameter of the constructor of the Intent class. You can refer to the table using ContactsContract.Contacts.CONTENT_URI. Then call the startActivityForResult () method passing the Intent object and request code to open the contacts list. After a contact is selected from the contacts list, to get the result, you need to override the onActivityResult(int reqCode, int resultCode, Intent data) method of the activity. You can call the getData() method of the data parameter to get the table or uri that contains the selected contact. From the t

Spinner with Search on DropDown - Android Tutorial

If you have more values on Dropdown of Spinner its hard to select the last item by making a long scroll. To overcome this issue Android introduced a component called  AutoCompleteTextView Yes it is!!! Then why Spinner with Search? There may be some requirement even though gave much knowledge about it. There is a simple and good library that helps us to achieve this -  SearchableSpinner Gradle dependencies {     ...     implementation 'com.toptoche.searchablespinner:searchablespinnerlibrary:1.3.1' } Usage Now replace your Normal Android Spinner on XML with the following < com.toptoche.searchablespinnerlibrary.SearchableSpinner     android:id="@+id/id_city"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:background="@android:color/transparent"     android:padding="5dp" /> ___________________________________________________________

Set Focus on Spinner when select Item on Vertical Scroll - Android Tutorial

We may face an issue on Spinner lies on long vertical scroll, (i.e.) when selected and item from dropdown the focus moves to top of scroll. To avoid this please follow this piece of code spinner.setFocusableInTouchMode( true ); spinner.setOnFocusChangeListener( new View.OnFocusChangeListener() {     @Override     public void onFocusChange(View v, boolean hasFocus) {         if (hasFocus) {             if (spinner.getWindowToken() != null ) {                 spinner.performClick();             }         }     } });   _______________________________________________________________________________ Happy Coding...