Contents

Recycler view is used to create a listview,gridview without using the default functionality of listview and gridview.

 

Step 1   -
Add dependency in the gradle (App level)

For RecyclerView:

   Check the latest version from the following link.
   (https://developer.android.com/guide/topics/ui/layout/recyclerview)
		
   implementation 'com.android.support:recyclerview-v7:27.1.1'
		
   For JSON parsing:
		
   Check the latest version from the following link.
   (https://developer.android.com/training/volley/)

   implementation 'com.android.volley:volley:1.0.0'

   For CardView:
		
   Check the latest version from the following link.
   (https://developer.android.com/guide/topics/ui/layout/cardview)

   implementation 'com.android.support:cardview-v7:27.1.1'
 

Step 2   -
Create XML

<?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"
    		android:background="@drawable/gradient"
    		tools:context=".Recyclerview">
    		
<android.support.v7.widget.RecyclerView
        	android:layout_width="match_parent"
        	android:layout_height="wrap_content"
        	android:id="@+id/rv1">
</android.support.v7.widget.RecyclerView>

</RelativeLayout>
 

Step 3   -
If you are getting the data from the API then you need to generate a volley application class before starting JSON parsing.

public class Volleyapplication extends Application{

   public static Volleyapplication sInstance;
   private RequestQueue requestQueue;


    @Override
    public void onCreate() {
        super.onCreate();
        OneSignal.startInit(this).inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
                		.unsubscribeWhenNotificationsAreDisabled(true)
                		.init();
        requestQueue = Volley.newRequestQueue(this);
        sInstance = this;
    }

    public RequestQueue getRequestQueue() {
        return requestQueue;
    }

    public synchronized static Volleyapplication getsInstance(){
        return sInstance;
    }
}
 

Step 4   -
Initialize recyclerview in the mainactivity.java and also provide the layout manager in it.

public class Recyclerview extends AppCompatActivity {
    		private List<Movie> movieList = new ArrayList<>();
    		private RecyclerView recyclerView;
    		private MoviesAdapter mAdapter;
    		String rank,population,country,flag;

    		@Override
    		protected void onCreate(Bundle savedInstanceState) {
        		super.onCreate(savedInstanceState);
        		setContentView(R.layout.activity_recyclerview);
        		myPreference= new MyPreference(this);
        		recyclerView = (RecyclerView) findViewById(R.id.rv1);
        		mAdapter = new MoviesAdapter(this,movieList);
        		RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        		recyclerView.setLayoutManager(mLayoutManager);
        		recyclerView.setItemAnimator(new DefaultItemAnimator());
        		recyclerView.setAdapter(mAdapter);
        		//prepareMovieData();
        		fetchdata();
    		}

    		private void fetchdata(){
        		String url= "http://www.androidbegin.com/tutorial/jsonparsetutorial.txt";
        		StringRequest stringRequest = new StringRequest(Request.Method.GET,
                	url,
                		new Response.Listener<String>() {
                    		@Override
                    			public void onResponse(String response) {
                        		Log.e("Response", "onResponse: "+response);
                        		try {
                                		JSONObject json=new JSONObject(response);
                                		JSONArray jsonArray=json.getJSONArray("worldpopulation");
                                		for (int l=0;l<=jsonArray.length();l++){
                           			JSONObject object=jsonArray.getJSONObject(l);
                                    			rank= object.getString("rank");
                                    			country=object.getString("country");
                                    			population= object.getString("population");
                                    			flag=object.getString("flag");
                                    			Movie movie = new Movie(""+rank, ""+country, ""+population,""+flag);
                                    			movieList.add(movie);
                                    			mAdapter.notifyDataSetChanged();
                                			}
                        		} catch (JSONException e) {
                            						e.printStackTrace();
                            						Log.e("Error","Message",e);
                        					  }
                    			}
                		},
                	new Response.ErrorListener() {
                    	@Override
                    	public void onErrorResponse(VolleyError error) {
                        if(error != null){
                            Log.e("Error","Message",error);
                        }
                    	}
                });
        	Demo.getsInstance().getRequestQueue().add(stringRequest);
    		}
	}

 

Step 5   -
Create Model Class:

public class Movie {
    private String title, genre, year,flag;

    public Movie(String title, String genre, String year,String flag) {
        this.title = title;
        this.genre = genre;
        this.year = year;
        this.flag= flag;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String name) {
        this.title = name;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

    public String getGenre() {
        return genre;
    }

    public void setGenre(String genre) {
        this.genre = genre;
    }

    public String getFlag() {
        return flag;
    }

    public void setFlag(String flag) {
        this.flag = flag;
    }
}
 

Step 6   -
Create an custom Adapter Class.

public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> {

    private List<Movie> moviesList;
    private Context mContext;

    public class MyViewHolder extends RecyclerView.ViewHolder {
    	public TextView title, year, genre;
    	public ImageView imageView;

    	public MyViewHolder(View view) {
           super(view);
           title = (TextView) view.findViewById(R.id.title);
           genre = (TextView) view.findViewById(R.id.genre);
           year = (TextView) view.findViewById(R.id.year);
           imageView=(ImageView)view.findViewById(R.id.image);

           view.setOnClickListener(new View.OnClickListener() {
           @Override
           	public void onClick(View v) {
              		Intent intent=new Intent(mContext,gson.class);
              		mContext.startActivity(intent);
           	}
    	   });
        }
   }
   public MoviesAdapter(Context mContext,List<Movie> moviesList) {
        this.moviesList = moviesList;
        this.mContext = mContext;
   }

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

   @Override
   public void onBindViewHolder(MyViewHolder holder, int position) {
       Movie movie = moviesList.get(position);
       holder.title.setText(movie.getTitle());
       holder.genre.setText(movie.getGenre());
       holder.year.setText(movie.getYear());
       Glide.with(mContext).load(movie.getFlag()).into(holder.imageView);
   }

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

 

Step 7   -
Create layout XML file for adapter

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    		android:layout_width="match_parent"
    		android:layout_height="wrap_content"
    		android:background="?android:attr/selectableItemBackground"
    		android:clickable="true"
    		android:focusable="true"
    		android:orientation="vertical"
    		android:paddingBottom="@dimen/row_padding_vertical"
    		android:paddingLeft="@dimen/activity_horizontal_margin"
    		android:paddingRight="@dimen/activity_horizontal_margin"
    		android:paddingTop="@dimen/row_padding_vertical">

	<android.support.v7.widget.CardView
  		android:layout_width="match_parent"
    		android:layout_height="wrap_content">
    			
	<ImageView
        	android:layout_width="80dp"
        	android:layout_height="80dp"
        	android:id="@+id/image"/>
    			
	<TextView
        	android:id="@+id/title"
        	android:layout_width="match_parent"
        	android:layout_height="wrap_content"
        	android:layout_marginLeft="100dp"
        	android:hint="rank"
        	android:layout_alignParentTop="true"
        	android:textColor="@color/title"
        	android:textSize="16sp"
        	android:textStyle="bold" />

    	<TextView
        	android:id="@+id/genre"
        	android:hint="country"
        	android:layout_marginLeft="100dp"
        	android:layout_marginTop="20dp"
        	android:layout_width="match_parent"
        	android:textStyle="bold"
        	android:textSize="16sp"
        	android:layout_height="wrap_content"
        	android:layout_below="@id/title" />

    	<TextView
        	android:id="@+id/year"
        	android:hint="population"
        	android:layout_width="wrap_content"
        	android:layout_marginLeft="100dp"
        	android:layout_marginTop="40dp"
        	android:textStyle="bold"
        	android:textSize="16sp"
        	android:layout_height="wrap_content"
        	android:layout_alignParentRight="true"
        	android:textColor="@color/year" />
	</android.support.v7.widget.CardView>

</RelativeLayout>

Got an Idea of Game Development? What are you still waiting for? Contact us now and see the Idea live soon. Our company has been named as one of the best Game Development Company in India.

I am mobile app developer. I am working on android. I love to share designing tips & tricks with you.

Download demo of this blog click on Download button.