Issue encountered while parsing the JsonArray

Hi, I have encountered an issue while parsing a JSON data. Here is the link to the JSON data that I'm working with.

Currently, I am trying to parse the JSON array for images so that I can display them in a recycler view using Picasso library. However, when I click on an image, I am getting all the images from the JSON instead of just the one corresponding to the clicked image.

For example, if I click on "emo", I only want to display the image for "emo" and not all the images. Do you have any idea how I can achieve this?

Here's my current implementation:

public class AppShowModule {
    private List<String> Allimage = new ArrayList<String>();

    public List<String> getAllimage() {
        return Allimage;
    }

    public void setAllimage(List<String> allimage) {
        Allimage = allimage;
    }
}

This is the fragment where I am working with the JSON data:

public class ImageListFragment extends Fragment {
    List<AppShowModule> appShowModules;
    List<AppShowModule> imagesModule;
    RecyclerView AppRecyclerView;
    RecyclerView.Adapter imageRecyclerViewadapter;
    List<String> imageUrls;
    String feedKey = "feed";
    String entryKey = "entry";
    String imageKey = "im:image";
    String labelKey = "label";
    String jsonUrl = "https://itunes.apple.com/jo/rss/topfreeapplications/limit=50/json";
    RequestQueue requestQueue;
    private RecyclerView.LayoutManager mLayoutManager;

    public ImageListFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_image_list, container, false);
    }

    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        AppRecyclerView = (RecyclerView) getView().findViewById(R.id.imageRecyclerView);
        imagesModule = new ArrayList<>();
        appShowModules = new ArrayList<>();
        imageUrls = new ArrayList<>();
        JsonAppShowData();
    }

    public void JsonAppShowData() {
        final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(jsonUrl, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray jsonArray = response.getJSONObject(feedKey).getJSONArray(entryKey);
                    AppShowModule appShowModule = new AppShowModule();
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONArray imageArray = response.getJSONObject(feedKey).getJSONArray(entryKey).getJSONObject(i).getJSONArray(imageKey);
                        for (int j = 0; j < imageArray.length(); j++) {
                            String image = imageArray.getJSONObject(j).getString(labelKey).toString();
                            imageUrls.add(image);
                            appShowModule.setAllimage(imageUrls);
                            appShowModules.add(appShowModule);
                        }
                    }
                    imageRecyclerViewadapter = new ImageListAdapter(appShowModules, getContext(), imageUrls);
                    AppRecyclerView.setAdapter(imageRecyclerViewadapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("LOG", error.toString());
            }
        });

        requestQueue = Volley.newRequestQueue(getContext());
        requestQueue.add(jsonObjectRequest);
        mLayoutManager = new GridLayoutManager(getContext().getApplicationContext(), 3);
        AppRecyclerView.setLayoutManager(mLayoutManager);
    }
}

This is the recycler adapter:

public class ImageListAdapter extends RecyclerView.Adapter<ImageListAdapter.ViewHolder> {
    List<AppShowModule> appShowModules;
    List<String> imageUrl;
    Context context;

    public ImageListAdapter(List<AppShowModule> appShowModules, Context context ,List<String> imageUrls){
        super();
        this.imageUrl =imageUrls;
        this.appShowModules = appShowModules;
        this.context = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.imagelayout, parent,false );
        ViewHolder viewHolder = new ViewHolder(v);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Picasso.with(context).load(imageUrl.get(position)).into(holder.appImage);
    }

    public int getItemCount() {
        return imageUrl.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        public ImageView appImage;

        public ViewHolder(View itemView) {
            super(itemView);
            appImage = (ImageView) itemView.findViewById(R.id.appImage);
        }
    }
}

And finally, here's the activity that contains the ImageView that is clicked:

public class ListViewDetailsFragment extends Fragment {
    ImageView AppImage;
    TextView AppName, AppArtist, AppContentType, AppRights, AppCategory, AppRealseDate, AppSammary;
    ImageButton AppLink;
    Context context;

