Android RecyclerView JSON Parsing using Retrofit
Hello Developers, Today we’ll make a Android App that will fetch JSON data from server using Volley and put the data to a RecylerView.
Before we begin: I’m using Ubuntu Linux and also using XAMPP as a server, so make sure if you have XAMPP installed in your system or just put the JSON data to your website. And I am using Android Studio RC 3.0 for this tutorial.
YouTube Video:
Our Final Output:
How the JSON will look like:
[
{
“title”: “Dawn of the Planet of the Apes”,
“rating”: 8.3,
“releaseYear”: 2014
},
//……
]
The JSON’s root is “[“ and all data is wrapped in “{“.
“title” = String
“rating” = int
“releaseYear” = int
Let’s Code
Step 1) Create a new Android Studio project and add these dependencies to app level build.gradle
compile 'com.android.volley:volley:1.0.0'compile 'com.android.support:design:26.1.0'implementation 'com.android.support:appcompat-v7:26.1.0'
Step 2) Open activity_main.xml and add a RecylerView attribute
<android.support.v7.widget.RecyclerView
android:id="@+id/main_list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
Step 4) Create a new Java Class and name it
Movie
and modify it with below codepackage example.neo.istone.volleyexample;
/**
* Created by ankit on 27/10/17.
*/public class Movie {
public String title;
public int rating;
public int year;
public Movie() {
}
public Movie(String title, int rating, int year) {
this.title = title;
this.rating = rating;
this.year = year;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
Step 5) Create a new Java Class for adapter and name it
MovieAdapter
and modify it with below codepackage example.neo.istone.volleyexample;
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.TextView;
import java.util.List;
/**
* Created by ankit on 27/10/17.
*/public class MovieAdapter extends RecyclerView.Adapter{
private Context context;
private Listlist;
public MovieAdapter(Context context, Listlist) {
this.context = context;
this.list = list;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.single_item, parent, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Movie movie = list.get(position);
holder.textTitle.setText(movie.getTitle());
holder.textRating.setText(String.valueOf(movie.getRating()));
holder.textYear.setText(String.valueOf(movie.getYear()));
}
@Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textTitle, textRating, textYear;
public ViewHolder(View itemView) {
super(itemView);
textTitle = itemView.findViewById(R.id.main_title);
textRating = itemView.findViewById(R.id.main_rating);
textYear = itemView.findViewById(R.id.main_year);
}
}
}
Step 6) You might get a error
R.layout.single_item
to fix this create a new layout and name it as single_item
and add below code in itxml version="1.0" encoding="utf-8"?><LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="@+id/main_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Title"
android:textSize="18sp"/>
<TextView
android:id="@+id/main_rating"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Rating"/>
<TextView
android:id="@+id/main_year"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Year"/>
</LinearLayout>
Step 7) Add below variables in
MainActivity.java
private RecyclerView mList;
private LinearLayoutManager linearLayoutManager;
private DividerItemDecoration dividerItemDecoration;
private ListmovieList;
private RecyclerView.Adapter adapter;
Step 8) Declare the variables
mList = findViewById(R.id.main_list);
movieList = new ArrayList<>();
adapter = new MovieAdapter(getApplicationContext(),movieList);
linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
dividerItemDecoration = new DividerItemDecoration(mList.getContext(), linearLayoutManager.getOrientation());
mList.setHasFixedSize(true);
mList.setLayoutManager(linearLayoutManager);
mList.addItemDecoration(dividerItemDecoration);
mList.setAdapter(adapter);
Step 9) If you’re using put your JSON file to
/htdocs/Volley/
. If you’re using a real website and have control to FTP put it to your website.Step 10) If you using a real website use you own domain, if you’r at XAMPP you need server IP instead of localhost. To get the IP Address: If your using Windows/Mac use
ipconfig
instead of this if you’r using Linux like me, use ifconfig
to get the IP Address.Step 11) Now you’ve got you Server Address, create a new String variable to
MainActivity.java
private String url = "http://192.168.43.196/Volley/data.json";
Step 12) Now we’ll fetch the data, create a new method in
MainActivity.java
and use below codeprivate void getData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener() {
@Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(jsonObject.getString("title"));
movie.setRating(jsonObject.getInt("rating"));
movie.setYear(jsonObject.getInt("releaseYear"));
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
}
}
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
Step 12) Execute the method in onCreate()
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/.................
getData();
}
Step 14) Now you’r
MainActivity.java
will look something like thispackage example.neo.istone.volleyexample;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
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;
public class MainActivity extends AppCompatActivity {
private String url = "http://192.168.43.196/Volley/data.json";
private RecyclerView mList;
private LinearLayoutManager linearLayoutManager;
private DividerItemDecoration dividerItemDecoration;
private ListmovieList;
private RecyclerView.Adapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mList = findViewById(R.id.main_list);
movieList = new ArrayList<>();
adapter = new MovieAdapter(getApplicationContext(),movieList);
linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
dividerItemDecoration = new DividerItemDecoration(mList.getContext(), linearLayoutManager.getOrientation());
mList.setHasFixedSize(true);
mList.setLayoutManager(linearLayoutManager);
mList.addItemDecoration(dividerItemDecoration);
mList.setAdapter(adapter);
getData();
}
private void getData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener() {
@Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(jsonObject.getString("title"));
movie.setRating(jsonObject.getInt("rating"));
movie.setYear(jsonObject.getInt("releaseYear"));
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
}
}
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
}
Step 15) Finally add Internet permission in manifest
android.permission.INTERNET
Step 16) Build and Test the app in an Emulator or use a real device if you’re using a real website. Clap and Comment if you got any problem in this code.
0 Comments: