Main menu

Pages

Parse Json Data from Url and display content to recyclerview | Android Studio Tutorial

Hey everyone, today we're going to create a parse Json Data from Url and display content to recyclerview app.


You can download all the image used in the explanation from here

First, we add colors


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>
    <color name="purple_700">#FF3700B3</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>
    <color name="colorPrimary">#FF7C61</color>
    <color name="colorPrimaryDark">#BA4734</color>
    <color name="colorAccent">#D81B60</color>
    <color name="colorBitterSweet">#FC6E51</color>
    <color name="colorBitterSweetDark">#E9573F</color>
</resources>

Then we increase the theme 

<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Theme.CodeXCode" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/purple_500</item>
        <item name="colorPrimaryVariant">@color/purple_700</item>
        <item name="colorOnPrimary">@color/white</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/teal_200</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/black</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
    </style>
    <style name="cxcTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</resources>


We add implementation in build.gradle


implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.picasso:picasso:2.5.2'


Add Permission


<uses-permission android:name="android.permission.INTERNET" />


Then we create a new file in layout and we call "list_row"


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/tools"
    app:ignore="NamespaceTypo">
    <androidx.cardview.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_margin="5dp"
        android:elevation="3dp"
        card_view:cardCornerRadius="15dp">
        <RelativeLayout
            android:layout_width="match_parent"
            android:id="@+id/ccl"
            android:layout_height="match_parent">
            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="140dp"
                    android:orientation="horizontal">
                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content">
                        <ImageView
                            android:id="@+id/thumbnail"
                            android:layout_width="240dp"
                            android:layout_height="140dp"
                            android:scaleType="centerCrop"
                            app:sriv_right_top_corner_radius="15dp" />
                    </LinearLayout>
                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:orientation="vertical">
                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="40dp"
                            android:layout_marginBottom="6.7dp"
                            android:background="@drawable/menuback4"
                            android:orientation="horizontal">
                            <ImageView
                                android:layout_width="40dp"
                                android:layout_height="40dp"
                                android:layout_gravity="left"
                                android:src="@drawable/ic_location_on_black_24dp"
                                app:ignore="VectorDrawableCompat" />
                            <TextView
                                android:id="@+id/title2"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_gravity="center"
                                android:layout_weight="1"
                                android:background="@drawable/menuback4"
                                android:gravity="left"
                                android:text="text1"
                                android:textColor="#fff"
                                android:scaleType="centerCrop"/>
                        </LinearLayout>
                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="40dp"
                            android:layout_marginBottom="6.7dp"
                            android:background="@color/colorBitterSweetDark"
                            android:orientation="horizontal">
                            <ImageView
                                android:layout_width="40dp"
                                android:layout_height="40dp"
                                android:layout_gravity="left"
                                card_view:srcCompat="@drawable/ic_text_format_black_24dp"
                                app:ignore="VectorDrawableCompat" />
                            <TextView
                                android:id="@+id/title3"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_gravity="center"
                                android:layout_weight="1"
                                android:textColor="#fff"
                                android:background="@color/colorBitterSweetDark"
                                android:gravity="left"
                                android:text="text2"/>
                        </LinearLayout>
                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="40dp"
                            android:background="@color/colorBitterSweetDark"
                            android:orientation="horizontal">
                            <ImageView
                                android:layout_width="40dp"
                                android:layout_height="40dp"
                                android:layout_gravity="left"
                                card_view:srcCompat="@drawable/ic_cloud_circle_black_24dp"
                                app:ignore="VectorDrawableCompat" />
                            <TextView
                                android:id="@+id/title4"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_gravity="center"
                                android:layout_weight="1"
                                android:background="@color/colorBitterSweetDark"
                                android:gravity="left"
                                android:text="text3"
                                android:textColor="#fff" />
                        </LinearLayout>
                    </LinearLayout>
                </LinearLayout>
                <TextView
                    android:id="@+id/title"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@drawable/menuback3"
                    android:padding="8dp"
                    android:text="title"
                    android:textAlignment="center"
                    android:textColor="#fff" />
            </LinearLayout>
        </RelativeLayout>
    </androidx.cardview.widget.CardView>
</LinearLayout>


