关闭db时 - java.lang.NullPointerException

时间:2016-05-02 12:27:59

标签: java android nullpointerexception

我在onDestroy()

中有异常

公共类FragmentList扩展了Fragment {

    private ListView listView;
    private FloatingActionButton fab;
    private Cursor cursor;
    private SQLiteDatabase db;
    boolean isAvatar;
    String nameText;

    public FragmentList() {
        // Обязателен открытый/публичный пустой конструктор
    }

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

        View v = inflater.inflate(R.layout.fragment_list, container, false);
        fab = (FloatingActionButton) v.findViewById(R.id.fab);
        listView = (ListView) v.findViewById(R.id.listView);


        //обработка добавления человека - нажатие на fab
        fab.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                //TODO добавление!!!
                Toast.makeText(v.getContext(), "Новая запись добавлена", Toast.LENGTH_SHORT).show();
            }
        });

        //создание курсора
        try{
            SQLiteOpenHelper databaseHelper = new DatabaseHelper(v.getContext());
            SQLiteDatabase db = databaseHelper.getWritableDatabase();
            Cursor cursor = db.query("PEOPLE", new String[] {"_id", "NAME", "CHECKBOX"}, null, null, null, null, null);
            CursorAdapter listAdapter = new SimpleCursorAdapter(v.getContext(), R.layout.list_item, cursor, new String[]{"NAME", "CHECKBOX"}, new int[]{R.id.name, R.id.checkBox}, 0);
            listView.setAdapter(listAdapter);

        } catch (SQLiteException e){
            Toast.makeText(v.getContext(), "База данных недоступна", Toast.LENGTH_SHORT).show();
        }



        return v;
}



    //обработка нажатия пункте списка
    public void onListItemClick(){

    }

    //закрытие базы данных и курсора
    @Override
    public void onDestroy(){
        super.onDestroy();
        if (cursor!=null) cursor.close();
        if (db.isOpen()) db.close();
    }
}

日志

E / AndroidRuntime:致命异常:主要                                                    过程:ru.bunakov.testapplication,PID:30583                                                    显示java.lang.NullPointerException                                                        at ru.bunakov.testapplication.fragments.FragmentList.onDestroy(FragmentList.java:85)                                                        在android.app.Fragment.performDestroy(Fragment.java:1913)                                                        在android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1013)                                                        在android.app.FragmentManagerImpl.removeFragment(FragmentManager.java:1167)                                                        在android.app.BackStackRecord.run(BackStackRecord.java:654)                                                        在android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)

2 个答案:

答案 0 :(得分:2)

您正在使用全局引用,但是您没有初始化它,您只是本地化了db。请将try catch块中的代码更改为以下内容:

    try{
        SQLiteOpenHelper databaseHelper = new DatabaseHelper(v.getContext());
        //Changed db reference intlo global.
        db = databaseHelper.getWritableDatabase();
        Cursor cursor = db.query("PEOPLE", new String[] {"_id", "NAME", "CHECKBOX"}, null, null, null, null, null);
        CursorAdapter listAdapter = new SimpleCursorAdapter(v.getContext(), R.layout.list_item, cursor, new String[]{"NAME", "CHECKBOX"}, new int[]{R.id.name, R.id.checkBox}, 0);
        listView.setAdapter(listAdapter);

    } catch (SQLiteException e){
        Toast.makeText(v.getContext(), "База данных недоступна", Toast.LENGTH_SHORT).show();
    }

答案 1 :(得分:0)

  

你已经两次声明了db变量并且只在有限的范围内初始化它一次,所以全局声明变量仍为null所以请尝试跟随更改

  private ListView listView;
private FloatingActionButton fab;
private Cursor cursor;
private SQLiteDatabase db;
boolean isAvatar;
String nameText;

public FragmentList() {
    // Обязателен открытый/публичный пустой конструктор
}

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

    View v = inflater.inflate(R.layout.fragment_list, container, false);
    fab = (FloatingActionButton) v.findViewById(R.id.fab);
    listView = (ListView) v.findViewById(R.id.listView);


    //обработка добавления человека - нажатие на fab
    fab.setOnClickListener(new View.OnClickListener() {
        @Override public void onClick(View v) {
            //TODO добавление!!!
            Toast.makeText(v.getContext(), "Новая запись добавлена", Toast.LENGTH_SHORT).show();
        }
    });

    //создание курсора
    try{
        SQLiteOpenHelper databaseHelper = new DatabaseHelper(v.getContext());

       //////**** make following change  it might work*****//// 

       db = databaseHelper.getWritableDatabase();
        Cursor cursor = db.query("PEOPLE", new String[] {"_id", "NAME", "CHECKBOX"}, null, null, null, null, null);
        CursorAdapter listAdapter = new SimpleCursorAdapter(v.getContext(), R.layout.list_item, cursor, new String[]{"NAME", "CHECKBOX"}, new int[]{R.id.name, R.id.checkBox}, 0);
        listView.setAdapter(listAdapter);

    } catch (SQLiteException e){
        Toast.makeText(v.getContext(), "База данных недоступна", Toast.LENGTH_SHORT).show();
    }
    return v;

}

//обработка нажатия пункте списка
public void onListItemClick(){

}

//закрытие базы данных и курсора
@Override
public void onDestroy(){
    super.onDestroy();
    if (cursor!=null) cursor.close();
    if (db.isOpen()) db.close();
}

}