应用程序崩溃在启动时,由于java.lang.IllegalArgumentException:如果列'_id'不存在 [英] App Crashes On Startup Due To java.lang.IllegalArgumentException: column '_id' does not exist

查看:1429
本文介绍了应用程序崩溃在启动时,由于java.lang.IllegalArgumentException:如果列'_id'不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的LogCat中列'_id'不存在错误:

每当我开始我的应用程序,我收到了 java.lang.IllegalArgumentException异常。我创建了列'_ ID,但它仍然抛出这个。这是我主要的.java:

 包com.gantt.shoppinglist;

进口android.app.Dialog;
进口android.app.ListActivity;
进口android.database.Cursor;
进口android.os.Bundle;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.widget.Button;
进口android.widget.EditText;
进口android.widget.ListView;
进口android.widget.SimpleCursorAdapter;

公共类ShoppingList扩展ListActivity {

    私人DataHelper DataHelper;
    / **第一次创建活动时调用。 * /
    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.main);
        DataHelper =新DataHelper(本);

        光标C =(光标)DataHelper.selectAll();
        长ID = c.getLong(c.getColumnIndex(_ ID));
        startManagingCursor(C);

        ListView的LV =(ListView控件)findViewById(android.R.id.list);

        的String []从=新的String [] {com.gantt.shoppinglist.DataHelper.getDatabaseName()};
        INT []到=新INT [] {android.R.id.text1};

        SimpleCursorAdapter适配器=新SimpleCursorAdapter(这一点,
                android.R.layout.simple_list_item_1,C,从,到);
        lv.setAdapter(适配器);

        按钮button1main =(按钮)findViewById(R.id.add);
        button1main.setOnClickListener(新OnClickListener(){
            @覆盖
            公共无效的onClick(视图v){
            最后一个对话框的AddItem =新的对话框(ShoppingList.this);
            additem.setContentView(R.layout.maindialog);
            最后的EditText等=(EditText上)additem.findViewById(R.id.edittext);
            additem.setTitle(输入您的项目);
            additem.setCancelable(真正的);
            et.setHint(类型的项目...的名字);

            Button按钮=(按钮)additem.findViewById(R.id.cancel);
            button.setOnClickListener(新OnClickListener(){
                @覆盖
                公共无效的onClick(视图v){
                    additem.dismiss();
                }
            });
            additem.show();

            OK按钮=(按钮)additem.findViewById(R.id.ok);
            ok.setOnClickListener(新OnClickListener(){
                @覆盖
                公共无效的onClick(视图v){
                    最后字符串文本= et.getText()的toString()。
                    additem.dismiss();
                    et.setText();
                }
            });
       }
        });
    }
}
 

下面是我的DataHelper类:

 包com.gantt.shoppinglist;

进口的java.util.ArrayList;
进口的java.util.List;

进口android.content.Context;
进口android.database.Cursor;
进口android.database.sqlite.SQLiteDatabase;
进口android.database.sqlite.SQLiteOpenHelper;
进口android.database.sqlite.SQLiteStatement;
进口android.util.Log;

