草庐IT

java - 无法从 CursorWindow 读取第 0 行,第 -1 列?

coder 2023-11-30 原文

我在使用数据库时遇到问题。当我运行 SQLView.java 时,出现致命异常:

java.lang.RuntimeException: Unable to start activity      ComponentInfo{com.jacob.eindproject/com.jacob.eindproject.SQLView}:     java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure     the Cursor is initialized correctly before accessing data from it.

希望有人能帮助我。我将发布所有与数据库相关的代码。当您需要更多信息时请告诉我,不要犹豫,询问更多信息!

我认为我的专栏有问题,无法找出原因。

此外,我已经阅读了该网站上的所有相关问题,但我找不到应该在哪里声明我的专栏以及要添加/更改的内容。有人知道怎么做吗? :)

开始:我的数据库类:

    package com.jacob.eindproject;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

import java.sql.*;

public class Database {

    public static final String KEY_ROWID = "_id";
    public static final String KEY_NAME = "persons_name";
    public static final String KEY_HOTNESS = "persons_hotness";

    private static final String DATABASE_NAME = "Databasedb";
    private static final String DATABASE_TABLE = "peopleTable";
    private static final int DATABASE_VERSION = 1;

    private DbHelper ourHelper;
    private final Context ourContext;
    private SQLiteDatabase ourDatabase;

    private static class DbHelper extends SQLiteOpenHelper{

        public DbHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            // TODO Auto-generated constructor stub
        }

        @Override //I create it here, right?
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
                    KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    KEY_NAME + " TEXT NOT NULL, " +
                    KEY_HOTNESS + " TEXT NOT NULL);"                    
        );


        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
            onCreate(db);
        }

        public void close(Database database) {
            // TODO Auto-generated method stub

        }
    }



    public Database(Context c){
        ourContext = c;
    }

    public Database open() throws SQLException{
        ourHelper = new DbHelper(ourContext);
        ourDatabase = ourHelper.getWritableDatabase();
        return this;        
    }

    public void close() {

    ourHelper.close(); 
}



    public long createEntry(String name, String hotness) {
        ContentValues cv = new ContentValues();
        cv.put(KEY_NAME, name);
        cv.put(KEY_HOTNESS, hotness);
        return ourDatabase.insert(DATABASE_TABLE, null, cv);

    }

    public String getData() {
        // TODO Auto-generated method stub
        String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS};
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
        String result = "";

        int iRow = c.getColumnIndex(KEY_ROWID);
        int iName = c.getColumnIndex(DATABASE_NAME);
        int iHotness = c.getColumnIndex(KEY_HOTNESS);

        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
            result = result + c.getString(iRow) + " " + c.getString(iName) + " " + c.getString(iHotness) + "\n";


        }

        return result;
    }
}

SQLite 类,用于修复输入:

package com.jacob.eindproject;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View.OnClickListener;


public class SQLite extends Activity implements View.OnClickListener {

    Button sqlUpdate, sqlView;
    EditText sqlName, sqlHotness;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sqllite);
        sqlUpdate = (Button) findViewById(R.id.bSQLUpdate);
        sqlName = (EditText) findViewById(R.id.etSQLName);
        sqlHotness = (EditText) findViewById(R.id.etSQLHotness);

        sqlView = (Button) findViewById(R.id.bSQLopenView);
        sqlView.setOnClickListener((android.view.View.OnClickListener) this);
        sqlUpdate.setOnClickListener((android.view.View.OnClickListener) this);
    }

    public void onClick(View arg0) {
        switch (arg0.getId()) {
        case R.id.bSQLUpdate:


            boolean didItWork = true;
            try{            
            String name = sqlName.getText().toString();
            String hotness = sqlHotness.getText().toString();

            Database entry = new Database(SQLite.this);
            entry.open();
            entry.createEntry(name, hotness);
            entry.close();

            }catch (Exception e ){
                didItWork = false;

            }finally{
                if (didItWork){
                    Dialog d = new Dialog(this);
                    d.setTitle("Heak Yeay");
                    TextView tv = new TextView(this);
                    tv.setText("Succes");
                    d.setContentView(tv);
                    d.show();
            }
        }

            break;
        case R.id.bSQLopenView:
            Intent i = new Intent("com.jacob.eindproject.SQLVIEW");
            startActivity(i);


        }
        }

    public void onClick(DialogInterface arg0, int arg1) {
        // TODO Auto-generated method stub

    }

    }

