0

В настоящее время я делаю приложение для Android с фидом, поэтому я могу отобразить небольшой блог, используя пользовательские данные из QuickBlox. Я хотел, чтобы каждая запись появлялась в CardView с изображением и заголовком под ним, а затем, когда пользователь забирает карту, она расширяется, чтобы отобразить более подробную информацию об этом. Однако мои попытки всегда заканчивались тем, что не отображали карты в RecyclerView. У меня есть данные, которые он загружает, но я не знаю, почему он не появляется.Android Studio: 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); 
} 
} 

CustomAdapter:

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> 

Любая помощь с благодарностью. Благодаря!

Edit 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) 

ответ

0

, если я понимаю, что вы хотите, ваш cardView должен быть в другой макет XML не в том же XML с recycleview а затем в ur onCreateViewHolder передайте этот элемент для создания представления, , чтобы узнать abour RecyclerView http://www.vogella.com/tutorials/AndroidRecyclerView/article.html

+0

Хорошо, я переместил CardView в другой XML, но он просто разбился (журнал опубликован в Edit 1 для уменьшения помех комментариев) – Cowboy433

 Смежные вопросы

  • Нет связанных вопросов^_^