The purpose of this blog is to show how to parse a JSON data by API calling using third party library as OKHTTP3 and make a simple app which shows a sample output like below-

The full source code is available on GitLab:

https://gitlab.com/Asif047/moviemenia.git

The YouTube video link:

Alright, so now let’s code it-

  • At first, let me show the API link from where we will parse the JSON –

http://api.themoviedb.org/3/discover/movie?api_key=004cbaf19212094e32aa9ef6f6577f22

  • Now, create a new project and I have named it as “Movie Menia”
  • Open the app level gradle file and add the following dependencies-
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'

    compile 'com.squareup.okhttp3:okhttp:3.4.1'

    compile 'com.google.code.gson:gson:2.2.+'

    compile 'com.github.thomper:sweet-alert-dialog:v1.4.0'


    compile 'com.android.support:recyclerview-v7:26.1.0'

    compile 'com.android.support:design:26.1.0'

    compile 'com.android.support:cardview-v7:26.1.0'

    compile 'com.squareup.picasso:picasso:2.4.0'

}
  • For, sweet alert dialog dependency, we also need to make some changes in the project level gradle file. In the allprojects we need to add following code-
allprojects {
    repositories {

        jcenter()
        google()

        maven {
            url 'https://jitpack.io'
        }

    }

}
  • After adding all these dependencies, we need to sync the project.
  • In the manifest file, we need to add the following permissions-
<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" />
  • Create a new java class and I have named it “BaseUrl” and our base url in that class-
public class BaseUrl {

    public static final String BASE_URL = "http://api.themoviedb.org/";

}
  • Now, we mainly need four classes for parsing and showing the data in a nice user nice interface-
    1. MainActivity class
    2. Model class
    3. Api Call class
    4. RecyclerAdapter class
  • For creating the Model class at first, copy the all JSON data and then visit the link-

http://www.jsonschema2pojo.org/

Then paste the entire inside the box in that link. Set the target language: Java and source type: JSON

Then, click the preview button and you will see magic- Our class has been designed.

The class name “Example” is main class. So, we need to copy the code inside the Example class.

Then create a new class which will our model class inside our project and I have named it “ModelMovie”. Then paste the code of the Example class inside the ModelMovie class.

The other class Result will be the inner class of the ModelMovie class and we will declare the Result class as static.

So,  our ModelMovie.java class-

public class ModelMovie {


    @SerializedName("page")
    @Expose
    private Integer page;
    @SerializedName("total_results")
    @Expose
    private Integer totalResults;
    @SerializedName("total_pages")
    @Expose
    private Integer totalPages;
    @SerializedName("results")
    @Expose
    private List<Result> results = null;

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public Integer getTotalResults() {
        return totalResults;
    }

    public void setTotalResults(Integer totalResults) {
        this.totalResults = totalResults;
    }

    public Integer getTotalPages() {
        return totalPages;
    }

    public void setTotalPages(Integer totalPages) {
        this.totalPages = totalPages;
    }

    public List<Result> getResults() {
        return results;
    }

    public void setResults(List<Result> results) {
        this.results = results;
    }


    public static class Result {

        @SerializedName("vote_count")
        @Expose
        private Integer voteCount;
        @SerializedName("id")
        @Expose
        private Integer id;
        @SerializedName("video")
        @Expose
        private Boolean video;
        @SerializedName("vote_average")
        @Expose
        private Double voteAverage;
        @SerializedName("title")
        @Expose
        private String title;
        @SerializedName("popularity")
        @Expose
        private Double popularity;
        @SerializedName("poster_path")
        @Expose
        private String posterPath;
        @SerializedName("original_language")
        @Expose
        private String originalLanguage;
        @SerializedName("original_title")
        @Expose
        private String originalTitle;
        @SerializedName("genre_ids")
        @Expose
        private List<Integer> genreIds = null;
        @SerializedName("backdrop_path")
        @Expose
        private String backdropPath;
        @SerializedName("adult")
        @Expose
        private Boolean adult;
        @SerializedName("overview")
        @Expose
        private String overview;
        @SerializedName("release_date")
        @Expose
        private String releaseDate;

        public Integer getVoteCount() {
            return voteCount;
        }

        public void setVoteCount(Integer voteCount) {
            this.voteCount = voteCount;
        }

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public Boolean getVideo() {
            return video;
        }

        public void setVideo(Boolean video) {
            this.video = video;
        }

        public Double getVoteAverage() {
            return voteAverage;
        }

        public void setVoteAverage(Double voteAverage) {
            this.voteAverage = voteAverage;
        }

        public String getTitle() {
            return title;
        }

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

        public Double getPopularity() {
            return popularity;
        }

        public void setPopularity(Double popularity) {
            this.popularity = popularity;
        }

