Skip to content

Instantly share code, notes, and snippets.

@ajaykumar2017
Last active May 30, 2019 05:34
Show Gist options
  • Save ajaykumar2017/e6cba3f8d95e933d1184bf9d3ba49efb to your computer and use it in GitHub Desktop.
Save ajaykumar2017/e6cba3f8d95e933d1184bf9d3ba49efb to your computer and use it in GitHub Desktop.
RecyclerView, Volley and Picasso
<?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=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/darker_gray" />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tecent.recyclerviewjsonexample">
<uses-permission android:name="android.permission.INTERNET" />
<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>
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:cardCornerRadius="8dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<ImageView
android:id="@+id/image_view"
android:layout_width="match_parent"
android:layout_height="200dp"
android:src="@mipmap/ic_launcher" />
<TextView
android:id="@+id/text_view_creator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Creater Name"
android:textColor="@android:color/black"
android:textSize="20sp" />
<TextView
android:id="@+id/text_view_likes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Like:" />
</LinearLayout>
</android.support.v7.widget.CardView>
package com.tecent.recyclerviewjsonexample;
import android.content.Context;
import android.support.annotation.NonNull;
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.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class ExampleAdapter extends RecyclerView.Adapter {
private Context mContext;
private ArrayList mExampleList;
public ExampleAdapter(Context context, ArrayList exampleList) {
mContext = context;
mExampleList = exampleList;
}
@NonNull
@Override
public ExampleViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(mContext).inflate(R.layout.example_item, viewGroup, false);
return new ExampleViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull ExampleViewHolder exampleViewHolder, int position) {
ExampleItem currentItem = mExampleList.get(position);
String imageUrl = currentItem.getmImageUrl();
String creatorName = currentItem.getCreator();
int likeCount = currentItem.getLikesCount();
exampleViewHolder.mTextViewCreator.setText(creatorName);
exampleViewHolder.mTextViewlikes.setText("Likes: " + likeCount);
Picasso.with(mContext).load(imageUrl).fit().centerInside().into(exampleViewHolder.mImageView);
}
@Override
public int getItemCount() {
return mExampleList.size();
}
public class ExampleViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public TextView mTextViewCreator;
public TextView mTextViewlikes;
public ExampleViewHolder(@NonNull View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.image_view);
mTextViewCreator = itemView.findViewById(R.id.text_view_creator);
mTextViewlikes = itemView.findViewById(R.id.text_view_likes);
}
}
}
package com.tecent.recyclerviewjsonexample;
public class ExampleItem {
private String mImageUrl;
private String mCreator;
private int mLikes;
public ExampleItem(String imageUrl, String creator, int likes) {
mImageUrl = imageUrl;
mCreator = creator;
mLikes = likes;
}
public String getmImageUrl() {
return mImageUrl;
}
public String getCreator() {
return mCreator;
}
public int getLikesCount() {
return mLikes;
}
}
package com.tecent.recyclerviewjsonexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
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.JsonObjectRequest;
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 RecyclerView mRecyclerView;
private ExampleAdapter mExampleAdapter;
private ArrayList mExampleList;
private RequestQueue mRequestQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mExampleList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON() {
String url = "https://pixabay.com/api/?key=12210473-92fa288f3823f1d930c2d918e&q=kitten&image_type=photo&pretty=true";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("hits");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
String creatorName = hit.getString("user");
String imageUrl = hit.getString("webformatURL");
int likeCount = hit.getInt("likes");
mExampleList.add(new ExampleItem(imageUrl, creatorName, likeCount));
}
mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
}
In this tutorial I am going to talk about RecyclerView, Volley and Picasso
RecyclerView:- RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible construction of any lists with XML layouts as an item which can be customized vastly while improving on the efficiency of ListViews and GridViews. This improvement is achieved by recycling the views which are out of the visibility of the user. For example, if a user scrolled down to a position where the items 4 and 5 are visible; items 1, 2 and 3 would be cleared from the memory to reduce memory consumption.
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.
Displaying images is easiest using a third party library such as Picasso from Square which will download and cache remote images and abstract the complexity behind an easy to use DSL.
Setup Picasso
Adding Picasso to our app/build.gradle file:
dependencies {
implementation 'com.squareup.picasso:picasso:2.5.2'
}
First of all add the following libraries in gradle(module:app)
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.android.volley:volley:1.1.1'
implementation 'com.squareup.picasso:picasso:2.5.2'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment