如何获取对象内部矩阵的数据并在RecyclerView中可视化它们?

时间:2018-07-11 17:52:11

标签: android object arraylist android-recyclerview retrofit2

由于我不知道如何获取对象内部排列的数据,因此我刚接触Android问题

这是我的网络服务的数据:

{"data":{"categories":[{"id":1,"name":"Whisky","photo":null,"photo_url":null,"created_at":"2018-07-06 17:28:15","updated_at":"2018-07-10 15:38:22"},{"id":2,"name":"Ron","photo":null,"photo_url":null,"created_at":"2018-07-10 15:37:56","updated_at":"2018-07-10 15:38:28"},{"id":3,"name":"Pisco","photo":null,"photo_url":null,"created_at":"2018-07-10 15:38:38","updated_at":"2018-07-10 15:38:38"},{"id":4,"name":"Vodka","photo":null,"photo_url":null,"created_at":"2018-07-10 15:38:44","updated_at":"2018-07-10 15:39:45"},{"id":5,"name":"Vino","photo":null,"photo_url":null,"created_at":"2018-07-10 15:39:56","updated_at":"2018-07-10 15:39:56"},{"id":6,"name":"Cerveza","photo":null,"photo_url":null,"created_at":"2018-07-10 15:40:02","updated_at":"2018-07-10 15:40:02"}]}}

我在模型中使用Json pojo:

public class Category {

@SerializedName("data")
@Expose
private Data data;

public Data getData() {
    return data;
}

public void setData(Data data) {
    this.data = data;
}

@Override
public String toString() {
    return "Category{" +
            "data=" + data +
            '}';
}

}

public class Category_ {

@SerializedName("id")
@Expose
private Integer id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("photo")
@Expose
private Object photo;
@SerializedName("photo_url")
@Expose
private Object photoUrl;
@SerializedName("created_at")
@Expose
private String createdAt;
@SerializedName("updated_at")
@Expose
private String updatedAt;

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Object getPhoto() {
    return photo;
}

public void setPhoto(Object photo) {
    this.photo = photo;
}

public Object getPhotoUrl() {
    return photoUrl;
}

public void setPhotoUrl(Object photoUrl) {
    this.photoUrl = photoUrl;
}

public String getCreatedAt() {
    return createdAt;
}

public void setCreatedAt(String createdAt) {
    this.createdAt = createdAt;
}

public String getUpdatedAt() {
    return updatedAt;
}

public void setUpdatedAt(String updatedAt) {
    this.updatedAt = updatedAt;
}

@Override
public String toString() {
    return "Category_{" +
            "id=" + id +
            ", name='" + name + '\'' +
            ", photo=" + photo +
            ", photoUrl=" + photoUrl +
            ", createdAt='" + createdAt + '\'' +
            ", updatedAt='" + updatedAt + '\'' +
            '}';
}

}


public class Data {

@SerializedName("categories")
@Expose
private List<Category_> categories;

public List<Category_> getCategories() {
    return categories;
}

public void setCategories(List<Category_> categories) {
    this.categories = categories;
}

@Override
public String toString() {
    return "Data{" +
            "categories=" + categories +
            '}';
}

}


然后我使用改造来获取数据,但是我只是带了对象,并且我只想使用该对象内部的数组通过带有AdapterView的RecyclerView来显示它

ApiService.java

@GET("/api/getCategories")
Call<Category> getCategories();

MainActivity.java

public class MainActivity extends AppCompatActivity{

private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView categoriesList;


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

//HERE IS THE PROBLEM, I DONT KNOW HOW CREATE AN ADAPTER FOR CATEGORIES
        categoriesList =(RecyclerView)findViewById(R.id.recyclerCategoryView);
        categoriesList.setLayoutManager(new LinearLayoutManager(this));

        //categoriesList.setAdapter(new CategoriesAdapter());

        initialize();

}

