1

我编写了一个程序,可以通过光标显示存储在列表视图中的数据库中的数据。但在运行时它给了我强制关闭。这是我的 logcat 和代码,当我在设备中运行应用程序时,它给我强制关闭,当我更改名称时db,问题解决!!我说之前的BB.sqlite是在另一个页面中创建的。它与这个页面有冲突吗?

这是我的日志:

12-28 04:45:02.950: E/jdwp(22457): Failed sending reply to debugger: Broken pipe
12-28 04:46:04.390: E/AndroidRuntime(22457): FATAL EXCEPTION: AsyncTask #1
12-28 04:46:04.390: E/AndroidRuntime(22457): java.lang.RuntimeException: An error occured while executing doInBackground()
12-28 04:46:04.390: E/AndroidRuntime(22457):    at android.os.AsyncTask$3.done(AsyncTask.java:200)
12-28 04:46:04.390: E/AndroidRuntime(22457):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
12-28 04:46:04.390: E/AndroidRuntime(22457):    at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
12-28 04:46:04.390: E/AndroidRuntime(22457):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
12-28 04:46:04.390: E/AndroidRuntime(22457):    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
12-28 04:46:04.390: E/AndroidRuntime(22457):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
12-28 04:46:04.390: E/AndroidRuntime(22457):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
12-28 04:46:04.390: E/AndroidRuntime(22457):    at java.lang.Thread.run(Thread.java:1019)
12-28 04:46:04.390: E/AndroidRuntime(22457): Caused by: android.database.sqlite.SQLiteException: no such column: _id: , while compiling: SELECT _id, Good_Name, Good_UnitPrice FROM Tbl_Goods ORDER BY _id ASC
12-28 04:46:04.390: E/AndroidRuntime(22457):    at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
12-28 04:46:04.390: E/AndroidRuntime(22457):    at android.database.sqlite.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:92)
12-28 04:46:04.390: E/AndroidRuntime(22457):    at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:65)
12-28 04:46:04.390: E/AndroidRuntime(22457):    at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:83)
12-28 04:46:04.390: E/AndroidRuntime(22457):    at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:49)
12-28 04:46:04.390: E/AndroidRuntime(22457):    at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:42)
12-28 04:46:04.390: E/AndroidRuntime(22457):    at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1364)
12-28 04:46:04.390: E/AndroidRuntime(22457):    at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:330)
12-28 04:46:04.390: E/AndroidRuntime(22457):    at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:280)
12-28 04:46:04.390: E/AndroidRuntime(22457):    at com.example.nfc.SqlHelper.getCursor(SqlHelper.java:97)
12-28 04:46:04.390: E/AndroidRuntime(22457):    at com.example.nfc.current_cart$SelectDataTask.doInBackground(current_cart.java:90)
12-28 04:46:04.390: E/AndroidRuntime(22457):    at com.example.nfc.current_cart$SelectDataTask.doInBackground(current_cart.java:1)
12-28 04:46:04.390: E/AndroidRuntime(22457):    at android.os.AsyncTask$2.call(AsyncTask.java:185)
12-28 04:46:04.390: E/AndroidRuntime(22457):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
12-28 04:46:04.390: E/AndroidRuntime(22457):    ... 4 more

当前购物车代码:

public class current_cart extends ListActivity {

    private ListView mainListView = null;
    CustomSqlCursorAdapter adapter = null;
    private SqlHelper dbHelper = null;
    private Cursor currentCursor = null;

    private ListView listView = null;

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

        if (this.dbHelper == null) {
            this.dbHelper = new SqlHelper(this);

        }

        listView = getListView();
        listView.setItemsCanFocus(false);
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        //listView.setClickable(true);

        Button btnClear = (Button) findViewById(R.id.btnClear);
        btnClear.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                Toast.makeText(getApplicationContext(),
                        " You clicked Clear button", Toast.LENGTH_SHORT).show();
               // ClearDBSelections();
            }
        });

        new SelectDataTask().execute();

        this.mainListView = getListView();

        mainListView.setCacheColorHint(0);

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        new SelectDataTask().execute();
    }

    @Override
    protected void onPause() {

        super.onPause();
        this.dbHelper.close();
    }

    //protected void ClearDBSelections() {

       // this.adapter.ClearSelections();

  //  }

    private class SelectDataTask extends AsyncTask<Void, Void, String> {

        protected String doInBackground(Void... params) {

            try {

                current_cart.this.dbHelper.createDatabase(dbHelper.dbSqlite);
                current_cart.this.dbHelper.openDataBase();

                current_cart.this.currentCursor = current_cart.this.dbHelper
                        .getCursor();

            } catch (SQLException sqle) {

                throw sqle;

            }
            return null;
        }

        // can use UI thread here
        protected void onPostExecute(final String result) {

            startManagingCursor(current_cart.this.currentCursor);
            int[] listFields = new int[] { R.id.txtTitle };
            String[] dbColumns = new String[] { SqlHelper.COLUMN_TITLE };

            current_cart.this.adapter = new CustomSqlCursorAdapter(
                    current_cart.this, R.layout.single_item,
                    current_cart.this.currentCursor, dbColumns, listFields,
                    current_cart.this.dbHelper);
            setListAdapter(current_cart.this.adapter);

        }
    }

}

