Android Studio:RecyClerview未显示数据



我当前正在用feed制作一个Android应用程序,因此我可以使用QuickBlox的自定义数据显示一个小博客。我想每个记录都出现在带有图片和标题下面的标题的卡片视图中,然后当用户点击卡时,它会扩展以显示有关它的更多详细信息。但是,我的尝试总是最终无法在Recyclerview上显示卡片。我确实有下载的数据,但我不知道为什么不显示它。

保存主要代码的片段是HomeRecyclerViewFragment,适配器为CustomAdapter,而布局XML为fragment_home.xml

homerecyClerviewFragment:

public class HomeRecyclerViewFragment extends Fragment {
private static final String TAG = "HomeRecyclerViewFragment";
private static final String KEY_LAYOUT_MANAGER = "layoutManager";
private static final int SPAN_COUNT = 2;
private static final int DATASET_COUNT = 60;
private QBCustomObject qbco;
public static ProgressDialog dia;
HashMap<String, Object> fields = new HashMap<String, Object>();
public List<String> ids;
Handler myHandler;
private enum LayoutManagerType {
    GRID_LAYOUT_MANAGER,
    LINEAR_LAYOUT_MANAGER
}
protected LayoutManagerType mCurrentLayoutManagerType;
protected CardView mLinearLayoutRadioButton;
protected CardView mGridLayoutRadioButton;
protected RecyclerView mRecyclerView;
protected CustomAdapter mAdapter;
protected RecyclerView.LayoutManager mLayoutManager;
protected String[] mDataset;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Initialize dataset, this data would usually come from a local content provider or
    // remote server.
    dia = ProgressDialog.show(this.getContext(), null,"Downloading recent posts...");
    dia.show();
    initDataset();
    myHandler = new Handler();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_home, container, false);
    rootView.setTag(TAG);
    mRecyclerView = (RecyclerView) rootView.findViewById(R.id.homerecyclerview);
    // LinearLayoutManager is used here, this will layout the elements in a similar fashion
    // to the way ListView would layout elements. The RecyclerView.LayoutManager defines how
    // elements are laid out.
    mLayoutManager = new LinearLayoutManager(getActivity());
    mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;
    if (savedInstanceState != null) {
        // Restore saved layout manager type.
        mCurrentLayoutManagerType = (LayoutManagerType) savedInstanceState
                .getSerializable(KEY_LAYOUT_MANAGER);
    }
    setRecyclerViewLayoutManager(mCurrentLayoutManagerType);
    mAdapter = new CustomAdapter(mDataset);
    // Set CustomAdapter as the adapter for RecyclerView.
    //mRecyclerView.setAdapter(mAdapter);
    mLinearLayoutRadioButton = (CardView) rootView.findViewById(R.id.card_view);
    mLinearLayoutRadioButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setRecyclerViewLayoutManager(LayoutManagerType.LINEAR_LAYOUT_MANAGER);
        }
    });
    //mRecyclerView.setAdapter(mAdapter);
    updateUI();
    return rootView;
}
/**
 * @param layoutManagerType Type of layout manager to switch to.
 */
public void setRecyclerViewLayoutManager(LayoutManagerType layoutManagerType) {
    int scrollPosition = 0;
    // If a layout manager has already been set, get current scroll position.
    if (mRecyclerView.getLayoutManager() != null) {
        scrollPosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager())
                .findFirstCompletelyVisibleItemPosition();
    }
    switch (layoutManagerType) {
        case GRID_LAYOUT_MANAGER:
            mLayoutManager = new GridLayoutManager(getActivity(), SPAN_COUNT);
            mCurrentLayoutManagerType = LayoutManagerType.GRID_LAYOUT_MANAGER;
            break;
        case LINEAR_LAYOUT_MANAGER:
            mLayoutManager = new LinearLayoutManager(getActivity());
            mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;
            break;
        default:
            mLayoutManager = new LinearLayoutManager(getActivity());
            mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;
    }
    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.scrollToPosition(scrollPosition);
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save currently selected layout manager.
    savedInstanceState.putSerializable(KEY_LAYOUT_MANAGER, mCurrentLayoutManagerType);
    super.onSaveInstanceState(savedInstanceState);
}

private void initDataset() {
    QBCustomObjects.getObjects("posts", (QBCallback) qbco, new QBCallbackImpl() {
        @Override
        public void onComplete(Result result) {
            if (result.isSuccess()) {
                Log.i(this.toString(),"Retrieved posts successfully.");
                dia.dismiss();
                QBCustomObjectLimitedResult coresult = (QBCustomObjectLimitedResult) result;
                ArrayList<QBCustomObject> co = coresult.getCustomObjects();

                int sum = 0;
                for (int i = 0; i < co.size(); ++i) {
                    ids.add(co.get(i).getCustomObjectId());
                    sum += Arrays.toString(co.toArray()).toCharArray()[i];
                }
                String[] stockArr = new String[ids.size()];
                stockArr = ids.toArray(stockArr);
                mDataset = stockArr;
                updateUI();
            } else {
                dia.dismiss();
                Log.e("Errors",result.getErrors().toString());
            }
        }
    });
    dia.dismiss();
}
private void updateUI() {
    mAdapter = new CustomAdapter(mDataset);
    mRecyclerView.setAdapter(mAdapter);
}
}

