我在CrimeFragment上收到空指针引用错误。
crimeFragment&onCreateView方法:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_crime, container, false);
try {
Button submit = (Button) view.findViewById(R.id.submitButton);
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Cant save yet!", Toast.LENGTH_SHORT).show();
EditText id = (EditText) view.findViewById(R.id.crimeID);
EditText des = (EditText) view.findViewById(R.id.crimeDesc);
Crime crime = new Crime();
String desS = des.getText().toString();
String idS = (id.getText().toString());
if(desS == null || idS == null){
Toast.makeText(getContext(),"Blank fields !",Toast.LENGTH_SHORT).show();
return;
}
crime.setId(Integer.parseInt(desS));
crime.setDesc(desS);
addCrime(crime);
}
});
}
catch(Exception e){
e.printStackTrace();
}
return view;
}
我已阅读片段生命周期文档&所以只有在OnCreateView中对它们进行充气后才抓取视图组件。那么为什么它会显示空对象?
MainActivity类:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
CrimeFragment frag = (CrimeFragment) fm.findFragmentById(R.id.main_container);
if(frag == null){
frag = new CrimeFragment();
fm.beginTransaction()
.add(R.id.main_container,frag)
.commit();
}
List<Crime> crimeList = frag.getCrime();
}
非常欢迎任何建议。
答案 0 :(得分:0)
将此editText casting code
移到onClick
View view = inflater.inflate(R.layout.fragment_crime, container, false);
try {
Button submit = (Button) view.findViewById(R.id.submitButton);
EditText id = (EditText) view.findViewById(R.id.crimeID);
EditText des = (EditText) view.findViewById(R.id.crimeDesc);
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Cant save yet!", Toast.LENGTH_SHORT).show();
Crime crime = new Crime();
String desS = des.getText().toString();
String idS = (id.getText().toString());
if(desS == null || idS == null){
Toast.makeText(getContext(),"Blank fields !",Toast.LENGTH_SHORT).show();
return;
}
crime.setId(Integer.parseInt(desS));
crime.setDesc(desS);
addCrime(crime);
}
});