简体   繁体   中英

Populating Fragment with JSON data

I'm using retrofit to request JSON data from my site. Here is the onCreate() method from my MainActivity class:

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

    RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint(BASE_URL)
            .build();

    ApiEndpointInterface apiService = restAdapter.create(ApiEndpointInterface.class);

    apiService.getFeed(9, new Callback<Post>() {

        @Override
        public void success(Post post, Response response) {
            // do something
        }

        @Override
        public void failure(RetrofitError retrofitError) {
            retrofitError.printStackTrace();
        }
    });

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // Initialize the ViewPager and set an adapter
    ViewPager pager = (ViewPager) findViewById(R.id.pager);
    pager.setAdapter(new PagerAdapter(getSupportFragmentManager()));

    // Bind the tabs to the ViewPager
    PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
    tabs.setViewPager(pager);
}

The JSON response looks like this:

[
    {
        "id":"1",
        "user_id":"1",
        ... more data ...
    },
    {
        "id":"2",
        "user_id":"1",
        ... more data ...
    },
    ... etc ...
]

I want to create a List within the Fragment, where each List item is populated by data from the returned JSON.

How do I create the List template and then populate it with the data?

将该JSON数据转换为POJO / Bean对象,将它们放入ArrayList,然后在recyclerview / listview的适配器中使用该arraylist。

You can use REST request libraries such as robospice or volley and for the list, you can use recycler view.

You will need to implement an adapter for your recycler view as described on the documentation and populate the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM