Android Studio,RecyclerView在启动时崩溃我的应用程序

时间:2015-06-18 19:33:12

标签: android android-recyclerview

我正在与android Recyclerviewer作斗争。我跟随了大多数教程并在StackOverflow上阅读了这些帖子,但我仍然没有做对。

MainActivity

public class MainActivity extends ActionBarActivity {
RecyclerView myrecyclerView;
MyAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    myrecyclerView = (RecyclerView)findViewById(R.id.myRecycleView);
    adapter = new MyAdapter(MainActivity.this, getData());
    final LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    myrecyclerView.setLayoutManager(layoutManager);
    myrecyclerView.setAdapter(adapter);
    myrecyclerView.setItemAnimator(new DefaultItemAnimator());

    //
}
//the Dataset
public static List<MyDataModel> getData()
{
    List<MyDataModel> myData = new ArrayList<>();
    String[] postText = {"ibm", "apple", "google", "microsoft"};
    int[] postImgUrl = {R.drawable.google, R.drawable.ibm, R.drawable.microsoft, R.drawable.apple};

    for(int x=0; x<postText.length && x<postImgUrl.length; x++)
    {
        MyDataModel myModel = new MyDataModel();
        myModel.postImgUrl = postImgUrl[x];
        myModel.postText = postText[x];
        myData.add(myModel);
    }
    return myData;
}

MyAdapter

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

List<MyDataModel> MyDataset;
private LayoutInflater inflater;
public MyAdapter(Context cont, List<MyDataModel> MyDataset)
{
    inflater = LayoutInflater.from(cont);
}

public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int ViewType)
{
    //get ItemLayoutView from xml
    View itemLayoutView = inflater.inflate(R.layout.my_items_row, parent, false);
    //pass it to the ViewHolder
    ViewHolder myViewHolder = new ViewHolder(itemLayoutView);
    return myViewHolder;
}

public void onBindViewHolder(ViewHolder viewHolder, int position)
{
    viewHolder.postText.setText(MyDataset.get(position).postText);
    viewHolder.postImage.setImageResource(MyDataset.get(position).postImgUrl);
}

public int getItemCount()
{
   return MyDataset.size();
}

public static class ViewHolder extends RecyclerView.ViewHolder
{
    public TextView postText;
    public ImageView postImage;

    public ViewHolder(View v)
    {
        super(v);
        postText = (TextView)v.findViewById(R.id.myPostText);
        postImage = (ImageView)v.findViewById(R.id.myPostImage);
    }

}
}

我的模型数据

public class MyDataModel {
String postText;
int postImgUrl;
 }

我正在通过Android工作室测试真实设备,我正在测试的其他应用程序也很好。 请帮忙谢谢。

1 个答案:

答案 0 :(得分:1)

您未在MyDataset

中初始化MyAdapter