Then we create a new file in the layout folder we call "aee"


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:background="@color/colorPrimary"
    android:layout_width="300dp"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="100dp"
        android:layout_gravity="center"
        android:layout_margin="5dp"
        android:layout_marginTop="10dp"
        android:src="@drawable/ic_text_format_black_24dp"
        android:layout_height="100dp" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_gravity="center"
        android:gravity="center"
        android:orientation="vertical"
        android:layout_height="wrap_content">


        <TextView
            android:layout_width="wrap_content"
            android:text="MY APP"
            android:layout_gravity="center"
            android:gravity="center"
            android:textSize="18sp"
            android:textColor="#fff"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="wrap_content"
            android:text="Error Loading"
            android:layout_gravity="center"
            android:gravity="center"
            android:textSize="18sp"
            android:textColor="#fff"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_gravity="center"
        android:gravity="center"
        android:layout_marginBottom="5dp"
        android:layout_height="wrap_content">
        <Button
            android:layout_width="120dp"
            android:layout_gravity="center"
            android:text="OK"
            android:textColor="#000"
            android:layout_margin="3dp"
            android:background="@drawable/menuback"
            android:textStyle="bold"
            android:padding="10dp"
            android:layout_height="40dp" />

    </LinearLayout>
    </LinearLayout>

We are changing the layout responsible for the activity in this xml file


<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/tools"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#fff"
    tools:context=".MainActivity">


    <ProgressBar
        android:id="@+id/progress_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:indeterminate="true"
        android:visibility="gone"
        android:indeterminateBehavior="cycle"
        app:layout_constraintBottom_toBottomOf="@+id/m_RecyclerView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/m_RecyclerView"
        app:layout_constraintTop_toTopOf="parent"
        card_view:ignore="MissingConstraints" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/m_RecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fadeScrollbars="true"
        android:scrollbars="vertical"
        card_view:cardUseCopmatPadding="true" />

</androidx.constraintlayout.widget.ConstraintLayout>

Now we come to the programming stage. We are creating a new class that we call "JSONData.java"


package waxben.monbac.codexcode;


public class JSONData {
    private String title;
    private String title2;
    private String title3;
    private String title4;
    private String thumbnail;

    public String getTitle() {
        return title;
    }

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

    public String getTitle2() {
        return title2;
    }

    public void setTitle2(String title2) {
        this.title2 = title2;
    }

    public String getTitle3() {
        return title3;
    }

    public void setTitle3(String title3) {
        this.title3 = title3;
    }

    public String getTitle4() {
        return title4;
    }

    public void setTitle4(String title4) {
        this.title4 = title4;
    }

    public String getThumbnail() {
        return thumbnail;
    }

    public void setThumbnail(String thumbnail) {
        this.thumbnail = thumbnail;
    }
}


in this step we are creating a new class that we call "OnItemClickListener.java"


package waxben.monbac.codexcode;

public interface OnItemClickListener {
    void onItemClick(JSONData item);
}

As in the previous stage, we are creating a new class that we call "MyRecyclerViewAdapter.java"


package waxben.monbac.codexcode;

import android.content.Context;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.squareup.picasso.Picasso;

import java.util.List;

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.CustomViewHolder> {
    private List<JSONData> feedItemList;
    private Context mContext;

    private OnItemClickListener onItemClickListener;

    public MyRecyclerViewAdapter(Context context, List<JSONData> feedItemList) {
        this.feedItemList = feedItemList;
        this.mContext = context;
    }

    @Override
    public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null);
        CustomViewHolder viewHolder = new CustomViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
        final JSONData jsonData = feedItemList.get(i);

        //Render image using Picasso library
        if (!TextUtils.isEmpty(jsonData.getThumbnail())) {
            Picasso.with(mContext).load(jsonData.getThumbnail())
                    .error(R.drawable.placeholder)
                    .placeholder(R.drawable.placeholder)
                    .into(customViewHolder.imageView);
        }

        //Setting text view title
        customViewHolder.textView.setText(Html.fromHtml(jsonData.getTitle()));
        customViewHolder.textView2.setText(Html.fromHtml(jsonData.getTitle2()));
        customViewHolder.textView3.setText(Html.fromHtml(jsonData.getTitle3()));
        customViewHolder.textView4.setText(Html.fromHtml(jsonData.getTitle4()));


        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onItemClickListener.onItemClick(jsonData);
            }
        };

        customViewHolder.imageView.setOnClickListener(listener);
        customViewHolder.textView.setOnClickListener(listener);
        customViewHolder.textView2.setOnClickListener(listener);
        customViewHolder.textView3.setOnClickListener(listener);
        customViewHolder.textView4.setOnClickListener(listener);
        customViewHolder.itemView.setOnClickListener(listener);
    }

    public OnItemClickListener getOnItemClickListener() {
        return onItemClickListener;
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    @Override
    public int getItemCount() {
        return (null != feedItemList ? feedItemList.size() : 0);
    }

    class CustomViewHolder extends RecyclerView.ViewHolder {
        protected ImageView imageView;
        protected TextView textView, textView2, textView3, textView4;
        protected String uur;
        protected int id;

        public CustomViewHolder(View view) {
            super(view);
            this.imageView = (ImageView) view.findViewById(R.id.thumbnail);
            this.textView = (TextView) view.findViewById(R.id.title);
            this.textView2 = (TextView) view.findViewById(R.id.title2);
            this.textView3 = (TextView) view.findViewById(R.id.title3);
            this.textView4 = (TextView) view.findViewById(R.id.title4);
        }
    }
}