CustomSqlCursorAdapter 代码:

public class CustomSqlCursorAdapter extends SimpleCursorAdapter {
    private Context mContext;

    private SqlHelper mDbHelper;
    private Cursor mCurrentCursor;

    public CustomSqlCursorAdapter(Context context, int layout, Cursor c,
            String[] from, int[] to, SqlHelper dbHelper) {
        super(context, layout, c, from, to);
        this.mCurrentCursor = c;
        this.mContext = context;
        this.mDbHelper = dbHelper;

    }

    public View getView(int pos, View inView, ViewGroup parent) {
        View v = inView;
        if (v == null) {
            LayoutInflater inflater = (LayoutInflater) mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = inflater.inflate(R.layout.single_item, null);
        }

        if (!this.mCurrentCursor.moveToPosition(pos)) {
            throw new SQLException("CustomSqlCursorAdapter.getView: Unable to move to position: "+pos);
        }

        CheckBox cBox = (CheckBox) v.findViewById(R.id.bcheck);


        cBox.setTag(Integer.valueOf(this.mCurrentCursor.getInt(0)));

        cBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {


            }
        });

        TextView txtTitle = (TextView) v.findViewById(R.id.txtTitle);
        txtTitle.setText(this.mCurrentCursor.getString(this.mCurrentCursor
                .getColumnIndex(SqlHelper.COLUMN_TITLE)));

        return (v);
    }

}

SqlHelper 代码:

public class SqlHelper extends SQLiteOpenHelper {
    private static final String DATABASE_PATH = "/data/data/com.example.nfc/databases/";

    public static final String DATABASE_NAME = "BB.sqlite";

    public static final String TABLE_NAME = "Tbl_Goods";
    public static final int ToDoItems_VERSION = 1;

    public static final String COLUMN_ID = "_id";               // 0
    public static final String COLUMN_TITLE = "Good_Name";          // 1
    public static final String COLUMN_NAME_DESC = "Good_UnitPrice";// 2
  //  public static final String COLUMN_SELECTED = "selected";    // 3
   // public static final int    COLUMN_SELECTED_idx = 3;

    public SQLiteDatabase dbSqlite;
    private Context mContext;

    public SqlHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
        mContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        createDB(db);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w("SqlHelper", "Upgrading database from version " + oldVersion
                + " to " + newVersion + ", which will destroy all old data");

        db.execSQL("DROP TABLE IF EXISTS Tbl_Goods;");

        createDB(db);
    }

    public void createDatabase(SQLiteDatabase db) {
        createDB(db);
    }

    private void createDB(SQLiteDatabase db) {
   //     if (db == null) {
            db = mContext.openOrCreateDatabase(DATABASE_NAME, 0, null);
     //   }

        db.execSQL("CREATE TABLE IF NOT EXISTS Tbl_Goods (_id INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL  DEFAULT 1,Good_ID INTEGER  NOT NULL ,Cart_ID INTEGER, Good_Name VARCHAR(50),Good_UnitPrice INTEGER (10),Quantity INTEGER);");
        db.setVersion(ToDoItems_VERSION);

        //
        // Generate a few rows for an example
        //
        // find out how many rows already exist, and make sure there's some minimum
      //  SQLiteStatement s = db.compileStatement("select count(*) from ToDoItems;");

      //  long count = s.simpleQueryForLong();
      //  for (int i = 0; i < 20-count; i++) {
        //    db.execSQL("INSERT INTO ToDoItems VALUES(NULL,'Task #"+i+"','Description #"+i+"');");
      //  }
    }

    public void openDataBase() throws SQLException {
        String myPath = DATABASE_PATH + DATABASE_NAME;

        dbSqlite = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);
    }

    @Override
    public synchronized void close() {
        if (dbSqlite != null)
            dbSqlite.close();

        super.close();
    }

    public Cursor getCursor() {
        SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

        queryBuilder.setTables(TABLE_NAME);

        String[] asColumnsToReturn = new String[] { COLUMN_ID,COLUMN_TITLE,
                COLUMN_NAME_DESC };

        Cursor mCursor = queryBuilder.query(dbSqlite, asColumnsToReturn, null,
                null, null, null, COLUMN_ID+" ASC");

        return mCursor;
    }

   // public void clearSelections() {
       // ContentValues values = new ContentValues();
       // values.put(COLUMN_SELECTED, 0);
       // this.dbSqlite.update(SqlHelper.TABLE_NAME, values, null, null);
  //  }
}