        public String getPosterPath() {
            return posterPath;
        }

        public void setPosterPath(String posterPath) {
            this.posterPath = posterPath;
        }

        public String getOriginalLanguage() {
            return originalLanguage;
        }

        public void setOriginalLanguage(String originalLanguage) {
            this.originalLanguage = originalLanguage;
        }

        public String getOriginalTitle() {
            return originalTitle;
        }

        public void setOriginalTitle(String originalTitle) {
            this.originalTitle = originalTitle;
        }

        public List<Integer> getGenreIds() {
            return genreIds;
        }

        public void setGenreIds(List<Integer> genreIds) {
            this.genreIds = genreIds;
        }

        public String getBackdropPath() {
            return backdropPath;
        }

        public void setBackdropPath(String backdropPath) {
            this.backdropPath = backdropPath;
        }

        public Boolean getAdult() {
            return adult;
        }

        public void setAdult(Boolean adult) {
            this.adult = adult;
        }

        public String getOverview() {
            return overview;
        }

        public void setOverview(String overview) {
            this.overview = overview;
        }

        public String getReleaseDate() {
            return releaseDate;
        }

        public void setReleaseDate(String releaseDate) {
            this.releaseDate = releaseDate;
        }

    }


}
  • Now, we need to create our Api Call class and I have named it “ApiCallMovies”. So, inside the class we will declare a GET method which will return the response body as string.
public class ApiCallMovies {

    public String GET(OkHttpClient client, String url) throws IOException{

        Request request = new Request.Builder()
                                    .url(url)
                                    .build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }

}
  • Now, we need to design our layout for MainActivity

Inside the activity_main.xml layout, we will simply declare the one Recyclerview.

So, the activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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="com.asif047.moviemenia.MainActivity">


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


</android.support.constraint.ConstraintLayout>
  • For each item inside the Recyclerview we need to create one more layout xml and I have named it “row_item_movie”

So, the row_item_movie.xml

<?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.support.v7.widget.CardView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"

       android:layout_margin="10dp"
       >

       <LinearLayout
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:orientation="horizontal"
           >

           <ImageView
               android:id="@+id/image_movie"
               android:layout_width="80dp"
               android:layout_height="100dp"
               android:layout_margin="5dp"
               />

           <LinearLayout
               android:layout_width="match_parent"
               android:layout_height="wrap_content"

               android:orientation="vertical"
               android:layout_marginLeft="5dp"
               >

               <TextView
                   android:id="@+id/textview_movie_name"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:text="Avengers"
                   android:textSize="20dp"
                   android:textColor="#000000"
                   />

               <TextView
                   android:id="@+id/textview_released_date"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:text="Released date"
               android:textSize="17dp"

               />


               <TextView
                   android:id="@+id/textview_overview"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:text="Overview"
                   android:textSize="15dp"

                   android:layout_marginTop="15dp"

                   />

           </LinearLayout>


       </LinearLayout>

   </android.support.v7.widget.CardView>


</RelativeLayout>
  • Now, we are ready to code for our RecyclerAdapter. I have named the class “RecyclerAdapterMovies”. It will extend Adapter class. Then we need to implement all the necessary methods.

Inside the classs, we will declare two variables- one context and a List of ModelMovie type. Then, create the constructor for that.

We will also create one inner class named MyViewHolder that will extend RecyclerView.ViewHolder and inside that define all the TextView and ImageView of the row_item_movie layout.

In the getItemCount() method, we will return the List size.

In the onBindViewHolder(MyViewHolder holder, int position) method, we wil set the text for the each TexView and image for the ImageView.

So, the RecyclerAdapterMovies.java class-

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

    private List<ModelMovie.Result> results;
    private Context context;

    public RecyclerAdapterMovies(Context context, List<ModelMovie.Result> results) {
        this.results = results;
        this.context = context;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.row_item_movie, parent, false);

        return new MyViewHolder(view);

    }

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

        holder.tvMovieName.setText(results.get(position).getOriginalTitle());
        holder.tvReleasedDate.setText(results.get(position).getReleaseDate());
        holder.tvOverview.setText(results.get(position).getOverview());

        Picasso.with(context).load("https://image.tmdb.org/t/p/w500"+results
                .get(position).getPosterPath()).into(holder.ivMovie);

    }

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


    public class MyViewHolder extends RecyclerView.ViewHolder {

        ImageView ivMovie;
        TextView tvMovieName, tvReleasedDate, tvOverview;

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

            ivMovie = itemView.findViewById(R.id.image_movie);
            tvMovieName = itemView.findViewById(R.id.textview_movie_name);
            tvReleasedDate = itemView.findViewById(R.id.textview_released_date);
            tvOverview = itemView.findViewById(R.id.textview_overview);
        }
    }


}
  • Now, we are all set for our final task which is editing our MainActivity