now, we are changing the java activity 


package waxben.monbac.codexcode;


import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Dialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "RecyclerViewJSON";
    private List<JSONData> feedsList;
    private RecyclerView mRecyclerView;
    private MyRecyclerViewAdapter adapter;
    private ProgressBar progressBar;
    private Dialog MyDialog;



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

        try {

            mRecyclerView = (RecyclerView) findViewById(R.id.m_RecyclerView);
            mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
            progressBar = (ProgressBar) findViewById(R.id.progress_bar);

            String url = "https://raw.githubusercontent.com/wben-sai/RecyclerView-JSON-from-Server/main/index.json";
            new GetDataBinding().execute(url);

        } catch (Exception ex) {
            Toast.makeText(MainActivity.this,
                    "Your Mesqdqs sdfsdfssage", Toast.LENGTH_LONG).show();
        }

    }

    private class GetDataBinding extends AsyncTask<String, Void, Integer> {
        @Override
        protected void onPreExecute() {
            progressBar.setVisibility(View.VISIBLE);
        }
        @Override
        protected Integer doInBackground(String... strings) {
            Integer result = 0;
            HttpURLConnection urlConnection;
            try {
                URL url = new URL(strings[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                int statusCode = urlConnection.getResponseCode();

                // 200 represents HTTP OK
                if (statusCode == 200) {
                    BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = r.readLine()) != null) {
                        response.append(line);
                    }
                    parseResult(response.toString());

                    result = 1; // Successful
                } else {
                    result = 0; //"Failed to fetch data!";
                }
            } catch (Exception e) {
                Log.d(TAG, e.getLocalizedMessage());
            }
            return result; //"Failed to fetch data!";
        }

        @Override
        protected void onPostExecute(Integer result) {
            progressBar.setVisibility(View.GONE);

            if (result == 1) {
                adapter = new MyRecyclerViewAdapter(MainActivity.this, feedsList);
                mRecyclerView.setAdapter(adapter);


                adapter.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(JSONData item) {
                        Toast.makeText(MainActivity.this, ""+item.getTitle(), Toast.LENGTH_LONG).show();



                    }
                });

            } else {

                MyDialog = new Dialog(MainActivity.this);
                MyDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                MyDialog.setContentView(R.layout.aae);
                MyDialog.setTitle("My Custom Dialog");

                MyDialog.show();
                MyDialog.setCanceledOnTouchOutside(false);
                MyDialog.setCancelable(false);


            }
        }
    }

    private void parseResult(String s) {
        try {
            JSONObject response = new JSONObject(s);
            JSONArray posts = response.optJSONArray("posts");
            feedsList = new ArrayList<>();
            for (int i = 0; i < posts.length(); i++) {
                JSONObject post = posts.optJSONObject(i);
                JSONData item = new JSONData();
                item.setTitle(post.optString("title"));
                item.setTitle2(post.optString("title2"));
                item.setTitle3(post.optString("title3"));
                item.setTitle4(post.optString("title4"));
                item.setThumbnail(post.optString("thumbnail"));
                feedsList.add(item);
            }

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

}

You are now in the first article
reactions

Comments