公共类DataHelper {

       私有静态最后弦乐DATABASE_NAME =items.db;
       私有静态最终诠释DATABASE_VERSION = 1;
       私有静态最后弦乐TABLE_NAME =表1;
       公共静态最后弦乐KEY_ROWID =_id;

       私人上下文的背景下;
       私人SQLiteDatabase分贝;

       私人SQLiteStatement的insertstmt;
       私有静态最后弦乐INSERT =插入
          + TABLE_NAME +(名称)值(?);

       公共DataHelper(上下文的背景下){
          this.context =背景;
          OpenHelper openHelper =新OpenHelper(this.context);
          this.db = openHelper.getWritableDatabase();
          this.insertStmt = this.db.compileStatement(INSERT);
       }

       众长刀片(字符串名称){
          this.insertStmt.bindString(1,名);
          返回this.insertStmt.executeInsert();
       }

       公共无效用deleteAll(){
          this.db.delete(TABLE_NAME,NULL,NULL);
       }

       公共光标全选(){
          名单<字符串>名单=新的ArrayList<字符串>();
          光标光标= this.db.query(TABLE_NAME,新的String [] {姓名},
            NULL,NULL,NULL,NULL,名降序);
          如果(cursor.moveToFirst()){
             做 {
                list.add(cursor.getString(0));
             }而(cursor.moveToNext());
          }
          如果(光标=空&安培;!&安培;!cursor.isClosed()){
             cursor.close();
          }
          返回游标;
       }

       公共静态字符串getDatabaseName(){
        返回DATABASE_NAME;
    }

    私有静态类OpenHelper扩展SQLiteOpenHelper {

          OpenHelper(上下文的背景下){
             超(背景下,getDatabaseName(),空,DATABASE_VERSION);
          }

          @覆盖
          公共无效的onCreate(SQLiteDatabase DB){
              db.execSQL(CREATE TABLE+ TABLE_NAME +(ID INTEGER PRIMARY KEY,名称文本);

          }

          @覆盖
          公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){
             Log.w(榜样,升级数据库,这将删除表并重新创建。);
             db.execSQL(DROP TABLE IF EXISTS+ TABLE_NAME);
             的onCreate(DB);
          }
       }
    }
 

解决方案

我有一个类似的问题 - 我认为这是不得不选择(或选择为)的情况下,一些所谓的 _id ,因为 SimpleCursorAdapter 需要它。

在<一个href="http://developer.android.com/guide/topics/providers/content-provider-creating.html#ContentURI">documentation:

  

内容处理URI标识

     

按照惯例,供应商提供访问单个行表中的由   接受内容的URI与该行的ID值时的结束   URI。同样按照约定,供应商ID值表的匹配    _ID 列,并执行对符合该行的请求的访问。

     

该公约有利于一个常见的​​设计模式的应用程序访问   的提供者。该应用程序做了查询,对供应商并显示   导致光标的ListView 使用的CursorAdapter 。定义   对的CursorAdapter 要求列在一个光标 _ID

在我的情况,我在我的表中的自动编号列被称为OID让我改变了我的SELECT命令是(例如)...

  SELECT OID为_id,名称,编号FROM mytable的
 

这治好了我的问题。

编辑,显示更广泛的code ...

  @覆盖
公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.channel_selector);

    GridView控件channel_selector_grid =(GridView控件)findViewById(R.id.channel_grid);
    SCA = getGuideAdapter();
    channel_selector_grid.setAdapter(SCA);
}

公共SimpleCursorAdapter getGuideAdapter(){
    SimpleCursorAdapter适配器= NULL;
    SQLiteDatabase DB = SQLiteDatabaseHelper.getReadableDatabase();
    光标光标= db.rawQuery(SELECT DISTINCT OID为_id,名称,数量从CHAN_TABLE ORDER BY号,NULL);
    如果(cursor.moveToFirst()){
        的String [] columnNames = {姓名};
        INT []渣油= {R.id.channel_name};
        适配器=新SimpleCursorAdapter(这一点,R.layout.channel_selector_item,光标为columnNames,渣油);
    }
    返回适配器;
}
 

Whenever I start my app, I get a java.lang.IllegalArgumentException: column '_id' does not exist error in my LogCat. I have created the column '_id', but it still throws this. Here is my main .java:

package com.gantt.shoppinglist;

import android.app.Dialog;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class ShoppingList extends ListActivity {

    private DataHelper DataHelper;
    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        DataHelper = new DataHelper(this);

        Cursor c = (Cursor) DataHelper.selectAll();
        long id = c.getLong(c.getColumnIndex("_id"));
        startManagingCursor(c);

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

        String[] from = new String[] { com.gantt.shoppinglist.DataHelper.getDatabaseName() };
        int[] to = new int[] { android.R.id.text1 };

        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_1, c, from, to);       
        lv.setAdapter(adapter);

        Button button1main = (Button) findViewById(R.id.add);
        button1main.setOnClickListener(new OnClickListener()  {
            @Override
            public void onClick(View v)  {
            final Dialog additem = new Dialog(ShoppingList.this);
            additem.setContentView(R.layout.maindialog);
            final EditText et = (EditText)additem.findViewById(R.id.edittext);
            additem.setTitle("Type your item");
            additem.setCancelable(true);
            et.setHint("Type the name of an item...");

            Button button = (Button) additem.findViewById(R.id.cancel);
            button.setOnClickListener(new OnClickListener()  {
                @Override
                public void onClick(View v)  {
                    additem.dismiss();
                }
            });
            additem.show();

            Button ok = (Button) additem.findViewById(R.id.ok);
            ok.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    final String text = et.getText().toString();
                    additem.dismiss();
                    et.setText("");
                }
            });
       }
        });
    }
}

