jjzjj

android - 尝试调用 getWritableDatabase() 时继续获取 NullPointerExceptions

coder 2023-07-20 原文

我是 Android 框架的新手,我无法通过 SQLite 的第一垒。

我正在尝试构建一个非常简单的应用程序,它有一个 EditText 搜索框,当按下某个键时,它会在 SQLite 数据库上执行 Like %word% 搜索,以查找在 EditText 框中输入的文本,并显示结果是一个 ListView。

注意下面的代码包括调试和注释代码,抱歉我还没抽空清理它。

激活是

public class sustainable_fish extends Activity {

private String keycodeToAscii(int arg2){

    String retvar = "";

    switch(arg2){
    case KeyEvent.KEYCODE_A: retvar = "a";break;
    case KeyEvent.KEYCODE_B: retvar = "b";break;

剪断了,但你明白了。

    case KeyEvent.KEYCODE_RIGHT_BRACKET: retvar = ")";break;
    default: retvar = ""; break;
    };
    return retvar;

}



 Context that = getApplicationContext();
 fishDB dh = new fishDB(getApplicationContext());


private OnKeyListener search = new OnKeyListener() {

    public boolean onKey(View arg0, int arg1, KeyEvent arg2) {


        @SuppressWarnings("unused")
        Cursor cur = null;
        String searchData;
        EditText myEditText = (EditText) findViewById(R.id.fish_search);
        CharSequence edit_text_value = myEditText.getText();
        searchData = edit_text_value.toString();
        searchData = searchData + keycodeToAscii(arg2.getKeyCode() );
        Log.d("onKey", "searchData = "+searchData);
        /*
        Commented out because as the database doesn't work, so theirs no point just yet searching.

        cur = fish.search(searchData);
        if (cur != null)
        {
            String[] displayFields = new String[] {cur.getString(2),
                    cur.getString(1)};

            int[] displayViews = new int[] { R.id.fish_rank,
                    R.id.fish_name};

            SimpleCursorAdapter adapter = new SimpleCursorAdapter(that, 
                    R.layout.text_list, cur, 
                    displayFields, displayViews);

            ListView myList=(ListView)findViewById(android.R.id.list);

            myList.setAdapter(adapter);
        } 
        */

        return false;
    }

};

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

   setContentView(R.layout.main);
   EditText searchBar = (EditText) findViewById(R.id.fish_search);
   searchBar.setOnKeyListener(search); 

}

}

SQLite 数据库由 fishDB 处理

  public class fishDB {

 public static final String DATABASE_NAME = "fish.db3";
 public static final int DATABASE_VERSION = 1;
 private SQLiteDatabase database;
 private Context myContext;
 private static boolean booFirstrun = false;

 fishDB(Context inContext){
     myContext = inContext;
     OpenHelper helper = new OpenHelper(myContext);
     Log.w("fishDB", "Called OpenHelper");

             // Here be the problem...

     database = helper.getWritableDatabase();

 }

 public boolean firstRun(){
    return booFirstrun;
 }


   private static class OpenHelper extends SQLiteOpenHelper {

       private static final String CREATE_TABLE_FEEDS = "create table feeds (feed_id integer primary key autoincrement, "
           + "title text not null, url text not null);";

          OpenHelper(Context context) {
             super(context, DATABASE_NAME, null, DATABASE_VERSION);
             Log.w("OpenHelper", "Called superconstructor");
            }

          @Override
          public void onCreate(SQLiteDatabase db) {
              try {
              Log.w("OpenHelper", "in onCreate");
              booFirstrun = true;
              Log.w("OpenHelper", "set booFirstrun");
              db.beginTransaction();
              Log.w("OpenHelper", "db.beginTransaction");
              try {
                  // Create tables and test data
                  db.execSQL(CREATE_TABLE_FEEDS);
                  Log.w("OpenHelper", "execSQL");
                  db.setTransactionSuccessful();
                  Log.w("OpenHelper", "setTransactionSuccessful");
              } catch (SQLException e) {
                  Log.e("Error creating tables and debug data", e.toString());
                  throw e;
              } finally {
                  db.endTransaction();
              }
              } catch (Exception e) {
                  Log.e("OpenHelper", e.toString() );
              } finally {
              Log.w("OpenHelper", "out of onCreate");
              }
          }

          @Override
          public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
             Log.w("OpenHelper", "Upgrading database, this will drop tables and recreate.");
             onCreate(db);
          }
       } 
 }