private void initialize() {

    ApiService service = ApiServiceGenerator.createService(ApiService.class);

    Call<Category> call = service.getCategories();

    call.enqueue(new Callback<Category>() {
        @Override
        public void onResponse(@NonNull Call<Category> call, @NonNull Response<Category> response) {
            try {

                int statusCode = response.code();
                Log.d(TAG, "HTTP status code: " + statusCode);

                if (response.isSuccessful()) {

                    Category categories = response.body();
                    Log.d(TAG, "Categorias: " + categories.getData().getCategories());

//THIS IS THE SAME PROBLEM
                    //CategoriesAdapter adapter = (CategoriesAdapter) categoriesList.getAdapter();
                    //adapter.setCategories(categories);
                    //adapter.notifyDataSetChanged();

                } else {
                    Log.e(TAG, "onError: " + response.errorBody().string());
                    throw new Exception("Error en el servicio");
                }

            } catch (Throwable t) {
                try {
                    Log.e(TAG, "onThrowable: " + t.toString(), t);
                    Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
                }catch (Throwable x){}
            }
        }
        @Override
        public void onFailure(Call<Category> call, Throwable t) {
            Log.e(TAG, "onFailure: " + t.toString());
            Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
        }

    });
}

最后,我尝试制作适配器,但这是错误的!!

CategoriesAdapter.java

public class CategoriesAdapter  extends RecyclerView.Adapter<CategoriesAdapter.ViewHolder> {

private Data listData;

public CategoriesAdapter(){
    this.listData = new Data();
}

public void setCategories(Data listData){
    this.listData = listData;
}

public class ViewHolder extends RecyclerView.ViewHolder{

    public ImageView imagenCatView;
    public TextView nombreCatText;

    public ViewHolder(View itemView) {
        super(itemView);
        //imagenView = itemView.findViewById(R.id.picture_image);
        nombreCatText = itemView.findViewById(R.id.name_cat_text);
    }
}


@Override
public CategoriesAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_categories_products,
            parent, false);
    return new ViewHolder(itemView);

}

@Override
public void onBindViewHolder(CategoriesAdapter.ViewHolder viewHolder, int position) {
    Category_ category = this.listData.getCategories().get(position);

    viewHolder.nombreCatText.setText(category.getName());
    //viewHolder.precioText.setText("S/. " + product.getPrice());
    //viewHolder.descripcionText.setText(product.getDescription());

    //String url = ApiService.API_BASE_URL + "/images/" + product.getImage();
    //Picasso.with(viewHolder.itemView.getContext()).load(url).into(viewHolder.imagenView);

}

@Override
public int getItemCount() {
    return this.listData.getCategories().size();
}

}

错误:

java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
    at pe.bazan.jhosep.com.barapp.Adapters.CategoriesAdapter.getItemCount(CategoriesAdapter.java:66)
    at android.support.v7.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:3603)
    at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:3103)
    at android.view.View.measure(View.java:18804)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
    at android.view.View.measure(View.java:18804)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
    at android.view.View.measure(View.java:18804)
    at android.widget.ScrollView.measureChildWithMargins(ScrollView.java:1286)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
    at android.widget.ScrollView.onMeasure(ScrollView.java:340)
    at android.view.View.measure(View.java:18804)
    at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
    at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
    at android.view.View.measure(View.java:18804)
    at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1060)
    at android.view.View.measure(View.java:18804)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
    at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
    at android.view.View.measure(View.java:18804)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954)
    at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:400)
    at android.view.View.measure(View.java:18804)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
    at android.view.View.measure(View.java:18804)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
    at android.view.View.measure(View.java:18804)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
    at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
    at android.view.View.measure(View.java:18804)
    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2112)
    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1228)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1464)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1119)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6060)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
    at android.view.Choreographer.doCallbacks(Choreographer.java:670)
    at android.view.Choreographer.doFrame(Choreographer.java:606)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
    at android.os.Handler.handleCallback(Handler.java:746)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5443)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
    at com.android.internal.os.ZygoteInit.main(Zygot

0 个答案:

没有答案