Android 如何发送多个Json请求并用数据填充ReyclView
我正在练习为wordpress博客构建一个android应用程序,我基本上想做的是展示文章标题和作者。我能够毫不费力地获取和显示文章标题,但让人头痛的是文章作者 这是json的链接 这是我的密码 positemsAndroid 如何发送多个Json请求并用数据填充ReyclView,android,json,wordpress,android-recyclerview,Android,Json,Wordpress,Android Recyclerview,我正在练习为wordpress博客构建一个android应用程序,我基本上想做的是展示文章标题和作者。我能够毫不费力地获取和显示文章标题,但让人头痛的是文章作者 这是json的链接 这是我的密码 positems public class PostItems implements Parcelable { private String post_title; private String post_author; public String getPost_title(
public class PostItems implements Parcelable {
private String post_title;
private String post_author;
public String getPost_title() {
return post_title;
}
public void setPost_title(String post_title) {
this.post_title = post_title;
}
public String getPost_author() {
return post_author;
}
public void setPost_author(String post_author) {
this.post_author = post_author;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.post_title);
dest.writeString(this.post_author);
}
public PostItems() {
}
protected PostItems(Parcel in) {
this.post_title = in.readString();
this.post_author = in.readString();
}
public static final Parcelable.Creator<PostItems> CREATOR = new Parcelable.Creator<PostItems>() {
@Override
public PostItems createFromParcel(Parcel source) {
return new PostItems(source);
}
@Override
public PostItems[] newArray(int size) {
return new PostItems[size];
}
};
}
public类positems实现可包裹{
私有字符串post_title;
私有字符串post_作者;
公共字符串getPost_title(){
返回帖子标题;
}
公共void setPost_title(字符串post_title){
this.post\u title=post\u title;
}
公共字符串getPost_author(){
回邮作者;
}
public void setPost_author(字符串post_author){
this.post_author=post_author;
}
@凌驾
公共int描述内容(){
返回0;
}
@凌驾
公共无效写入包裹(包裹目的地,内部标志){
目的地书面记录(此邮政标题);
目的地写作网(本帖作者);
}
公共职位(){
}
受保护邮件项(包裹中){
this.post_title=in.readString();
this.post_author=in.readString();
}
public static final Parcelable.Creator=新建Parcelable.Creator(){
@凌驾
公共PostItems createFromParcel(地块源){
返回新帖子(来源);
}
@凌驾
public PostItems[]新数组(整数大小){
返回新的positem[大小];
}
};
}
帖子列表的一部分
...
private void getData(){
Log.d(TAG, "getData called");
final ProDialoFrag dialoFrag = ProDialoFrag.newInstance();
dialoFrag.show(getFragmentManager(), "fragmentDialog");
//Creating a json request
jsonArrayRequest = new JsonArrayRequest(GET_URL,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called");
//Dismissing the progress dialog
if (dialoFrag != null ) {
dialoFrag.dismiss();
}
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (dialoFrag != null) {
dialoFrag.dismiss();
}
if (sthWrongAlert != null) {
sthWrongAlert.show();
}
}
}) {
};
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
mPostItemsList.clear();
for(int i = 0; i<array.length(); i++) {
PostItems postItem = new PostItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
JSONObject postTitle = jsonObject.getJSONObject("title");
postItem.setPost_title(postTitle.getString("rendered"));
JSONObject links = jsonObject.getJSONObject("_links");
JSONArray authorLink = links.getJSONArray("author");
String authorhref = authorLink.getJSONObject(0).getString("name")
postItem.setPostId(jsonObject.getString("link"));
} catch (JSONException w) {
w.printStackTrace();
//Toast.makeText(this, "Error in parsing Json", Toast.LENGTH_LONG).show();
}
mPostItemsList.add(postItem);
}
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}
public class PostFragment extends Fragment{
private List<PostItems> mPostItemsList = new ArrayList<>();
...
// Nothing changed here, just added it so you will understand my code better
ObservableRecyclerView recyclerView;
private RecyclerView.Adapter adapter;
LinearLayoutManager mLayoutManager;
public PostFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String title = getArguments().getString("title");
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_post, container, false);
//Initializing Views
recyclerView = (ObservableRecyclerView) view.findViewById(R.id.post_recycler);
recyclerView.setScrollViewCallbacks(this);
mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager( mLayoutManager);
...
//This method will get data from the web api
private void getData(){
Log.d(TAG, "getData called");
final ProDialoFrag dialoFrag = ProDialoFrag.newInstance();
dialoFrag.show(getFragmentManager(), "fragmentDialog");
//Creating a json request
jsonArrayRequest = new JsonArrayRequest(GET_URL,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called");
//Dismissing the progress dialog
if (dialoFrag == null ) {
dialoFrag.dismiss();
}
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (dialoFrag != null) {
dialoFrag.dismiss();
}
if (sthWrongAlert != null) {
sthWrongAlert.show();
}
}
}) {
n Response.success(resp.result, entry);
}
};
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
JSONObject jsonObject;
try {
jsonObject = array.getJSONObject(i);
JSONObject postTitle = jsonObject.getJSONObject("title");
String title = postTitle.getString("rendered"));
JSONObject links = jsonObject.getJSONObject("_links");
JSONArray authorLink = links.getJSONArray("author");
String authorhref = authorLink.getJSONObject(0).getString("href");
PostItems postItem = new PostItems();
postItem.setPost_title(title);
postItem.setPostAuthorUrl(authorhref);
mPostItemsList.add(postItem);
if (adapter.getAuthor(authorhref) == null) {
getAuthor(authorhref);
}
} catch (JSONException w) {
w.printStackTrace();
//Toast.makeText(this, "Error in parsing Json", Toast.LENGTH_LONG).show();
}
}
adapter.setPostItems(mPostItemsList);
}
private void getAuthor (String authorhref) {
Log.d(TAG, "getAuthor called");
JsonObjectRequest authorRequest = new JsonObjectRequest(authorhref, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, "onResponse called");
parseAuthor(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Do nothing
}
});
authorRequest.setShouldCache(false);
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(authorRequest);
}
private void parseAuthor (JSONObject object) {
Log.d(TAG, "Parsing auhor");
try {
JSONObject links = object.getJSONObject("_links");
JSONArray self = links.getJSONArray("self");
String href = self.getJSONObject(0).getString("href");
String authorname = object.getString("name");
adapter.putAuthor(href, authorname);
} catch (JSONException w) {
w.printStackTrace();
}
}
}
。。。
私有void getData(){
Log.d(标记“getData called”);
final ProDialoFrag dialoFrag=ProDialoFrag.newInstance();
show(getFragmentManager(),“fragmentDialog”);
//创建json请求
jsonArrayRequest=新的jsonArrayRequest(获取URL,
新的Response.Listener(){
@凌驾
公共void onResponse(JSONArray响应){
Log.d(标记“onResponse called”);
//取消“进度”对话框
如果(dialoFrag!=null){
dialoFrag.disclose();
}
//调用方法来解析json数组
解析数据(响应);
}
},
新的Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
如果(dialoFrag!=null){
dialoFrag.disclose();
}
如果(sthWrongAlert!=null){
sthWrongAlert.show();
}
}
}) {
};
//创建请求队列
RequestQueue RequestQueue=Volley.newRequestQueue(getActivity());
//将请求添加到队列
add(jsonArrayRequest);
}
//此方法将解析json数据
私有void parseData(JSONArray数组){
d(标记,“解析数组”);
mPostItemsList.clear();
对于(int i=0;i如果您使用的是HttpURLConnection
和AsyncTask
,则可以在一个后台操作中发出这两个请求,并且没有问题
但是,由于您似乎致力于使用截击,我建议您使用两个阶段的方法。在第1阶段,您解析帖子并保存帖子的作者url。在第2阶段,您将作者名称添加到按url索引的映射中
- 让
positem
包含作者url而不是作者姓名:
public class PostItem implements Parcelable {
private String post_title;
private String post_author_url;
// also change all the getters/setters/parceling etc.
}
(我把它做成PostItem——单数形式——因为它不是任何类型的同质集合。)
- 将
映射添加到适配器以包含作者姓名:
/** posts, which contain author url */
private List<PostItem> mPostItems;
/** authors by url */
private Map<String, String> mAuthorMap;
- 请注意,我将您的
getAuthor
方法更改为获取参数(而不是使用成员变量):
- 收到作者后,将其添加到适配器
private void parseAuthor (JSONObject object) {
Log.d(TAG, "Parsing author");
try {
JSONObject links = jsonObject.getJSONObject("_links");
JSONArray self = links.getJSONArray("self");
String href = authorLink.getJSONObject(0).getString("href");
String authorname = object.getString("name");
mAdapter.putAuthor(href, name);
} catch (JSONException w) {
w.printStackTrace();
}
}
- 下面是新的适配器方法:
public void setPostItems(List<PostItem> postItems) {
mPostItems = postItems;
notifyDataSetChanged();
}
public void putAuthor(String url, String name) {
mAuthorMap.put(url, name);
notifyDataSetChanged();
}
public String getAuthor(String url) {
return mAuthorMap.get(url);
}
编辑:获取作者url的不同方式,无需解析作者JSON->\u links->self[0]->href
// notice that authorhref is final
private void getAuthor (final String authorhref) {
Log.d(TAG, "getAuthor called");
JsonObjectRequest authorRequest = new JsonObjectRequest(authorhref, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, "onResponse called");
parseAuthor(authorhref, response); // pass authorhref with response
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Do nothing
}
});
authorRequest.setShouldCache(false);
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(authorRequest);
}
private void parseAuthor (String authorhref, JSONObject object) {
Log.d(TAG, "Parsing author");
try {
String authorname = object.getString("name");
mAdapter.putAuthor(authorhref, name);
} catch (JSONException w) {
w.printStackTrace();
}
}
//注意authorhref是final
私有void getAuthor(最终字符串authorhref){
Log.d(标记“getAuthor called”);
JsonObjectRequest authorRequest=新的JsonObjectRequest(authorhref,null,
新的Response.Listener(){
@凌驾
公共void onResponse(JSONObject响应){
Log.d(标记“onResponse called”);
parseAuthor(authorhref,response);//传递authorhref和response
}
},
新的Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
//无所事事
}
});
authorRequest.setShouldCache(false);
RequestQueue RequestQueue=Volley.newRequestQueue(getActivity());
添加(authorRequest);
}
私有void parseAuthor(字符串authorhref,JSONObject对象){
Log.d(标记“解析作者”);
试一试{
字符串authorname=object.getString(“名称”);
mAdapter.putAuthor(authorhref,名称);
}捕获(JSONException w){
w、 printStackTrace();
}
}
谢谢!我真的很感谢你的回答。我已经更新了我的问题,以反映应用你的答案后所做的更改以及我遇到的问题。请看一看。我为什么
public PostAdapter(List<PostItems> postItems, Context context) {
super();
//Getting all posts
this.mPostItems = postItems;
this.mContext = context;
this.mAuthorMap = new HashMap<>();
}
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
// Collect all the PostItems and add to adapter all at once
List<PostItem> postItems = new ArrayList<>();
for (int i = 0; i<array.length(); i++) {
JSONObject jsonObject;
try {
jsonObject = array.getJSONObject(i);
JSONObject postTitle = jsonObject.getJSONObject("title");
String title = postTitle.getString("rendered");
JSONObject links = jsonObject.getJSONObject("_links");
JSONArray authorLink = links.getJSONArray("author");
String authorhref = authorLink.getJSONObject(0).getString("href");
PostItem postItem = new PostItem();
postItem.setPostTitle(title);
postItem.setPostAuthorUrl(authorhref);
postItems.add(postItem);
if (mAdapter.getAuthor(authorhref) == null) {
getAuthor(authorhref);
}
} catch (JSONException w) {
w.printStackTrace();
//Toast.makeText(this, "Error in parsing Json", Toast.LENGTH_LONG).show();
}
}
mAdapter.setPostItems(postItems);
}
private void getAuthor(String authorhref) {
...
private void parseAuthor (JSONObject object) {
Log.d(TAG, "Parsing author");
try {
JSONObject links = jsonObject.getJSONObject("_links");
JSONArray self = links.getJSONArray("self");
String href = authorLink.getJSONObject(0).getString("href");
String authorname = object.getString("name");
mAdapter.putAuthor(href, name);
} catch (JSONException w) {
w.printStackTrace();
}
}
public void setPostItems(List<PostItem> postItems) {
mPostItems = postItems;
notifyDataSetChanged();
}
public void putAuthor(String url, String name) {
mAuthorMap.put(url, name);
notifyDataSetChanged();
}
public String getAuthor(String url) {
return mAuthorMap.get(url);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof CardDetails) {
final PostItem postItem = mPostItems.get(position);
((CardDetails) holder).postTitle.setText(Html.fromHtml(postItem.getPostTitle()));
String name = mAuthorMap.get(postItem.getPostAuthorUrl());
if (name != null) {
((CardDetails) holder).postAuthor.setText(name);
}
// don't worry if author name is null, when it's retrieved
// the adapter will be notified to refresh the list
} else {
((ProgressViewHolder) holder).progressBar.setIndeterminate(true);
}
}
// notice that authorhref is final
private void getAuthor (final String authorhref) {
Log.d(TAG, "getAuthor called");
JsonObjectRequest authorRequest = new JsonObjectRequest(authorhref, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, "onResponse called");
parseAuthor(authorhref, response); // pass authorhref with response
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Do nothing
}
});
authorRequest.setShouldCache(false);
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(authorRequest);
}
private void parseAuthor (String authorhref, JSONObject object) {
Log.d(TAG, "Parsing author");
try {
String authorname = object.getString("name");
mAdapter.putAuthor(authorhref, name);
} catch (JSONException w) {
w.printStackTrace();
}
}