如何在Android的RecyclerView中显示其他JsonArray [英] How to show other JsonArray in RecyclerView on Android

查看:86
本文介绍了如何在Android的RecyclerView中显示其他JsonArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为一个网站开发android应用程序.我从json中读取网站帖子,并每10个帖子在RecyclerView中显示它,当用户在RecyclerView上滚动时,显示更多10个帖子,然后结束!在这个项目中,我使用okHTTP v3RecyclerView
我想在文本视图中显示title中的title,但是我不知道该如何显示?!
我的Json:

I want develop android application for one website. I read website posts from json and show its in RecyclerView every 10 posts and when user scrolling on RecyclerView show more 10 post and go to end! in this project i use okHTTP v3 and RecyclerView!
I want show title from categories in textview, but i don't know how to show this?!
My Json :

{
    "status": "ok",
    "count": 10,
    "count_total": 28,
    "pages": 3,
    "posts": [{
        "id": 145,
        "type": "post",
        "slug": "english-post-2",
        "url": "http:\/\/tellfa.com\/tafrihgah\/?p=145",
        "status": "publish",
        "title": "English Post",
        "title_plain": "English Post",
        "content": "<p>This post is test for show Text and Image<\/p>\n<p><img class=\"alignnone size-medium wp-image-79\" src=\"http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol49-027-300x240.jpg\" alt=\"[WallpapersMania]_vol49-027\" width=\"300\" height=\"240\" srcset=\"http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol49-027-300x240.jpg 300w, http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol49-027-768x614.jpg 768w, http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol49-027-1024x819.jpg 1024w, http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol49-027.jpg 1280w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/p>\n<p>This is image in Text<\/p>\n",
        "excerpt": "<p>This post is test for show Text and Image<\/p>\n<p>This is image in Text<\/p>\n",
        "date": "2016-05-01 08:20:39",
        "modified": "2016-05-01 08:20:39",
        "categories": [{
            "id": 1,
            "slug": "%d8%af%d8%b3%d8%aa%d9%87%e2%80%8c%d8%a8%d9%86%d8%af%db%8c-%d9%86%d8%b4%d8%af%d9%87",
            "title": "\u062f\u0633\u062a\u0647\u200c\u0628\u0646\u062f\u06cc \u0646\u0634\u062f\u0647",
            "description": "",
            "parent": 0,
            "post_count": 24
        }],
        "tags": [],
        "author": {
            "id": 1,
            "slug": "tellfa",
            "name": "\u0645\u062d\u0645\u062f",
            "first_name": "",
            "last_name": "",
            "nickname": "\u0645\u062d\u0645\u062f",
            "url": "http:\/\/codesaz.com",
            "description": "\u0627\u06cc\u0646 \u0632\u0646\u062f\u06af\u06cc \u0646\u0627\u0645\u0647 \u0645\u0646 \u0627\u0633\u062a",
            "avatar": "76"
        },
        "comments": [],
        "attachments": [{
            "id": 146,
            "url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031.jpg",
            "slug": "wallpapersmania_vol33-031",
            "title": "WallpapersMania_vol33-031",
            "description": "",
            "caption": "",
            "parent": 145,
            "mime_type": "image\/jpeg",
            "images": {
                "full": {
                    "url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031.jpg",
                    "width": 1600,
                    "height": 1200
                },
                "thumbnail": {
                    "url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-150x150.jpg",
                    "width": 150,
                    "height": 150
                },
                "medium": {
                    "url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-300x225.jpg",
                    "width": 300,
                    "height": 225
                },
                "mediaphase-frontpage-news": {
                    "url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-300x220.jpg",
                    "width": 300,
                    "height": 220
                },
                "mediaphase-blog-large": {
                    "url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-700x313.jpg",
                    "width": 700,
                    "height": 313
                }
            }
        }],
        "comment_count": 0,
        "comment_status": "open",
        "thumbnail": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-150x150.jpg",
        "custom_fields": {},
        "thumbnail_size": "thumbnail",
        "thumbnail_images": {
            "full": {
                "url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031.jpg",
                "width": 1600,
                "height": 1200
            },
            "thumbnail": {
                "url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-150x150.jpg",
                "width": 150,
                "height": 150
            },
            "medium": {
                "url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-300x225.jpg",
                "width": 300,
                "height": 225
            },
            "mediaphase-frontpage-news": {
                "url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-300x220.jpg",
                "width": 300,
                "height": 220
            },
            "mediaphase-blog-large": {
                "url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-700x313.jpg",
                "width": 700,
                "height": 313
            }
        }
    }

我从Array中读取了该标题:

I read this title from this Array :

"categories": [{
            "id": 1,
            "slug": "%d8%af%d8%b3%d8%aa%d9%87%e2%80%8c%d8%a8%d9%86%d8%af%db%8c-%d9%86%d8%b4%d8%af%d9%87",
            "title": "\u062f\u0633\u062a\u0647\u200c\u0628\u0646\u062f\u06cc \u0646\u0634\u062f\u0647",
            "description": "",
            "parent": 0,
            "post_count": 24
        }],

我的AsyncTask代码:

public class MainDataInfo {
    private Context mContext;
    private String ServerAddress = ServerIP.getIP();

    public void getMainDataInfo(Context context) {
        mContext = context;
        new getInfo().execute(ServerAddress + "page=1");
    }

    private class getInfo extends AsyncTask<String, Void, String> {
        EventBus bus = EventBus.getDefault();
        private String ou_response;
        private List<MainDataModel> infoModels;

        @Override
        protected void onPreExecute() {
            CustomProcessDialog.createAndShow(mContext);
            infoModels = new ArrayList<>();
        }

        @Override
        protected String doInBackground(String... params) {
            OkHttpClient client = new OkHttpClient();

            //String url = (String) params[0];
            Request request = new Request.Builder()
                    .url(ServerAddress + "page=1")
                    .cacheControl(CacheControl.FORCE_NETWORK)
                    .build();

            Response response;
            try {
                response = client.newCall(request).execute();
                ou_response = response.body().string();
                response.body().close();
                if (ou_response != null) {
                    try {
                        JSONObject postObj = new JSONObject(ou_response);
                        JSONArray postsArray = postObj.optJSONArray("posts");
                        infoModels = new ArrayList<>();

                        for (int i = 0; i <= infoModels.size(); i++) {
                            JSONObject postObject = (JSONObject) postsArray.get(i);
                            // Thumbnail
                            JSONObject images = postObject.optJSONObject("thumbnail_images");
                            JSONObject imagesPair = images.optJSONObject("medium");
                            // Author
                            JSONObject Author = postObject.optJSONObject("author");

                            int id = postObject.getInt("id");
                            String title = postObject.getString("title");
                            String content = postObject.getString("content");
                            String dateTime = postObject.getString("date");
                            String thumbnail = imagesPair.getString("url");
                            String authorShow = Author.getString("name");
                            Log.d("Data", "Post id: " + id);
                            Log.d("Data", "Post title: " + title);
                            Log.d("Data", "Post image: " + thumbnail);
                            Log.d("Data", "Post category: " + authorShow);

                            //Use the title and id as per your requirement
                            infoModels.add(new MainDataModel(id, title, content, dateTime, authorShow, thumbnail));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return ou_response;
        }

        @Override
        protected void onPostExecute(String result) {
            CustomProcessDialog.dissmis();
            if (result != null) {
                bus.post(infoModels);

            }
        }
    }
}

MainActivity代码:

public class Main_page extends AppCompatActivity {

    private static final long RIPPLE_DURATION = 250;
    private Toolbar toolbar;
    private RelativeLayout root;
    private ImageView menu_image, toolbar_refresh;
    private RecyclerView main_recyclerView;
    private MainAdapter_loadMore mAdaper;
    private List<MainDataModel> dataModels = new ArrayList<MainDataModel>();
    protected Handler handler;
    private RelativeLayout loadLayout;
    private LinearLayoutManager mLayoutManager;
    private int pageCount = 1;
    String ServerAddress = ServerIP.getIP();
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_page);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        // Initializing
        handler = new Handler();
        context = getApplicationContext();
        toolbar = (Toolbar) findViewById(R.id.main_toolbar);
        mLayoutManager = new LinearLayoutManager(this);
        loadLayout = (RelativeLayout) findViewById(R.id.main_empty_layout);
        toolbar_refresh = (ImageView) toolbar.findViewById(R.id.toolbar_update);
        // Toolbar
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            getSupportActionBar().setTitle(null);
        }
        // Load First Data
        LoadData();
        // Menu
        root = (RelativeLayout) findViewById(R.id.main_root);
        View guillotineMenu = LayoutInflater.from(this).inflate(R.layout.menu_layout, null);
        root.addView(guillotineMenu);
        menu_image = (ImageView) toolbar.findViewById(R.id.toolbar_logo);
        new GuillotineAnimation.GuillotineBuilder(guillotineMenu, guillotineMenu.findViewById(R.id.menu_layout_image), menu_image)
                .setStartDelay(RIPPLE_DURATION)
                .setActionBarViewForAnimation(toolbar)
                .setClosedOnStart(true)
                .build();
        // RecyclerView and setData
        main_recyclerView = (RecyclerView) findViewById(R.id.main_recycler);
        main_recyclerView.setHasFixedSize(true);
        main_recyclerView.setLayoutManager(mLayoutManager);
        mAdaper = new MainAdapter_loadMore(this, main_recyclerView, dataModels);
        main_recyclerView.setAdapter(mAdaper);
        // Load More data
        mAdaper.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                dataModels.add(null);
                mAdaper.notifyItemInserted(dataModels.size() - 1);
                LoadMoreData(pageCount);
            }
        });

        // Refresh Data
        toolbar_refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getApplicationContext(), PostShow_page.class));
            }
        });
    }

    @Subscribe
    public void onEvent(List<MainDataModel> mainInfoModels) {
        if (dataModels.size() > 0) {
            dataModels.remove(dataModels.size() - 1);
            mAdaper.notifyItemRemoved(dataModels.size());
            mAdaper.setLoaded();
        }

        mAdaper.add(mainInfoModels);
        mAdaper.notifyDataSetChanged();
        pageCount++;

        if (dataModels.isEmpty()) {
            main_recyclerView.setVisibility(View.GONE);
            loadLayout.setVisibility(View.VISIBLE);

        } else {
            main_recyclerView.setVisibility(View.VISIBLE);
            loadLayout.setVisibility(View.GONE);
        }
    }

    private void LoadData() {
        MainDataInfo dataInfo = new MainDataInfo();
        // here getMainDataInfo() should return the server response
        dataInfo.getMainDataInfo(this);
    }

    private void LoadMoreData(int pageNumber) {
        MainDataInfo_loadMore dataInfo_loadMore = new MainDataInfo_loadMore();
        // here getMainDataInfo() should return the server response
        dataInfo_loadMore.getMainDataInfo_loadMore(this, pageNumber);
    }
}

