我的行为很奇怪。当我在QuestionMenuAdapter中访问我的列表时。 我有四个类。
1.TestActivity 2.TestActivityDrawerFragment 3.QuestionMenuAdapter 4.QuestionFetch
我正在做的是...... 我在 TestActivity 类中创建了 QuestionFetch 类的对象。 然后我通过 setUp 方法将问题列表(我从QuestionFetch类中获取)传递给 TestActivityDrawerFragment , 这里列表获取表单TestActivity传递给 QuestionMenuAdapter 。现在在 QuestionMenuAdapter 中,在 onBindViewHolder()我逐个问我的问题....但我得到 NPE
下面是我的代码 QuestionFetch 类
public class QuestionFetch {
List<Question> questionList=new ArrayList<>();
public List<Question> getQuestionList() {
return questionList;
}
public QuestionFetch()
{
for(int i=0;i<15;++i)
{
String option[]=new String[4];
Question item=new Question();
item.setQuestion("What is my name"+i);
item.setCorrectOptionIndex(i%4);
item.setNegativeMarks("1/2");
item.setSolution("deepak is name set by mom"+i);
item.setTypeOfQuestion("four");
for(int j=0;j<4;++j)
option[j]="deepak"+(i+j);
item.setOptions(option);
questionList.add(item);
}
}
}
现在在TestActivity中我正在创建QuestionFetch类的对象
questionFetch=new QuestionFetch();
drawerFragment=(TestActivityDrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.test_navigation_drawer_fragment);
// here passing the list of Questions to setUp method of TestActivityDrawerFragment
drawerFragment.setUp((DrawerLayout) findViewById(R.id.test_drawer_layout),questionFetch.getQuestionList());
现在在 TestActivityDrawerFragment 类
中public void setUp( DrawerLayout drawerLayout,List<Question> data) {
this.data=data;}
并在onCreateView中将此列表传递给 QuestionMenuAdapter
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
data=new QuestionFetch().getQuestionList();
// here is list is in data
adapter=new QuestionMenuAdapter(getActivity(),data);
adapter.setOnClickListener(this);
return inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
}
最后我在 QuestionMenuAdapter 类
中的 onBindViewHolder()中访问我的列表public class QuestionMenuAdapter extends RecyclerView.Adapter<QuestionMenuAdapter.PageViewHolder>{
Context context;
boolean addOrRemoveItemClicked=false;
private LayoutInflater inflater;
ClickListener clickListener;
List<Question> data= Collections.emptyList();
public QuestionMenuAdapter(Context context, List<Question> data)
{
inflater = LayoutInflater.from(context);
this.context=context;
this.data=data;
//here i have checked that my question is getting but not in onBindVievHolder
Toast.makeTosat(context,""+this.data.get(0).getQuestion,Toast.LENGTH_SHORT).show();
}
@Override
public void onBindViewHolder(QuestionMenuAdapter.PageViewHolder holder, int position) {
holder.customTextView.setText(""+(position+1));
// here i m getting NPE
holder.questionText.setText(data.get(position).getQuestion());
}