我在MainActivity里放置了一个ViewPager,对应四个不同的Fragment.
创建了数据库DBHelper继承SQLiteOpenHelper。
现在我在一个fragment界面取出数据库内容时出现了错误,这是怎么回事呢?
// fragme代码, 构造方法和onCreateView()方法没动,只写了onActivityCreated()方法
public class CommunityFragment extends Fragment {
DBHelper dbHelper = new DBHelper(getContext());
public CommunityFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_community, container, false);
// Inflate the layout for this fragment
return view;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// 取出用户账号
SharedPreferences sp = getActivity().getSharedPreferences("LoginSp", Context.MODE_PRIVATE);
String account = sp.getString("account",null);
SQLiteDatabase dbread = dbHelper.getReadableDatabase();
String sql = "select * from "+DBHelper.table_AccountTags+" where account='"+account+"'";
Cursor cursor = dbread.rawQuery(sql,null);
int flag = cursor.getCount();
if(flag == 0) {// 没有标签的用户
}
else {// 有标签的用户
}
cursor.close();
dbread.close();
}
}
DBhelper创建了数据表
String sql = "CREATE TABLE IF NOT EXISTS "+DBHelper.table_AccountTags+"(_id INTEGER PRIMARY KEY AUTOINCREMENT,account VARCHAR(20),tag1 VARCHAR(20),tag2 VARCHAR(20),tag3 VARCHAR(20))";
db.execSQL(sql);
运行后app强制关闭,提示一下错误:
(CommunityFragment.java:68)这句是:SQLiteDatabase dbread = dbHelper.getReadableDatabase();