Full width home advertisement

Watch Tutorials

Post Page Advertisement [Top]

Fetching JSON Data and Displaying in RecyclerView Using MVP Design Pattern

In this video, we demonstrate how to fetch JSON data from the assets directory and display it in a RecyclerView using the MVP design pattern. This tutorial addresses a request for implementing MVP architecture with a focus on local data sources. Let’s get started!

Watch the Video Tutorial

If you prefer a step-by-step walkthrough, watch the video tutorial below:

Introduction

We will work with a JSON file located in the assets directory, which contains a list of drinks that we want to display in a RecyclerView. The JSON file is used to simulate data fetching from a local database in the MVP architecture.

For a visual representation of the MVP architecture, check out this video: MVP Design Pattern Explained.

Step 1: Set Up the Repository

Our repository contains two data sources: local and remote. We will focus on updating the local data source to return JSON data from the assets directory. First, create a constructor to initialize the asset manager:


    public class LocalDataSource {
        private AssetManager assetManager;

        public LocalDataSource(AssetManager assetManager) {
            this.assetManager = assetManager;
        }

        // Method to load JSON data
        public String loadJsonData() {
            // Implementation here
        }
    }

Next, load the JSON data from the assets directory:


    private String loadJsonData() {
        String json = null;
        try {
            InputStream is = assetManager.open("drinks.json");
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            json = sb.toString();
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }

Step 2: Update the MVP Components

In the MVP architecture, update the local data source to handle JSON data and pass it to the presenter. Define methods to get all drinks and return them through a callback:


    public interface LocalDataSourceCallback {
        void onDrinksLoaded(List drinks);
        void onError(String error);
    }

    public void getAllDrinks(LocalDataSourceCallback callback) {
        String json = loadJsonData();
        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONArray jsonArray = jsonObject.getJSONArray("drinks");
            List drinksList = new ArrayList<>();
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject drinkObject = jsonArray.getJSONObject(i);
                String name = drinkObject.getString("name");
                drinksList.add(new Drink(name));
            }
            callback.onDrinksLoaded(drinksList);
        } catch (JSONException e) {
            callback.onError(e.getMessage());
        }
    }

In the presenter, call this method to fetch drinks and update the view accordingly:


    public class DrinkPresenter {
        private LocalDataSource localDataSource;
        private DrinkView view;

        public DrinkPresenter(LocalDataSource localDataSource, DrinkView view) {
            this.localDataSource = localDataSource;
            this.view = view;
        }

        public void loadDrinks() {
            view.showLoading();
            localDataSource.getAllDrinks(new LocalDataSourceCallback() {
                @Override
                public void onDrinksLoaded(List drinks) {
                    view.hideLoading();
                    view.displayDrinks(drinks);
                }

                @Override
                public void onError(String error) {
                    view.hideLoading();
                    view.showError(error);
                }
            });
        }
    }

Step 3: Update the RecyclerView

Add a RecyclerView to the layout and set up an adapter to display the list of drinks. Update the adapter with data from the presenter:


    public class DrinkAdapter extends RecyclerView.Adapter<DrinkAdapter.DrinkViewHolder> {
        private List<Drink> drinks;

        public DrinkAdapter(List<Drink> drinks) {
            this.drinks = drinks;
        }

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

        @Override
        public void onBindViewHolder(DrinkViewHolder holder, int position) {
            holder.bind(drinks.get(position));
        }

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

        public class DrinkViewHolder extends RecyclerView.ViewHolder {
            private TextView drinkName;

            public DrinkViewHolder(View itemView) {
                super(itemView);
                drinkName = itemView.findViewById(R.id.drink_name);
            }

            public void bind(Drink drink) {
                drinkName.setText(drink.getName());
            }
        }
    }

Ensure the RecyclerView is updated with the list of drinks once they are fetched by the presenter. Run the application to see the drinks displayed in the RecyclerView.

Conclusion

We have successfully fetched JSON data from the assets directory and displayed it in a RecyclerView using the MVP design pattern.

No comments:

Post a Comment

Share your thoughts ...

Bottom Ad [Post Page]