    public ListViewDetailsFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_list_view_details, container, false);
    }

    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        AppImage = (ImageView) getView().findViewById(R.id.imageView);
        AppName = (TextView) getView().findViewById(R.id.textname);
        AppArtist = (TextView) getView().findViewById(R.id.textartest);
        AppContentType = (TextView) getView().findViewById(R.id.textcontent);
        AppRights = (TextView) getView().findViewById(R.id.textrights);
        AppCategory = (TextView) getView().findViewById(R.id.textCategory);
        AppRealseDate = (TextView) getView().findViewById(R.id.textRelease);
        AppSammary = (TextView) getView().findViewById(R.id.textSummary);
        AppLink = (ImageButton) getView().findViewById(R.id.imageButton);

        String name = getActivity().getIntent().getExtras().getString("App_name");
        final String image = getActivity().getIntent().getExtras().getString("App_image");
        String artist = getActivity().getIntent().getExtras().getString("App_artist");
        String contentType = getActivity().getIntent().getExtras().getString("App_ContentType");
        String rights = getActivity().getIntent().getExtras().getString("App_Rights");
        String category = getActivity().getIntent().getExtras().getString("App_Category");
        String realse = getActivity().getIntent().getExtras().getString("App_ReleaseDate");
        final String link = getActivity().getIntent().getExtras().getString("App_link");
        String sammary = getActivity().getIntent().getExtras().getString("App_summary");

        AppName.setText(name);
        AppArtist.setText(artist);
        AppContentType.setText(contentType);
        AppRights.setText(rights);
        AppCategory.setText(category);
        AppRealseDate.setText(realse);
        AppSammary.setText(sammary);

        Picasso.with(context).load(image).into(AppImage);

        AppLink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity().getBaseContext(),
                        WebView.class);
                intent.putExtra("App_link", link);
                getActivity().startActivity(intent);
            }
        });

        AppImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String id = (String) view.getTag();
                Intent intent = new Intent(getActivity().getBaseContext(), ImageList.class);
                intent.putExtra("id", id);
                getActivity().startActivity(intent);
            }
        });
    }
}

Answer №1

If you carefully examine the JSON structure, you'll notice that there are three different types of images with varying heights: small, medium, and large, located inside the im:image tag. However, you only require one specific type, not all three.

To achieve this, you need to modify the following code within your ImageListFragment, specifically in the JsonAppShowData() method:

AppShowModule appShowModule = new AppShowModule();
for (int i = 0; i < jsonArray.length(); i++) {
    String image = response.getJSONObject(feedKey).getJSONArray(entryKey)
                            .getJSONObject(i).getJSONArray(imageKey)
/* Make sure to make this crucial change -> */.get(2).getString(labelKey).toString();

    imageUrls.add(image);
    appShowModule.setAllimage(imageUrls);
    appShowModules.add(appShowModule);
}
imageRecyclerViewadapter = new ImageListAdapter(appShowModules, getContext(), imageUrls);

I hope these modifications prove helpful to you.

For a JSON sample, you can refer to:

Suggestion: Consider utilizing GSON for parsing JSON data. It offers an easy-to-understand and implement solution.

Answer №2

Wow, this coding is quite peculiar. Nevertheless, make sure you configure the scaleType attribute in your xml file for the imageview to either centerInside, center, or matrix; whichever suits your needs.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Export Image as Json File

I am currently working on creating a browser extension and I am trying to figure out how to save images locally. My plan is to store the images in a json file, but I'm feeling quite lost on how to accomplish this. Below is the code I have so far, alth ...

Javascript: A guide on passing an object through multiple nested functions

Hey fellow developers, I'm facing a challenge in my code and seeking advice from the experts out there. I'm attempting to retrieve JSON data from a specific URL, as shown below, and utilize it in a React component outside of the getWeather() fun ...

Unexpected behavior with the ion-datetime time picker on an Android device

I am encountering challenges with a Date and Time entry feature in my Angular/Ionic application that involves date pickers. When I tap on the Time field, the time picker opens. Everything works perfectly in my browser - I can select a time, spin the value ...

Converting intricate JSON documents into .csv format

I have this JSON file containing a wealth of information about football players and I am trying to convert it into a .csv format. However, as a beginner in this field, I am facing some challenges! You can access the raw data file at: https://raw.githubuse ...

An issue with Axios request in a cordova app using a signed version

