Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

android - Passing JSONObject into another activity

I'm hitting an external API that's returning JSON data (new dvd titles). I'm able to parse out the JSON and list each dvd title and other dvd information into a ListView just fine. I was also able to setup an onListItemClick method just fine for primitive data (title string). I ended up writing something like so for the onListItemClick method:

Just to note, the productArray is a class var that's being set by another method that holds an array of JSONObjects.

protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

    Intent i = new Intent(DvdListingActivity.this, MovieProductActivity.class);
    try {
        JSONObject jsonObj = productArray.getJSONObject(position);
        i.putExtra("mTitle", jsonObj.getJSONObject("Title").opt("val").toString());
        i.putExtra("mRelDate", jsonObj.getJSONObject("RelDate").opt("val").toString());
        i.putExtra("mDesc", jsonObj.getJSONObject("Desc").opt("val").toString());
        i.putExtra("mRating", jsonObj.getJSONObject("MPAA").getJSONObject("Rating").opt("val").toString());
        i.putExtra("mActors", jsonObj.getJSONObject("Actors").opt("val").toString());
        i.putExtra("mImage", jsonObj.getJSONObject("Image").opt("val").toString());
        startActivity(i);

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }       

}

The above code all works, but I'm thinking there's GOTTA be a better way for me to pass in data to another Activity. I was thinking that I would be able to pass a JSONObject that contains all the data for a dvd movie instead of setting each data point individually.

I tried for a week and a half to figure out how to use Parcelable. I tried instantiating a new JSONObject jsonObj that implements Parcelable with no luck. I kept getting an error in my LogCat that said that the object was un-parcelable.

I've tried reading the Android developer site and other blogs, but I couldn't apply their examples to what I needed to do.

Any help would be much appreciated

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can simply put an entire JSONObject as a string. Something like this:

i.putString("product", jsonObj.toString);

And then in the MovieProductActivity you could

JSONObject jsonObj = new JSONObject(getIntent().getStringExtra("product"));


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...