实现onItemClickListener,然后在另一个活动中显示JSON数据

时间:2017-06-18 07:18:45

标签: android json listview

如何在ListView中加载特定的JSON数据,它包含点击的ListView项目中包含的所有数据?我不知道如何在detailinfo

中显示json数据

主要活动

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;
}
}

在此处显示JSON数据

detailinfo

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

电影

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;
}

}

3 个答案:

答案 0 :(得分:2)

  

它随身携带点击的ListView项目中包含的所有数据

通常,使用Intent附加功能。

How do I pass data between Activities in Android application?

更快的方法是在电影类

上实现Parcelable接口

How can I make my custom objects Parcelable?

您可以通过Intent传递Parcelable对象以在下一个Activity中使用

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

要获取点击的项目,您可以使用adapter.getItem(position)

答案 1 :(得分:1)

非常好的答案在这里:How to pass an object from one activity to another on Android

您只需要使您的Movie类实现Serializable。 然后在onClick传递电影对象,就像intent.putExtra("movie", movie);

在第二项活动中,将其设为getIntent.getSerializableExtra("movie")

答案 2 :(得分:1)

使用Gson

将Java对象转换为JSON

String jsonInString = gson.toJson(obj);

将JSON转换为Java对象

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

在itemClick上将Java Object转换为JsonString并通过传递intent将其发送到detailActivity,然后在detailActivity中获取intent数据并将其转换为Java Object。