注意:请不要给我负面意见,我是业余爱好者,我真的需要您的帮助!谢谢所有< 3

Attention : Please don't give me negative points, i am amateur and i really need you helps! thanks all <3

推荐答案

在布局中添加RecyclerView

add RecyclerView in layout

<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:scrollbars="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

添加依赖项

compile 'com.android.support:recyclerview-v7:23.1.1'

为RecyclerView的每一行创建一个布局,并将其命名为list_row.xml

create a layout for each row of RecyclerView and name it list_row.xml

  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusable="true"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:clickable="true"
    android:background="?android:attr/selectableItemBackground"
    android:orientation="vertical">

    <TextView
        android:id="@+id/title"
        android:textColor="@color/title"
        android:textSize="16dp"
        android:textStyle="bold"
        android:layout_alignParentTop="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />



</RelativeLayout>

创建一个JAVA文件Model.java

create a JAVA file Model.java

public class Model {

    public String title;

}

现在创建名为Adapter.java

    import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

public class Adapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> {

    private ArrayList<Model> modelArrayList=new ArrayList<>();

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView title;

        public MyViewHolder(View view) {
            super(view);
            title = (TextView) view.findViewById(R.id.title);

        }
    }


    public Adapter(ArrayList<Model> modelArrayList) {
        this.modelArrayList = modelArrayList;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_row, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Movie movie = moviesList.get(position);
        holder.title.setText(modelArrayList.get(position).title);

    }

    @Override
    public int getItemCount() {
        return modelArrayList.size();
    }
}

MainActivity.java

创建类型为Model

    ArrayList<Model> modelArrayList=new ArrayList<>();
 RecyclerView recyclerView;



recyclerView = (RecyclerView) findViewById(R.id.recycler_view);


        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);

购买数据

JSONObject jsonObject = new JSONObject(ou_response);
JSONArray message = jsonObject.getJSONArray("categories");

for (int i = 0; i < message.length(); i++) {
                    Model model = new Model();
                    JSONObject temp = message.getJSONObject(i);
                    model.tittle = temp.getString("tittle");
                    modelArrayList.add(model);
}

创建适配器并将其设置为recyclerView

create Adapter and set it to recyclerView

Adapter madapter = new Adapter(modelArrayList);

    recyclerView.setAdapter(mAdapter);

这篇关于如何在Android的RecyclerView中显示其他JsonArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