现在每次“database = helper.getWritableDatabase();”称为应用程序崩溃并出现 NullPointerException。我设法将错误追溯到 OpenHelper 的 onCreate 方法和“db.beginTransaction();”行。

我错过了什么?

最佳答案

实际上您不需要在助手的 onCreate 方法中启动事务。尝试从方法中删除除 db.execSQL(CREATE_TABLE_FEEDS);

之外的所有内容

更新:我能够重复这个问题。

在该错误消失后,将 ​​fishDb 字段初始化移至 Activity 的 onCreate() 方法。在调用 onCreate 之前开始数据库初始化似乎不是一个好主意。

所以代替

fishDB fishDb = new fishDB(getApplicationContext());

fishDB fishDb;

onCreate(){
  super.onCreate();
  fishDb = new fishDB(getApplicationContext());
  .... //init listener, query db etc..
}

关于android - 尝试调用 getWritableDatabase() 时继续获取 NullPointerExceptions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3489427/

有关android - 尝试调用 getWritableDatabase() 时继续获取 NullPointerExceptions的更多相关文章

  1. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  2. ruby - 即使失败也继续进行多主机测试 - 2

    我已经构建了一些serverspec代码来在多个主机上运行一组测试。问题是当任何测试失败时,测试会在当前主机停止。即使测试失败,我也希望它继续在所有主机上运行。Rakefile:namespace:specdotask:all=>hosts.map{|h|'spec:'+h.split('.')[0]}hosts.eachdo|host|begindesc"Runserverspecto#{host}"RSpec::Core::RakeTask.new(host)do|t|ENV['TARGET_HOST']=hostt.pattern="spec/cfengine3/*_spec.r

  3. ruby - 简单获取法拉第超时 - 2

    有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url

  4. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  5. ruby-on-rails - 每次我尝试部署时,我都会得到 - (gcloud.preview.app.deploy) 错误响应 : [4] DEADLINE_EXCEEDED - 2

    我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie

  6. ruby - 从 Ruby 中的主机名获取 IP 地址 - 2

    我有一个存储主机名的Ruby数组server_names。如果我打印出来,它看起来像这样:["hostname.abc.com","hostname2.abc.com","hostname3.abc.com"]相当标准。我想要做的是获取这些服务器的IP(可能将它们存储在另一个变量中)。看起来IPSocket类可以做到这一点,但我不确定如何使用IPSocket类遍历它。如果它只是尝试像这样打印出IP:server_names.eachdo|name|IPSocket::getaddress(name)pnameend它提示我没有提供服务器名称。这是语法问题还是我没有正确使用类?输出:ge

  7. ruby - 获取模块中定义的所有常量的值 - 2

    我想获取模块中定义的所有常量的值:moduleLettersA='apple'.freezeB='boy'.freezeendconstants给了我常量的名字:Letters.constants(false)#=>[:A,:B]如何获取它们的值的数组,即["apple","boy"]? 最佳答案 为了做到这一点,请使用mapLetters.constants(false).map&Letters.method(:const_get)这将返回["a","b"]第二种方式:Letters.constants(false).map{|c

  8. ruby-on-rails - 获取 inf-ruby 以使用 ruby​​ 版本管理器 (rvm) - 2

    我安装了ruby​​版本管理器,并将RVM安装的ruby​​实现设置为默认值,这样'哪个ruby'显示'~/.rvm/ruby-1.8.6-p383/bin/ruby'但是当我在emacs中打开inf-ruby缓冲区时,它使用安装在/usr/bin中的ruby​​。有没有办法让emacs像shell一样尊重ruby​​的路径?谢谢! 最佳答案 我创建了一个emacs扩展来将rvm集成到emacs中。如果您有兴趣,可以在这里获取:http://github.com/senny/rvm.el

  9. c# - 如何在 ruby​​ 中调用 C# dll? - 2

    如何在ruby​​中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL

  10. Ruby 从大范围中获取第 n 个项目 - 2

    假设我有这个范围:("aaaaa".."zzzzz")如何在不事先/每次生成整个项目的情况下从范围中获取第N个项目? 最佳答案 一种快速简便的方法:("aaaaa".."zzzzz").first(42).last#==>"aaabp"如果出于某种原因你不得不一遍又一遍地这样做,或者如果你需要避免为前N个元素构建中间数组,你可以这样写:moduleEnumerabledefskip(n)returnto_enum:skip,nunlessblock_given?each_with_indexdo|item,index|yieldit

随机推荐