2015-09-23 46 views
-3

當我嘗試運行我的應用程序時,出現一個錯誤,說我正試圖調用空對象上的方法。我知道錯誤發生在哪裏,但我不確定爲什麼,因爲我以爲我早些時候初始化了這個對象。
代碼如下:嘗試調用空對象錯誤的方法[android]

public class InjuryListFragment extends Fragment{ 
    private RecyclerView mInjuryRecyclerView; 
    private InjuryAdapter mAdapter; 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ 
     View view=inflater.inflate(R.layout.fragment_injury_list, container, false); 
     mInjuryRecyclerView=(RecyclerView)view.findViewById(R.id.injury_recycler_view); 
     mInjuryRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); 
     updateUI(); 
     return view; 
    } 
    private void updateUI(){ 
     InjuryLab injuryLab=InjuryLab.get(getActivity()); 
     List<Injury>injuries=injuryLab.getInjuries(); 
     mAdapter=new InjuryAdapter(injuries); 
     mInjuryRecyclerView.setAdapter(mAdapter); 

    } 
    private class InjuryHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ 

     private TextView mTitleTextView; 
     private TextView mDescriptionTextView; 
     private Injury mInjury; 
     public InjuryHolder(View itemView){ 
      super(itemView); 
      itemView.setOnClickListener(this); 
      mTitleTextView=(TextView)itemView.findViewById(R.id.list_item_injury_title_text_view); 
      mDescriptionTextView=(TextView)itemView.findViewById(R.id.injury_description); 
     } 
     public void bindInjury(Injury injury){ 
      mInjury=injury; 
      mTitleTextView.setText(mInjury.getTitle()); 
      mDescriptionTextView.setText(mInjury.getDescription()); 
     } 
     @Override 
     public void onClick(View v){ 
      Intent intent=InjuryActivity.newIntent(getActivity(), mInjury.getId()); 
      startActivity(intent); 
     } 
    } 

就行發生錯誤mDescriptionTextView.setText(mInjury.getDescription());

+1

告訴我們錯誤特別是,甚至更好的後logcat。是空對象'mDescriptionTextView'還是'mInjury'? – Breavyn

+0

的logcat的是如下 09-23 00:03:37.106 19159-19159/com.bignerdranch.android.firstaid E/AndroidRuntime:致命異常:主 工藝:com.bignerdranch.android.firstaid,PID:19159 java.lang.NullPointerException:嘗試在空對象引用 處調用虛方法'void android.widget.TextView.setText(java.lang.CharSequence)'at com.bignerdranch.android.firstaid.InjuryListFragment $ InjuryHolder.bindInjury(InjuryListFragment .java:54) at com.bignerdranch.android.firstaid.InjuryListFragment $ InjuryAdapter.onBindViewHolder(InjuryListFragment.java:79) – Bukimon

+0

發佈您的適配器代碼。 – arun

回答

0

仔細檢查的意見,XML和code.Check無論你是初始化TextView.Also檢查是否之前設置文本的ID構造函數中執行bindInjury方法之前調用

0

試試這個

public void bindInjury(Injury injury){ 
    if(injury != null){ 
    mInjury=injury; 
    } 
    mTitleTextView.setText(mInjury.getTitle()); 
    mDescriptionTextView.setText(mInjury.getDescription()); 
} 
相關問題