0

I have exception in onDestroy()

public class FragmentList extends 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();
    }
}

log

E/AndroidRuntime: FATAL EXCEPTION: main Process: ru.bunakov.testapplication, PID: 30583 java.lang.NullPointerException at ru.bunakov.testapplication.fragments.FragmentList.onDestroy(FragmentList.java:85) at android.app.Fragment.performDestroy(Fragment.java:1913) at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1013) at android.app.FragmentManagerImpl.removeFragment(FragmentManager.java:1167) at android.app.BackStackRecord.run(BackStackRecord.java:654) at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)

Evgeny GooDi
  • 159
  • 2
  • 3
  • 12
  • Normally, the database should not be closed. However, try moving super.onDestroy to after your close calls. – Ali May 02 '16 at 12:31
  • Exception when im trying close db. Cursor close normally – Evgeny GooDi May 02 '16 at 12:34
  • you have declared variable db twice and initializing it only once that too in limited scope so te globally declares db variable is still null – Vishal Mokal May 02 '16 at 12:36
  • You're declaring `db` in your `try-catch` in `onCreateView` and you are assinging to that variable, not the global one which you are trying to close. – Ali May 02 '16 at 12:39

2 Answers2

2

You are using global reference, but you did not initialize it, you just localized the db. Please Change your code in try catch block to below:

    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();
    }
Saritha G
  • 2,588
  • 1
  • 15
  • 27
0

You had declared db variable twice and initializing it only once that too in limited scope so globally declare variable is still null so try following changes

  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();
}

}

Vishal Mokal
  • 792
  • 1
  • 5
  • 22