Here is my DataHelper class:

package com.gantt.shoppinglist;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

public class DataHelper {

       private static final String DATABASE_NAME = "items.db";
       private static final int DATABASE_VERSION = 1;
       private static final String TABLE_NAME = "table1";
       public static final String KEY_ROWID = "_id";

       private Context context;
       private SQLiteDatabase db;

       private SQLiteStatement insertStmt;
       private static final String INSERT = "insert into " 
          + TABLE_NAME + "(name) values (?)";

       public DataHelper(Context context) {
          this.context = context;
          OpenHelper openHelper = new OpenHelper(this.context);
          this.db = openHelper.getWritableDatabase();
          this.insertStmt = this.db.compileStatement(INSERT);
       }

       public long insert(String name) {
          this.insertStmt.bindString(1, name);
          return this.insertStmt.executeInsert();
       }

       public void deleteAll() {
          this.db.delete(TABLE_NAME, null, null);
       }

       public Cursor selectAll() {
          List<String> list = new ArrayList<String>();
          Cursor cursor = this.db.query(TABLE_NAME, new String[] { "name" }, 
            null, null, null, null, "name desc");
          if (cursor.moveToFirst()) {
             do {
                list.add(cursor.getString(0)); 
             } while (cursor.moveToNext());
          }
          if (cursor != null && !cursor.isClosed()) {
             cursor.close();
          }
          return cursor;
       }

       public static String getDatabaseName() {
        return DATABASE_NAME;
    }

    private static class OpenHelper extends SQLiteOpenHelper {

          OpenHelper(Context context) {
             super(context, getDatabaseName(), null, DATABASE_VERSION);
          }

          @Override
          public void onCreate(SQLiteDatabase db) {
              db.execSQL("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY, name TEXT");

          }

          @Override
          public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
             Log.w("Example", "Upgrading database, this will drop tables and recreate.");
             db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
             onCreate(db);
          }
       }
    }

解决方案

I had a similar issue - I think it's a case of having to 'select' (or 'select as') something called _id because the SimpleCursorAdapter needs it.

From the documentation:

Handling content URI IDs

By convention, providers offer access to a single row in a table by accepting a content URI with an ID value for the row at the end of the URI. Also by convention, providers match the ID value to the table's _ID column, and perform the requested access against the row that matches.

This convention facilitates a common design pattern for apps accessing a provider. The app does a query against the provider and displays the resulting Cursor in a ListView using a CursorAdapter. The definition of CursorAdapter requires one of the columns in the Cursor to be _ID.

In my case, I have an autonumber column in my table called 'oid' so I altered my SELECT command to be (for example)...

SELECT oid as _id, name, number FROM mytable

This cured the problem for me.

EDIT to show more extensive code...

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.channel_selector);

    GridView channel_selector_grid = (GridView) findViewById(R.id.channel_grid);
    sca = getGuideAdapter();
    channel_selector_grid.setAdapter(sca);
}

public SimpleCursorAdapter getGuideAdapter() {
    SimpleCursorAdapter adapter = null;
    SQLiteDatabase db = SQLiteDatabaseHelper.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT DISTINCT oid as _id, name, number FROM CHAN_TABLE ORDER BY number", null);
    if (cursor.moveToFirst()) {
        String[] columnNames = { "name" };
        int[] resIds = { R.id.channel_name };
        adapter = new SimpleCursorAdapter(this, R.layout.channel_selector_item, cursor, columnNames, resIds);
    }
    return adapter; 
}

这篇关于应用程序崩溃在启动时,由于java.lang.IllegalArgumentException:如果列'_id'不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