A
A
Alexander Sinitsyn2016-03-25 09:25:28
Android
Alexander Sinitsyn, 2016-03-25 09:25:28

Why is there an error when executing such code with SimpleCursorAdapter?

public class NotesFragment extends Fragment {

    DBHelper dbHelper;
    ListView lvData;
    String TABLE_NAME = "t_notes";
    SimpleCursorAdapter scAdapter;
    Cursor cursor;
    SQLiteDatabase database;

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

        View rootView = inflater.inflate(R.layout.fragment_notes, container, false);

        lvData = (ListView) getActivity().findViewById(R.id.listView);

        // создаем объект для создания и управления версиями БД
        dbHelper = new DBHelper(getActivity());

        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        // открываем подключение
        database = dbHelper.getReadableDatabase();

        //получаем данные из бд
        cursor =  database.query(TABLE_NAME, null, null, null, null, null, null);
//        getActivity().startManagingCursor(cursor);

        String[] from = new String[] { "f_name" };
        int[] to = new int[] { R.id.textName };

        // создаем адаптер и настраиваем список
        scAdapter = new SimpleCursorAdapter(getActivity(),
                R.layout.listview_item, cursor,
                from,
                to, 0);

        lvData.setAdapter(scAdapter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        cursor.close();
        dbHelper.close();

    }
}

The error disappears if I change the cursor to null in
scAdapter = new SimpleCursorAdapter(getActivity(),
                R.layout.listview_item, null,
                from,
                to, 0);

and turn it off
// lvData.setAdapter(scAdapter);
But then it actually does not display anything :)
Added
//получаем данные из бд
        cursor =  database.query(TABLE_NAME, null, null, null, null, null, null);
        cursor.moveToFirst();
        Toast.makeText(getContext(), cursor.getString(cursor.getColumnIndex("f_name")), Toast.LENGTH_LONG).show();

There is data in the field.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Sinitsyn, 2016-03-25
@a_u_sinitsin

Found.
Changed
lvData = (ListView) getActivity.findViewById(R.id.listView);
On
lvData = (ListView) rootView.findViewById(R.id.listView);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question