无法从android中的片段打开可读数据库

时间:2016-01-19 14:01:05

标签: android android-fragments

我正在尝试像以下项目中那样实现数据库

https://github.com/steventrigg/AlarmClock/tree/master/AlarmClock

我尝试使用片段而不是活动。但每当我将活动转换为片段时,它就无法访问数据库。

我使用以下方法访问数据库

public AlarmModel getAlarm(long id) {
SQLiteDatabase db = this.getReadableDatabase(); //error is shown here
String select = "SELECT * FROM " + Alarm.TABLE_NAME + " WHERE " + Alarm._ID + " = " + id;

    Cursor c = db.rawQuery(select, null);

    if (c.moveToNext()) {
        return populateModel(c);
    }

    return null;
}

我的片段类是

public class AlarmListActivity extends Fragment {

private AlarmListAdapter=new AlarmDBHelper(getActivity());;
private AlarmDBHelper dbHelper;
private Context mContext;
ListView list;

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

    mContext = getContext();
    View view = inflater.inflate(R.layout.activity_alarm_list, container,
            false);
    list=(ListView) view.findViewById(R.id.listview);

    FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            startAlarmDetailsActivity(-1);

        }
    });

    mAdapter = new AlarmListAdapter(getActivity(),dbHelper.getAlarms(),AlarmListActivity.this);
    list.setAdapter(mAdapter);
    ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Alarm List");

    return view;
}



    public void setAlarmEnabled(long id, boolean isEnabled) {
    AlarmManagerHelper.cancelAlarms(getActivity());

    AlarmModel model = dbHelper.getAlarm(id);
    model.isEnabled = isEnabled;
    dbHelper.updateAlarm(model);

    AlarmManagerHelper.setAlarms(getActivity());
}

在logcat中只说它无法获得可读数据库。

2 个答案:

答案 0 :(得分:0)

this.getReadableDatabase中的“this”引用片段 - 但是,它需要一个可以作为活动的上下文。试试getActivity()。getReadableDatabase();否则将以下方法放入片段中:

@Override
        public void onAttach(Activity activity) {
        a=activity;
        super.onAttach(activity);
        }

宣布公共领域

Activity a;

然后在方法中使用a.getReadableDatabase()

答案 1 :(得分:0)

onCreateView()方法中添加以下行。不要把它放在你放的地方。

private AlarmListAdapter=new AlarmDBHelper(getActivity());

因为它需要获取活动的上下文,而这个上下文在您声明为getActivity()的范围内不可用,所以不会在那里返回活动。