【问题标题】:Android Application SQlite AccessAndroid 应用程序 SQlite 访问
【发布时间】:2014-05-27 13:44:36
【问题描述】:

从活动访问 SQlite DB 工作正常 例如。

    public class MainActivity extends Activity {

     DatabaseHelper db;
     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        db = new DatabaseHelper(getApplicationContext());

        // Creating tags
        Tag tag1 = new Tag("Shopping");
        Tag tag2 = new Tag("Important");
        Tag tag3 = new Tag("Watchlist");
        Tag tag4 = new Tag("Androidhive");

        // Inserting tags in db
        long tag1_id = db.createTag(tag1);
        long tag2_id = db.createTag(tag2);
        long tag3_id = db.createTag(tag3);
        long tag4_id = db.createTag(tag4);

        Log.d("Tag Count", "Tag Count: " + db.getAllTags().size());
        setContentView(R.layout.activity_main);
                if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new        PlaceholderFragment()).commit();
        }
    }

但只要我在 Activity 中获取 DB 代码并在 Application Constructor 中调用它,我就会得到空指针。 例如

public class MainClass extends Application {
// Database Helper
private DatabaseHelper db;
private static final String LOG = MainClass.class.getName();

public MainClass()  {
    Log.d(LOG, "MainClass Init");
    db = new DatabaseHelper(getApplicationContext());

我错过了什么?

【问题讨论】:

  • 你什么时候调用Application构造函数?
  • 应用程序构造函数由清单文件调用。就像我将 mf 文件指定为

标签: android sqlite nullpointerexception


【解决方案1】:

应用程序类不需要显式构造函数。

在调用构造函数的对象实例化阶段,Application 尚未设置为Context。 getApplicationContext() 不起作用。

您只能在onCreate() 或更高版本中将Application 用作Context。

【讨论】:

  • 应用启动时如何创建数据库?
  • 感谢拉尔托。在应用程序 oncreate 中创建数据库有效。谢谢队友
猜你喜欢
  • 1970-01-01
  • 2012-11-02
  • 1970-01-01
  • 2012-07-11
  • 1970-01-01
  • 2017-03-26
  • 1970-01-01
  • 2013-11-30
  • 1970-01-01
相关资源
最近更新 更多