另一个我的页面使用此代码来使用数据库:

 private static String DB_NAME = "BB.sqlite";

 public static final String COLUMN_ID = "_id";
        public static final String CartID = "Cart_ID";
        public static final String GoodID = "Good_ID";
        public static final String GoodName = "Good_Name";

 public static final String DATABASE_TABLE = "Tbl_Goods";


  public static final String DATABASE_CREATE =


        //_id INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  DEFAULT 1,
        "CREATE  TABLE Tbl_Goods (_id INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  DEFAULT 1,Good_ID INTEGER  NOT NULL ,Cart_ID INTEGER, Good_Name VARCHAR(50),Good_UnitPrice INTEGER (10),Quantity INTEGER);";
        public static final String DATABASE_CREATE2 = "CREATE  TABLE Tbl_Cart (Cart_ID INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  DEFAULT 1,"+" Cart_Date DATETIME ,"+" Cart_Start_Time DATETIME ,"+" Cart_End_Time DATETIME,"+" Cart_Total INTEGER (10),"+" Cart_Status INTEGER);";
        private static final String Good_Name = null;
        private static final String Quantity = null;
        private static final String Good_UnitPrice = null;
        private java.util.Date _Date;
     //   private DatabaseHelper DBHelper;
        private SQLiteDatabase db;
       // private SQLiteDatabase db;
        // the extension may be .sqlite
        // or .db
      //  public SQLiteDatabase myDataBase;

        public DBAdapter(Context context) {
            super(context, DB_NAME, null, 1);

            this.mycontext = context;

        }

        public void createDataBase() throws IOException{

             boolean dbExist = checkDataBase();

             if(dbExist){
             //do nothing - database already exist
             }else{

             //By calling this method and empty database will be created into the default system path
             //of your application so we are gonna be able to overwrite that database with our database.
             this.getReadableDatabase();

             try {

             copyDataBase();

             } catch (IOException e) {

             throw new Error("Error copying database");

             }
             }

            }

        private boolean checkDataBase()
        {

             SQLiteDatabase checkDB = null;

             try{
             String myPath = DB_PATH + DB_NAME;
             checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

             }catch(SQLiteException e){

             //database does't exist yet.

             }

             if(checkDB != null){

             checkDB.close();

             }

             return checkDB != null ? true : false;
            }



      private void copyDataBase() throws IOException
      {

          //Open your local db as the input stream
          InputStream myInput = mycontext.getAssets().open(DB_NAME);

          // Path to the just created empty db
          String outFileName = DB_PATH + DB_NAME;

          //Open the empty db as the output stream
          OutputStream myOutput = new FileOutputStream(outFileName);

          //transfer bytes from the inputfile to the outputfile
          byte[] buffer = new byte[1024];
          int length;
          while ((length = myInput.read(buffer))>0){
          myOutput.write(buffer, 0, length);
          }

          //Close the streams
          myOutput.flush();
          myOutput.close();
          myInput.close();
        }

      public DBAdapter open() throws SQLException 
        {

            String myPath = DB_PATH + DB_NAME;
           db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
           return this;
        }
      public DBAdapter open1() throws SQLException 
        {

            String myPath = DB_PATH + DB_NAME;
           db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
           return this;
        }


      @Override
      public synchronized void close() {

      if(db != null)
      db.close();

      super.close();
      }

      @Override
      public void onCreate(SQLiteDatabase db) 
      {
      // db.execSQL(DATABASE_CREATE);
      }

      @Override
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

      }
      public void Cancel() 
        {
            ContentValues args = new ContentValues();
            args.put(CartStatus, 2);          
            db.update(DATABASE_TABLE2, args, CartID + "=" + lastId, null);

        }
}
4

0 回答 0