我使用静态数据填充回收站视图进行测试。现在,在通过解析json使用动态数据之后,回收器视图没有显示出来。我已经使用控制台检查JSON是否正确解析并显示正确的结果。 这是我的活动代码。
package com.paaltao.activity;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.github.mrengineer13.snackbar.SnackBar;
import com.paaltao.Adapters.CategoryAdapter;
import com.paaltao.R;
import com.paaltao.classes.Category;
import com.paaltao.classes.Product;
import com.paaltao.classes.SharedPreferenceClass;
import com.paaltao.network.VolleySingleton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import static com.paaltao.extras.Keys.ProductList.KEY_DATA;
import static com.paaltao.extras.Keys.ProductList.KEY_ERROR_CODE;
import static com.paaltao.extras.Keys.UserCredentials.*;
import static com.paaltao.extras.Keys.ProductList.*;
import static com.paaltao.extras.urlEndPoints.BASE_URL;
import static com.paaltao.extras.urlEndPoints.CATEGORY_LIST;
import static com.paaltao.extras.urlEndPoints.FEATURED_LIST;
import static com.paaltao.extras.urlEndPoints.UAT_BASE_URL;
public class CategoryActivity extends ActionBarActivity {
private RecyclerView mRecyclerView;
Long id;
private JSONArray categoryListArray;
String accessToken = "67drd56g",imageURL,categoryName;
CategoryAdapter categoryAdapter;
CategoryActivity activity;
private ArrayList<Category> categoryArrayList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category);
sendJsonRequest();
mRecyclerView = (RecyclerView) findViewById(R.id.category_grid_recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
categoryAdapter = new CategoryAdapter(activity,getApplicationContext());
mRecyclerView.setAdapter(categoryAdapter);
Toolbar toolbar = (Toolbar) this.findViewById(R.id.app_bar);
toolbar.setTitleTextColor(Color.WHITE);
this.setSupportActionBar(toolbar);
this.setTitle("Categories");
}
public void sendJsonRequest(){
final JSONObject jsonObject = new JSONObject();
final JSONObject categoryList = new JSONObject();
try{
jsonObject.put("accessToken",accessToken);
categoryList.put("categoryList",jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, getRequestUrl(),categoryList, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
categoryArrayList = parseJsonResponse(jsonObject);
categoryAdapter.setCategoryArrayList(categoryArrayList);
Log.e("categoryList",categoryArrayList.toString());
new SnackBar.Builder(CategoryActivity.this)
.withMessage(jsonObject.toString())
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
Log.e("url", UAT_BASE_URL + CATEGORY_LIST);
Log.e("input_payload",categoryList.toString());
Log.e("error", jsonObject.toString());
Log.e("json", categoryList.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
new SnackBar.Builder(CategoryActivity.this)
.withMessage("No Internet Connection!")
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
} else if (volleyError instanceof AuthFailureError) {
//TODO
} else if (volleyError instanceof ServerError) {
//TODO
} else if (volleyError instanceof NetworkError) {
//TODO
} else if (volleyError instanceof ParseError) {
//TODO
}
}
});
requestQueue.add(jsonObjectRequest);
}
public static String getRequestUrl() {
return UAT_BASE_URL
+ CATEGORY_LIST;
}
public ArrayList<Category> parseJsonResponse(JSONObject response) {
ArrayList<Category> categoryArrayList = new ArrayList<>();
if (response != null && response.length() > 0) {
try {
JSONObject dataObject = response.getJSONObject(KEY_DATA);
if (dataObject.has(KEY_CATEGORY_LIST)) {
categoryListArray = dataObject.getJSONArray(KEY_CATEGORY_LIST);
for (int i = 0; i < categoryListArray.length(); i++) {
JSONObject categoryListObject = categoryListArray.getJSONObject(i);
id = categoryListObject.getLong(KEY_CATEGORY_ID);
categoryName = categoryListObject.getString(KEY_CATEGORY_NAME);
imageURL = categoryListObject.getString(KEY_CATEGORY_IMAGE);
Category category = new Category();
category.setCategory_id(id);
category.setCategory_name(categoryName);
category.setImageURL(imageURL);
categoryArrayList.add(category);
Log.e("id",id.toString());
Log.e("image URL", imageURL);
Log.e("name",categoryName);
}
}
if (response.has(KEY_ERROR_CODE)) {
JSONObject errorObject = response.getJSONObject(KEY_ERROR_CODE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return categoryArrayList;
}
}
我还提供适配器的代码和包含回收站视图的布局
这是我的适配器代码:
package com.paaltao.Adapters;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.paaltao.R;
import com.paaltao.activity.CategoryActivity;
import com.paaltao.activity.ProductDetailsActivity;
import com.paaltao.activity.ProductListActivity;
import com.paaltao.classes.Category;
import com.paaltao.classes.Product;
import com.paaltao.network.VolleySingleton;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by Arindam on 02-Feb-15.
*/
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.CategoryHolder> {
private Context context;
CategoryActivity activity;
private LayoutInflater inflater;
private View view;
private VolleySingleton singleton;
private ImageLoader imageLoader;
private ArrayList<Category> categoryArrayList = new ArrayList<>();
public CategoryAdapter(CategoryActivity activity, Context context){
this.context = context;
this.activity = activity;
singleton = VolleySingleton.getsInstance();
imageLoader = singleton.getImageLoader();
}
@Override
public CategoryHolder onCreateViewHolder(ViewGroup parent, int viewType) {
inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.category_card, parent, false);
CategoryHolder holder = new CategoryHolder(view);
holder.categoryImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(activity,ProductListActivity.class);
activity.startActivity(intent);
}
});
return holder;
}
public void setCategoryArrayList(ArrayList<Category> categoryArrayList){
this.categoryArrayList = categoryArrayList;
notifyItemRangeChanged(0, categoryArrayList.size());
}
@Override
public void onBindViewHolder(final CategoryHolder holder, int position) {
Category current = categoryArrayList.get(position);
holder.categoryName.setText(current.getCategory_name());
final String imageURL = current.getImageURL();
if(imageURL != null){
imageLoader.get(imageURL, new ImageLoader.ImageListener() {
@Override
public void onResponse(ImageLoader.ImageContainer imageContainer, boolean b) {
holder.categoryImage.setImageBitmap(imageContainer.getBitmap());
Log.e("imageURLAdapter",imageURL);
}
@Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("imageURL","no image found");
}
});
}
}
@Override
public int getItemCount() {
return categoryArrayList.size();
}
class CategoryHolder extends RecyclerView.ViewHolder {
TextView categoryName;
ImageView categoryImage;
public CategoryHolder(View itemView) {
super(itemView);
categoryImage = (ImageView) itemView.findViewById(R.id.category_image);
categoryName = (TextView) itemView.findViewById(R.id.category_name);
}
}
}
下面的是包含Recycler视图的布局代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#e2e2e2"
android:orientation="vertical" >
<include
android:id="@+id/app_bar"
layout="@layout/app_bar" />
<!-- A RecyclerView with some commonly used attributes -->
<android.support.v7.widget.RecyclerView
android:id="@+id/category_grid_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
/>
</LinearLayout>
最后这里是回收者视图行的代码
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
card_view:cardCornerRadius="0dp"
card_view:cardUseCompatPadding="false">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="220dp">
<ImageView
android:id="@+id/category_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/apple_small"
android:contentDescription="@string/category_image_text" />
<RelativeLayout
android:id="@+id/transparentOverlay"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/black99" />
<TextView
android:id="@+id/category_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:fontFamily="sans-serif-light"
android:text="Handicrafts"
android:textColor="@color/white"
android:textSize="40sp" />
</RelativeLayout>
</android.support.v7.widget.CardView>
活动根本不显示回收站视图,但日志显示正确的JSON数据。
答案 0 :(得分:2)
在将数据添加到列表后,在Adapter上调用notifyDataSetChanged()。
如果这不起作用。试试这个
像这样改变你的构造函数
...
private ArrayList<Category> categoryArrayList;
public CategoryAdapter(CategoryActivity activity, Context context,ArrayList<Category> categoryArrayList){
this.context = context;
this.activity = activity;
singleton = VolleySingleton.getsInstance();
imageLoader = singleton.getImageLoader();
this.categoryArrayList = categoryArrayList;
}
并在向JSON解析添加数据后调用CategoryAdapter上的notifyDataSetChanged()()。