之后,我的 SQLView 类,用于查看来自 SQLite 类的输入:

package com.jacob.eindproject;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class SQLView extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sqlview);
        TextView tv = (TextView) findViewById(R.id.tvSQLinfo);
        Database info = new Database(this);
        info.open();
        String data = info.getData();
        info.close();
        tv.setText(data);





    }

}

现在,我的 xml 文件:

SQLView.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="wrap_content">


    <TableLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/tableLayout1">

        <TableRow>

                <TextView android:text="@string/Names" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1"/>

                <TextView android:text="@string/Hotness" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" />

        </TableRow>


    </TableLayout>

        <TextView android:id="@+id/tvSQLinfo" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="@string/info"/>

</LinearLayout>

sqllite.xml:

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">


    <TextView
        android:id="@+id/Naam" 
        android:text="@string/Naam"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall" />

    <EditText
        android:id="@+id/etSQLName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </EditText>

    <TextView
        android:id="@+id/hotness" 
        android:text="@string/hotnessscale"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
    /> 

    <EditText
        android:id="@+id/etSQLHotness"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </EditText>    

    <Button
        android:id="@+id/bSQLUpdate"
        android:text="@string/Update"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" ></Button>



    <Button
        android:id="@+id/bSQLopenView"
        android:text="@string/View"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"    
    ></Button>    

</LinearLayout>

Menu 类,用于修复菜单,带有 OnListItemClick(那里还有一些其他 Activity ,例如 Overgewicht。不要介意这些,我猜..?):

