查看SQLite数据库时,片段listview崩溃

时间:2018-12-04 07:37:03

标签: android android-sqlite

当我向下滚动到页面的最底部时,片段使我的应用程序崩溃 列表显示。它可以在具有相同代码的其他片段上工作,但只会在该特定片段上崩溃。请帮助我,我真的不知道该怎么办。 我的代码有什么问题吗?如果有,请指出。我真的很感激。

public class LunchFragment extends Fragment {
    ListView userFoods;
    SQLiteOpenHelper helper,helper1;
    SQLiteDatabase db,db1;
    String name,allergy,condition="";
    Double bmi=0.0;

    ArrayList<String> listItemz;
    ArrayAdapter adapter2;
    public LunchFragment() {
        // Required empty public constructor
    }

    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View view1 = inflater.inflate(R.layout.fragment_lunch,container,false);
        helper1=new Database(getActivity());
        db1=helper1.getReadableDatabase();
        helper= new FoodDB(getActivity());
        db=helper.getReadableDatabase();
        userFoods=(ListView)view1.findViewById(R.id.userFoods);
        listItemz= new ArrayList<>();
        try {
            getStats();
            disorderz();
            viewData();
            adapter2= new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1,listItemz);
            userFoods.setAdapter(adapter2);
            userFoods.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    String text=userFoods.getItemAtPosition(i).toString();
                    Toast.makeText(getActivity(), ""+text, Toast.LENGTH_SHORT).show();
                }
            });
        }catch (Exception g){
            Toast.makeText(getActivity(), "ERROR", Toast.LENGTH_SHORT).show();
        }
        return view1;
    }

    private void viewData() {
        Cursor cursor=db.rawQuery("SELECT * FROM Lunch",null);

        if(cursor.getCount()==0){
            Toast.makeText(getActivity(), "No data to show", Toast.LENGTH_SHORT).show();
        }else{
            while(cursor.moveToNext()){
                listItemz.add(cursor.getString(cursor.getColumnIndex("Name")));
            }
            adapter2= new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1,listItemz);
            userFoods.setAdapter(adapter2);
        }
        cursor.close();
    }

    public void getStats(){
        Cursor cbm= db1.rawQuery("SELECT bmi FROM "+TABLE_bmi+" WHERE ID = 1",null);
        cbm.moveToFirst();
        bmi=cbm.getDouble(0);
    }
    public void disorderz(){
        Cursor c = db1.rawQuery("SELECT Disorders FROM "+TABLE_info,null);
        c.moveToFirst();
        condition=c.getString(c.getColumnIndex("Disorders"));
    }
}

0 个答案:

没有答案