"定制":

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private String[] mDataset;
private Uri[] imgUriList;
private List<String> listOfTitles;
private QBCustomObject qbco;
public ProgressDialog dia;
HashMap<String, Object> fields = new HashMap<String, Object>();
public List<String> ids;

private String id;
private String name;
private String description;
private String year;
private float rating;
private long date;
Handler myHandler;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class MyViewHolder extends RecyclerView.ViewHolder {
    public CardView mCardView;
    public TextView mTextView;
    public MyViewHolder(View v) {
        super(v);
        mCardView = (CardView) v.findViewById(R.id.card_view);
        mTextView = (TextView) v.findViewById(R.id.info_text);
    }
}
// Provide a suitable constructor (depends on the kind of dataset)
public CustomAdapter(String[] myDataset) {
    mDataset = myDataset;
}
// Create new views (invoked by the layout manager)
@Override
public CustomAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
                                                 int viewType) {
    // create a new view
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.fragment_home, parent, false);
    // set the view's size, margins, paddings and layout parameters
    MyViewHolder vh = new MyViewHolder(v);
    dia = ProgressDialog.show(v.getContext(), null,"Downloading recent posts...");
    dia.show();
    myHandler = new Handler();
    //initQb();
    return vh;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    holder.mTextView.setText(mDataset[position]);
}
@Override
public int getItemCount() {
    if (mDataset != null) return mDataset.length;
    else return 0;
}
public void initQb() {
    QBCustomObjects.getObjects("posts", (QBCallback) qbco, new QBCallbackImpl() {
        @Override
        public void onComplete(Result result) {
            if (result.isSuccess()) {
                QBCustomObjectLimitedResult coresult = (QBCustomObjectLimitedResult) result;
                ArrayList<QBCustomObject> co = coresult.getCustomObjects();
                dia.dismiss();
                Log.println(Log.INFO,"PostGetHandler","Retrieved posts successfully.");
                int sum = 0;
                for (int i = 0; i < co.size(); ++i) {
                    ids.add(co.get(i).getCustomObjectId().toString());
                    sum += co.toArray().toString().toCharArray()[i];
                }
                String[] stockArr = new String[ids.size()];
                stockArr = ids.toArray(stockArr);
                CustomAdapter ca = new CustomAdapter(stockArr);
            } else {
                dia.dismiss();
                Log.e("Errors",result.getErrors().toString());
            }
        }
    });
}
}

fragment_home.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
android:id="@+id/linearlayoutv"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:background="@drawable/splashscreen">

<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/homerecyclerview">    </android.support.v7.widget.RecyclerView>
<android.support.v7.widget.CardView
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    card_view:cardCornerRadius="4dp"
    android:layout_weight="0.25"
    android:layout_height="match_parent"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginTop="5dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="212dp"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/info_text"
            android:layout_width="347dp"
            android:layout_height="34dp"
            android:textSize="16sp"
            android:foregroundGravity="bottom"
            android:gravity="bottom"
            android:layout_marginTop="180dp" />
        <ImageView
            android:id="@+id/myImage"
            android:layout_width="wrap_content"
            android:layout_gravity="fill_horizontal"
            android:layout_height="wrap_content" />

    </LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>

任何帮助将不胜感激。谢谢!

编辑1:新的错误日志(向右滚动显示其余的)

FATAL EXCEPTION: main
                                                                                Process: com.example.adamangle.ameroboticsapp, PID: 2977
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.CardView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                                                    at io.github.adamangle.ameroboticsapp.fragments.HomeRecyclerViewFragment.onCreateView(HomeRecyclerViewFragment.java:105)
                                                                                    at android.support.v4.app.Fragment.performCreateView(Fragment.java:2074)
                                                                                    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
                                                                                    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1286)
                                                                                    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:758)
                                                                                    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1671)
                                                                                    at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:532)
                                                                                    at android.os.Handler.handleCallback(Handler.java:739)
                                                                                    at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                    at android.os.Looper.loop(Looper.java:135)
                                                                                    at android.app.ActivityThread.main(ActivityThread.java:5221)
                                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                                    at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
                                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

如果我了解您想要的内容,则您的cardView应该在另一个布局xml中,与recycleview在同一xml中,然后在ur un createviewholder中通过该项目创建视图,视图,要学习Abour Recyclerview http://www.vogella.com/tutorials/androidrecyclerview/article.html

相关内容

  • 没有找到相关文章

最新更新