package com.jacob.eindproject;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class Menu extends ListActivity implements OnItemClickListener { 


    String classes[] = { "BMI- Calculator", "Ondergewicht", "Gezond Gewicht", "Overgewicht", "Database", "Bekijk Database"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setListAdapter(new ArrayAdapter<String>(Menu.this, android.R.layout.simple_list_item_1, classes));
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    //Positie 0 is het eerste item (dus de BMI-Calculator.)
    super.onListItemClick(l, v, position, id);

    switch(position)
    {
    case 0: 
    Intent openStartingPoint = new Intent(getApplicationContext(),MainActivity.class);
    startActivity(openStartingPoint);   
    break;

    case 1: 
    Intent openOndergewicht = new Intent(getApplicationContext(),Ondergewicht.class);
    startActivity(openOndergewicht);
    break;

    case 2: 
    Intent openGezondgewicht = new Intent(getApplicationContext(),Gezond_gewicht.class);
    startActivity(openGezondgewicht);   
    break;

    case 3: 
    Intent openOvergewicht = new Intent(getApplicationContext(),Overgewicht.class);
    startActivity(openOvergewicht); 

    break;


    case 4: 
    Intent openDatabase = new Intent(getApplicationContext(),SQLite.class);
    startActivity(openDatabase);    

    break;

    case 5: 
    Intent openViewdatabase = new Intent(getApplicationContext(),SQLView.class);
    startActivity(openViewdatabase);    

    break;

    }


    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { 
        // TODO Auto-generated method stub

    }
}

我的 Android Manifest 文件:(再次声明,我已经声明了一些其他内容,请不要介意这些!)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jacob.eindproject"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >


        <activity
            android:name="com.jacob.eindproject.Menu"
            android:label="@string/app_name" >
        </activity>

        <activity
            android:name="com.jacob.eindproject.Inleiding"
            android:label="@string/app_name" >
                    <intent-filter>
                            <action android:name="android.intent.action.MAIN" />
                            <category android:name="android.intent.category.LAUNCHER" />
                    </intent-filter>
        </activity>

        <activity
            android:name="com.jacob.eindproject.MainActivity"
            android:label="@string/app_name" >
                     <intent-filter>
                            <action android:name="android.intent.action.MAIN" />
                            <category android:name="android.intent.category.DEFAULT" />
                    </intent-filter>
        </activity>        

        <activity
            android:name="com.jacob.eindproject.Ondergewicht"
            android:label="@string/app_name" >
        </activity>        

        <activity
            android:name="com.jacob.eindproject.Gezond_gewicht"
            android:label="@string/app_name" >
        </activity>   

        <activity
            android:name="com.jacob.eindproject.Overgewicht"
            android:label="@string/app_name" >
        </activity>

        <activity
            android:name="com.jacob.eindproject.Database"
            android:label="@string/app_name" >
                    <intent-filter>
                            <action android:name="com.jacob.eindproject.DATABASE" />
                            <category android:name="android.intent.category.DEFAULT" />
                    </intent-filter>
        </activity>                 

        <activity
            android:name=".SQLView"
            android:label="@string/app_name" >
                    <intent-filter>
                            <action android:name="com.jacob.eindproject.SQLVIEW" />
                            <category android:name="android.intent.category.DEFAULT" />
                    </intent-filter>                     

        </activity>           


        <activity
            android:name="com.jacob.eindproject.SQLite"
            android:label="@string/app_name" >
                    <intent-filter>
                            <action android:name="com.jacob.eindproject.SQLITE" />
                            <category android:name="android.intent.category.DEFAULT" />
                    </intent-filter>
        </activity>  



    </application>

</manifest>

最后,我的 LogCat,向您展示错误:

12-14 11:04:18.227: E/AndroidRuntime(1577): FATAL EXCEPTION: main
12-14 11:04:18.227: E/AndroidRuntime(1577): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jacob.eindproject/com.jacob.eindproject.SQLView}: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.os.Looper.loop(Looper.java:137)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.app.ActivityThread.main(ActivityThread.java:5103)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at java.lang.reflect.Method.invokeNative(Native Method)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at java.lang.reflect.Method.invoke(Method.java:525)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at dalvik.system.NativeStart.main(Native Method)
12-14 11:04:18.227: E/AndroidRuntime(1577): Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.database.CursorWindow.nativeGetString(Native Method)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.database.CursorWindow.getString(CursorWindow.java:434)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at com.jacob.eindproject.Database.getData(Database.java:95)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at com.jacob.eindproject.SQLView.onCreate(SQLView.java:16)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.app.Activity.performCreate(Activity.java:5133)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
12-14 11:04:18.227: E/AndroidRuntime(1577):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
12-14 11:04:18.227: E/AndroidRuntime(1577):     ... 11 more

希望有人花时间帮助我。我已经非常感谢那些查看它的人。提前谢谢大家。

雅各布

最佳答案

String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";

int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(DATABASE_NAME);

您的光标 没有名为DATABASE_NAME。对于此 getColumnIndex() 调用,您的意思可能是 KEY_NAME,在这种形式中返回 -1 并尝试获取具有此类索引的数据将导致您看到的异常。

关于java - 无法从 CursorWindow 读取第 0 行,第 -1 列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20593852/

有关java - 无法从 CursorWindow 读取第 0 行,第 -1 列?的更多相关文章

  1. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  2. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  3. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  4. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  5. ruby-on-rails - 无法在centos上安装therubyracer(V8和GCC出错) - 2

    我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e

  6. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

  7. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  8. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  9. ruby - 无法覆盖 irb 中的 to_s - 2

    我在pry中定义了一个函数:to_s,但我无法调用它。这个方法去哪里了,怎么调用?pry(main)>defto_spry(main)*'hello'pry(main)*endpry(main)>to_s=>"main"我的ruby版本是2.1.2看了一些答案和搜索后,我认为我得到了正确的答案:这个方法用在什么地方?在irb或pry中定义方法时,会转到Object.instance_methods[1]pry(main)>defto_s[1]pry(main)*'hello'[1]pry(main)*end=>:to_s[2]pry(main)>defhello[2]pry(main)

  10. ruby - 无法在 60 秒内获得稳定的 Firefox 连接 (127.0.0.1 :7055) - 2

    我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类

随机推荐