-1

how to load the specific JSON data in ListView that it carries with it all the data contained in the clicked ListView item ? i have no idea how to show the json data in the detailinfo

main activity

public class MainActivity extends Activity {

// Log tag
private static final String TAG = MainActivity.class.getSimpleName();

// Movies json url
private static final String url = "http://api.androidhive.info/json/movies.json";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;


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


    listView = (ListView) findViewById(R.id.list);
    adapter = new CustomListAdapter(this, movieList);
    listView.setAdapter(adapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            if (position == 0) {
                Intent myIntent = new Intent(view.getContext(), detailinfo.class);
                startActivityForResult(myIntent, 0);
            }

            if (position == 1) {
                Intent myIntent = new Intent(view.getContext(), detailinfo2.class);
                startActivityForResult(myIntent, 0);
            }

            if (position == 2) {
                Intent myIntent = new Intent(view.getContext(), detailinfo3.class);
                startActivityForResult(myIntent, 0);
            }

            if (position == 3) {
                Intent myIntent = new Intent(view.getContext(), detailinfo.class);
                startActivityForResult(myIntent, 0);
            }

            if (position == 4) {
                Intent myIntent = new Intent(view.getContext(), detailinfo2.class);
                startActivityForResult(myIntent, 0);
            }

            if (position == 5) {
                Intent myIntent = new Intent(view.getContext(), detailinfo3.class);
                startActivityForResult(myIntent, 0);
            }

            if (position == 6) {
                Intent myIntent = new Intent(view.getContext(), detailinfo.class);
                startActivityForResult(myIntent, 0);
            }

            if (position == 7) {
                Intent myIntent = new Intent(view.getContext(), detailinfo2.class);
                startActivityForResult(myIntent, 0);
            }
        }
    });

    pDialog = new ProgressDialog(this);
    // Showing progress dialog before making http request
    pDialog.setMessage("Loading...");
    pDialog.show();


    // Creating volley request obj
    JsonArrayRequest movieReq = new JsonArrayRequest(url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());
                    hidePDialog();

                    // Parsing json
                    for (int i = 0; i < response.length(); i++) {
                        try {

                            JSONObject obj = response.getJSONObject(i);
                            Movie movie = new Movie();
                            movie.setTitle(obj.getString("title"));
                            movie.setThumbnailUrl(obj.getString("image"));
                            movie.setRating(((Number) obj.get("rating"))
                                    .doubleValue());
                            movie.setYear(obj.getInt("releaseYear"));

                            // Genre is json array
                            JSONArray genreArry = obj.getJSONArray("genre");
                            ArrayList<String> genre = new ArrayList<String>();
                            for (int j = 0; j < genreArry.length(); j++) {
                                genre.add((String) genreArry.get(j));
                            }
                            movie.setGenre(genre);

                            // adding movie to movies array
                            movieList.add(movie);

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

                    }

                    // notifying list adapter about data changes
                    // so that it renders the list view with updated data
                    adapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            hidePDialog();

        }
    });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(movieReq);
}

@Override
public void onDestroy() {
    super.onDestroy();
    hidePDialog();
}

private void hidePDialog() {
    if (pDialog != null) {
        pDialog.dismiss();
        pDialog = null;
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
}

showing the JSON data here

detailinfo

public class detailinfo3 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.detail_info);
}
}

movie

public class Movie {
private String title, thumbnailUrl;
private int year;
private double rating;
private ArrayList<String> genre;

public Movie() {
}

public Movie(String name, String thumbnailUrl, int year, double rating,
             ArrayList<String> genre) {
    this.title = name;
    this.thumbnailUrl = thumbnailUrl;
    this.year = year;
    this.rating = rating;
    this.genre = genre;
}

public String getTitle() {
    return title;
}

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

public String getThumbnailUrl() {
    return thumbnailUrl;
}

public void setThumbnailUrl(String thumbnailUrl) {
    this.thumbnailUrl = thumbnailUrl;
}

public int getYear() {
    return year;
}

public void setYear(int year) {
    this.year = year;
}

public double getRating() {
    return rating;
}

public void setRating(double rating) {
    this.rating = rating;
}

public ArrayList<String> getGenre() {
    return genre;
}

public void setGenre(ArrayList<String> genre) {
    this.genre = genre;
}

}
Moacito
  • 39
  • 5

3 Answers3

2

that it carries with it all the data contained in the clicked ListView item

In general, use Intent extras.

How do I pass data between Activities in Android application?


A quicker way would be to implement Parcelable interface on the movie class

How can I make my custom objects Parcelable?

You can pass Parcelable objects via the Intent to use in the next Activity

Android: How to pass Parcelable object to intent and use getParcelable method of bundle?

To get the clicked item, you can use adapter.getItem(position)

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
1

Very good answer is here: How to pass an object from one activity to another on Android

You just have to make your Movie class implement Serializable. Then in onClick pass movie object just like intent.putExtra("movie", movie);

And in second activity get it as getIntent.getSerializableExtra("movie")

Subhan Ali
  • 1,370
  • 13
  • 17
  • Other solution is to serialize object to json string, then deserialize it back in second activity. – user1209216 Jun 18 '17 at 07:36
  • Yes it is possible. – Subhan Ali Jun 18 '17 at 07:43
  • thank you, but how if i want to pass the specific json data (title,image and rating) only ? – Moacito Jun 18 '17 at 07:57
  • Why do you want to pass these in Json? I mean hopefully title, image, ratings will be strings which you can pass individually in intent. – Subhan Ali Jun 18 '17 at 09:04
  • ok but can i simply call the volley in the detail activity ? – Moacito Jun 18 '17 at 09:42
  • 1
    Volley is to make an efficient server request. Its not for communicating data between activities.Do you mean to make a new server request using volley in detail activity? – Subhan Ali Jun 18 '17 at 09:45
  • yes, i mean to make a new volley request in the detail activity is this possible ? – Moacito Jun 18 '17 at 10:32
  • Parcelable should be preferred over Serializable, by the way – OneCricketeer Jun 18 '17 at 11:53
  • @Moacito Sorry for delay, Yes you can make a new server request but why are you making it burdensome avoid extraneous requests if you already have same data. Make your app light weight as much as possible. Frequent server requests cause battery drain. – Subhan Ali Jun 19 '17 at 07:00
  • @cricket_007 Yes dear, You are right. Thanks for correction. Actually Parcelable is specifically designed for android on the other hand serializable is for general Java. Both at the end have the same purpose of marshalling and unmarshalling java objects. A very good and short difference is mentioned here: https://stackoverflow.com/a/3323554/6577892 – Subhan Ali Jun 19 '17 at 07:05
1

Use Gson

Convert Java object to JSON

String jsonInString = gson.toJson(obj);

Convert JSON to Java object

YourClass yourClass = gson.fromJson(jsonInString, YourClass .class);

Convert Java Object to JsonString on itemClick and send it to detailActivity by passing through intent , then get intent data in detailActivity and convert it to Java Object.

Dhiraj Sharma
  • 4,364
  • 24
  • 25
  • thanks mate, but in this case i'm using volley to parsing the json, can i simply call the volley in the detailActivity to show the json data? – Moacito Jun 18 '17 at 09:47
  • Intent extras are limited in size, so JSON isn't always best. @Moacito Volley doesn't parse JSON into anything other than String or JSONObject by default. The libraries do different things, and can be used together. https://developer.android.com/training/volley/request-custom.html – OneCricketeer Jun 18 '17 at 11:50