At first, we need to declare all the necessary variables –

private SweetAlertDialog pDialog;
private String path, response;
private OkHttpClient client;

private ModelMovie modelMovie;
private ApiCallMovies apiCallMovies;
private List<ModelMovie.Result> data;

private RecyclerView recyclerView;
private RecyclerAdapterMovies recyclerAdapterMovies;
private RecyclerView.LayoutManager layoutManager;
  • Inside the onCreate method, we will initialize these variables-
pDialog = new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE);
apiCallMovies = new ApiCallMovies();
data = new ArrayList<>();

recyclerView = findViewById(R.id.recyclerview);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
  • Now, we need to create one inner class GetDataFromServer that will extend AsyncTask. Then we will implement the necessary doInBackground(Void… voids) We will also override two methods- onPreExecute() and onPostExecute(Void result)

The purpose of using this class is doing all the API calling part in background thread. The onPreExecute() method will work before API call and loading data.

The onPostExecute(Void result) method will work after the API call and loading data.

private class GetDataFromServer extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        try {
            pDialog.getProgressHelper().setBarColor(Color
                    .parseColor("#26A65B"));
            pDialog.setTitleText("Loading");
            pDialog.setCancelable(false);
            pDialog.show();
        } catch (Exception e) {

        }
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

        if(pDialog.isShowing()) {
            pDialog.dismiss();
        }

        recyclerAdapterMovies = new RecyclerAdapterMovies(MainActivity.this,
                                        data);
        recyclerView.setAdapter(recyclerAdapterMovies);


    }

    @Override
    protected Void doInBackground(Void... voids) {

        try {

            client = new OkHttpClient();
            response = apiCallMovies.GET(client, path);

            Log.e("##JSON:", response);

            Gson gson = new Gson();
            Type type = new TypeToken<Collection<ModelMovie>>() {

            }.getType();

            modelMovie = gson.fromJson(response, ModelMovie.class);

            if(data.isEmpty()) {
                for(int i = 0; i < modelMovie.getResults().size(); i++) {
                    data.add(modelMovie.getResults().get(i));
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;

    }
}
  • Now, we need to initialize our entire url and call the GetDataFromServer class from onCreate method
  • try {
        path = BaseUrl.BASE_URL+"3/discover/movie?api_key=004cbaf19212094e32aa9ef6f6577f22";
        new GetDataFromServer().execute();
    } catch (Exception e) {
    
    }
    
  • So, the final code for the MainActivity.java class –
public class MainActivity extends AppCompatActivity {

    private SweetAlertDialog pDialog;
    private String path, response;
    private OkHttpClient client;

    private ModelMovie modelMovie;
    private ApiCallMovies apiCallMovies;
    private List<ModelMovie.Result> data;

    private RecyclerView recyclerView;
    private RecyclerAdapterMovies recyclerAdapterMovies;
    private RecyclerView.LayoutManager layoutManager;


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

        pDialog = new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE);
        apiCallMovies = new ApiCallMovies();
        data = new ArrayList<>();

        recyclerView = findViewById(R.id.recyclerview);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);

        try {
            path = BaseUrl.BASE_URL+"3/discover/movie?api_key=004cbaf19212094e32aa9ef6f6577f22";
            new GetDataFromServer().execute();
        } catch (Exception e) {

        }

    }



    private class GetDataFromServer extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            try {
                pDialog.getProgressHelper().setBarColor(Color
                        .parseColor("#26A65B"));
                pDialog.setTitleText("Loading");
                pDialog.setCancelable(false);
                pDialog.show();
            } catch (Exception e) {

            }
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            if(pDialog.isShowing()) {
                pDialog.dismiss();
            }

            recyclerAdapterMovies = new RecyclerAdapterMovies(MainActivity.this,
                                            data);
            recyclerView.setAdapter(recyclerAdapterMovies);


        }

        @Override
        protected Void doInBackground(Void... voids) {

            try {

                client = new OkHttpClient();
                response = apiCallMovies.GET(client, path);

                Log.e("##JSON:", response);

                Gson gson = new Gson();
                Type type = new TypeToken<Collection<ModelMovie>>() {

                }.getType();

                modelMovie = gson.fromJson(response, ModelMovie.class);

                if(data.isEmpty()) {
                    for(int i = 0; i < modelMovie.getResults().size(); i++) {
                        data.add(modelMovie.getResults().get(i));
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;

        }
    }

}
  • So, now we have completed our code. Let’s run the project and see the output.
Previous ArticleNext Article
Android Developer

Leave a Reply

Your email address will not be published. Required fields are marked *