在我的活动中,我有 4 个片段。其中之一需要连接到数据库并获取其数据。但是,当我运行我的应用程序时发生错误并且 logcat 显示:
07-19 02:09:01.011: E/AndroidRuntime(229): Uncaught handler: thread main exiting due to uncaught exception
07-19 02:09:01.031: E/AndroidRuntime(229): java.lang.ExceptionInInitializerError
07-19 02:09:01.031: E/AndroidRuntime(229): at com.astro.database.DatabaseHandler.<init>(DatabaseHandler.java:26)
07-19 02:09:01.031: E/AndroidRuntime(229): at com.astro.fragments.TopRecipesFragment.onActivityCreated(TopRecipesFragment.java:96)
07-19 02:09:01.031: E/AndroidRuntime(229): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:892)
07-19 02:09:01.031: E/AndroidRuntime(229): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1083)
07-19 02:09:01.031: E/AndroidRuntime(229): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1065)
.
.
.
我的片段代码是这样的:
public class TopRecipesFragment extends Fragment {
private Context context;
private DatabaseHandler dbHandler;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.template_toprecipes, container, false);
context = getActivity().getApplicationContext();
Log.i(TAG, "View created.");
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i(TAG, "inside onActivityCreated()");
dbHandler = new DatabaseHandler(context);
}
.
.
.
}
然后,DatabaseHandler 类:
public class DatabaseHandler {
private DatabaseHelper dbHelper;
private SQLiteDatabase database;
public DatabaseHandler(Context context) {
dbHelper = new DatabaseHelper(context); // Error happens here
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
.
.
.
}
最后是 DatabaseHelper 类:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "db";
private static final String COLUMN_ID = "_id";
private static final int DATABASE_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
.
.
.
}
我不知道为什么会这样。任何建议,将不胜感激。谢谢