Currently, I am in the process of developing a Cordova application utilizing Axios and React. The interesting part is that everything runs smoothly when I build the app with Cordova and test it on my phone using the APK. However, once I sign, zipalign it, ...

python extract values from a JSON object

I've been searching everywhere, but I haven't been able to find a solution. It seems like my question is not clear enough, so I'm hoping to receive some guidance. Currently, I am working with turbogears2.2. In my client view, I am sending a ...

Deliver JSON data to APNS using the Push-Sharp framework

I want to send JSON data to an iOS device in the following format: {"aps":{"content-available":1}} Would it be better to use the AppleNotification class or the AppleNotificationPayLoad class? Can you please provide a sample code for reference? Currently, ...

Access the contents of objects during the creation process

I am currently in the process of creating a large object that includes API path variables. The challenge I am facing is the need to frequently modify these API paths for application migration purposes. To address this, I had the idea of consolidating base ...

Converting JSON to CSV Using Python

i am currently working with a JSON file structured like this: { "temperature": [ { "ts": 1672753924545, "value": "100" } ], "temperature c1": [ { "ts": 167275392 ...

Issue: Incorrectly calling a hook. Hooks can only be used within the body of a function component. Assistance needed to resolve this issue

import React, { useState } from "react"; const RegistrationForm = () => { const [name, setName] = useState(""); const [password, setPassword] = useState(""); const [email, setEmail] = useState(" ...

get value from json with specified key

Here is a function that handles the success of my AJAX call: success: function(responseJson) { var receivedData = []; $.each(responseJson.jsonArray, function(index) { $.each(responseJson.jsonArray[index], function(key, value) ...

The API response includes a JSONObject indicating that the value for "empty" is set to false

I am currently working on a project that includes the following code snippet: @SessionScope @RestController public class cdaDisplayTool { private final static Logger LOG = LoggerFactory.getLogger(cdaDisplayTool.class); @PostMapping(path = "/d ...

What methods can be used to carry out personalized deserialization for specific fields?

I'm working on extracting data from my Firefox bookmarks for further manipulation. To my surprise, the process went smoothly with the following code: class Bookmark { public string title; public int? id; public int? parent; public str ...

react-native-iap is constantly returning an empty array when trying to fetch subscriptions

I am currently utilizing react-native-iap for in-app purchases. However, I am encountering an issue where the getSubscriptions function is returning an empty array when used on Android. Interestingly, everything works as expected on iOS. Despite my best e ...

The C# Twitch Class consistently retains a null value

As a self-taught C# programmer, my knowledge of classes and using JSON data is not as strong as I would like. I have been studying Java in school and applying that knowledge to C#, but I am struggling with deserializing JSON data obtained from an HTTP requ ...

Retrieve the output of a function once the function has completed

I'm facing an issue where I need to wait for a function to return a value from my MySQL table before using it as a return for my const ProjektNameIntentHandler. Here is the relevant code snippet: const ProjektNameIntentHandler = { canHandle(handlerIn ...

Analyze the JSON feedback

In Java, I am attempting to parse the following JSON response and retrieve the "message" and "WORKORDERID" data. { "operation": { "result": { "message": " successfully.", "status": "Success" }, "Details" ...

Deciphering intricate JSON structures using Pentaho

When using the variable path like ($..X..Y..Z), my goal is to retrieve values specifically from the path X/Y/Z. However, I am also getting values from all related paths where folder Z exists, such as (X/Y/1/Z), (X/Y/2/Z), (X/Y/3/B/Z). How can I ensure tha ...

Ways to eliminate unnecessary quotation marks surrounding a string in a JSON file using a shell script

I need help removing extra quotation marks from the following JSON data: {""id"":""1"", ""name"":""john"",""address"":"",""timestamp"":""2018/01/01 12:43:42 -700"",""dept"":""} To address this issue, I have been using the sed command: sed -i -e 's/ ...

javascript retrieving JSON data through an API request from a redirected URL

I am retrieving JSON data from the Glitch API. Upon opening the link, it redirects to a different domain (the domain was changed from gomix.me to glitch.me) When using Postman for both HTTP requests, I receive identical JSON data. However, there is a d ...