简体   繁体   中英

android SQLITE database app crashes oncreate when it runs the getAllComments() method

i am trying to make an app which you can enter two comments into the database at once, it keeps crashing oncreate when it tries to add all the comments to the list. any help would be most appreciated. thank you in advance.

onCreate

 @Override

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.comments);
    etComm = (EditText) findViewById(R.id.etComment);
    etname = (EditText) findViewById(R.id.etName);
    //Create a new data manager objects
    datasource = new CommentsManageData(this);
    datasource.open(); //Create or open the database
    List<Comment> values = datasource.getAllComments();
    // use the SimpleCursorAdapter to show elements in a ListView
    ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
        android.R.layout.simple_list_item_1,values);
    setListAdapter(adapter);
  }

 //This retrieves data from the database and puts it into an ArrayList
  public List<Comment> getAllComments() {
        List<Comment> comments = new ArrayList<Comment>();
        //Retrieve all comments - returns a cursor positioned 
        //over first item in the results     
        Cursor cursor = database.query(CommentsSQLiteHelper.TABLE_COMMENTS,
          allColumns, null, null, null, null, null);
        cursor.moveToFirst(); //Just in case it wasn't there already
        while (!cursor.isAfterLast()) {
            Comment comment = cursorToComment(cursor);
            comments.add(comment);//Add the comment

            cursor.moveToNext(); // move to the next item in results
        }
        cursor.close(); // make sure to close the cursor
        return comments;
      }

SQLiteOpenHelper:

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/*
 * This class is responsible for creating the database. 
 * It also defines several constants for the table name and the table columns
 * This could be a private class within CommentsDataSource
 */
public class CommentsSQLiteHelper extends SQLiteOpenHelper {//Note subclass

      public static final String TABLE_COMMENTS = "comments";
      public static final String COLUMN_ID = "_id";
      public static final String COLUMN_COMMENT = "comment";
      public static final String COLUMN_NAME = "name";
      private static final String DATABASE_NAME = "commments.db";
      private static final int DATABASE_VERSION = 1;

      // Database creation sql statement
      private static final String DATABASE_CREATE = "create table "
          + TABLE_COMMENTS + "(" + 
          COLUMN_ID + " integer primary key autoincrement, " +
          COLUMN_COMMENT + " integer not null, "+
          COLUMN_NAME + "integer not null)";

      public CommentsSQLiteHelper (Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
      }
      //Must override this method
      public void onCreate(SQLiteDatabase database) {
        database.execSQL(DATABASE_CREATE);
      }

      //The onUpgrade() method will simply delete all existing data and re-create the table.
    //Must override this method
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(CommentsSQLiteHelper.class.getName(),
            "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_COMMENTS);
        onCreate(db);
      }

    } 


   comment object code 

public class Comment {
      private long id;
      private String comment;
      private String name;


      public long getId() {
        return id;
      }

      public void setId(long id) {
        this.id = id;
      }

      public String getComment() {
        return comment;
      }

      public void setComment(String comment) {
        this.comment = comment;
      }

      public String getname() {
            return name;
          }

     public void setname(String name) {
            this.name = name;
          }
}

Logcat:

04-28 04:10:35.998: E/SQLiteLog(1332): (1) no such column: name
04-28 04:10:36.068: E/AndroidRuntime(1332): FATAL EXCEPTION: main
04-28 04:10:36.068: E/AndroidRuntime(1332): Process: cct.mad.lab, PID: 1332
04-28 04:10:36.068: E/AndroidRuntime(1332): java.lang.RuntimeException: Unable to start activity ComponentInfo{cct.mad.lab/cct.mad.lab.CommentsApp}: android.database.sqlite.SQLiteException: no such column: name (code 1): , while compiling: SELECT _id, comment, name FROM comments
04-28 04:10:36.068: E/AndroidRuntime(1332):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at android.os.Handler.dispatchMessage(Handler.java:102)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at android.os.Looper.loop(Looper.java:136)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at android.app.ActivityThread.main(ActivityThread.java:5017)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at java.lang.reflect.Method.invokeNative(Native Method)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at java.lang.reflect.Method.invoke(Method.java:515)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at dalvik.system.NativeStart.main(Native Method)
04-28 04:10:36.068: E/AndroidRuntime(1332): Caused by: android.database.sqlite.SQLiteException: no such column: name (code 1): , while compiling: SELECT _id, comment, name FROM comments
04-28 04:10:36.068: E/AndroidRuntime(1332):     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1200)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at cct.mad.lab.CommentsManageData.getAllComments(CommentsManageData.java:33)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at cct.mad.lab.CommentsApp.onCreate(CommentsApp.java:22)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at android.app.Activity.performCreate(Activity.java:5231)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-28 04:10:36.068: E/AndroidRuntime(1332):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)

The logcat you posted, says no such column "name" which means that your database table "TABLE_COMMENTS" which has column with title "name" is not created successfully. And from your CommentsSQLiteHelper class, you are creating your table like this:

// Database creation sql statement
  private static final String DATABASE_CREATE = "create table "
      + TABLE_COMMENTS + "(" + 
      COLUMN_ID + " integer primary key autoincrement, " +
      COLUMN_COMMENT + " integer not null, "+
      COLUMN_NAME + "integer not null)";

Here, if you'll observe there is no space between COLUMN_NAME & start of "integer not null" so it is clearly taking it as single string column name with no data type.

See here -> COLUMN_NAME + "integer not null)"; (No space before start of datatype integer)

Hence, workaround is to put space before start of " integer not null". Copy paste below code:

 // Database creation sql statement
  private static final String DATABASE_CREATE = "create table "
      + TABLE_COMMENTS + "(" + 
      COLUMN_ID + " integer primary key autoincrement, " +
      COLUMN_COMMENT + " integer not null, "+
      COLUMN_NAME + " integer not null)";

UPDATE: As you are using string(text) in your "comment" & "name" field change datatype of COLUMN_COMMENT & COLUMN_NAME from integer to text(string).

Use below code:

private static final String DATABASE_CREATE = "create table "
      + TABLE_COMMENTS + "(" + 
      COLUMN_ID + " integer primary key autoincrement, " +
      COLUMN_COMMENT + " text not null, "+
      COLUMN_NAME + " text not null)";

Your error is: "no such column: name (code 1): , while compiling: SELECT _id, comment, name FROM comments".

The column name does not exists in your DB.

Furthermore, you coded this:

  // Database creation sql statement
  private static final String DATABASE_CREATE = "create table "
      + TABLE_COMMENTS + "(" + 
      COLUMN_ID + " integer primary key autoincrement, " +
      COLUMN_COMMENT + " integer not null, "+
      COLUMN_NAME + "integer not null)";

As you want to store comments, why to use integer ? it should be text like this:

  // Database creation sql statement
  private static final String DATABASE_CREATE = "create table "
      + TABLE_COMMENTS + " (" + 
      COLUMN_ID + " integer primary key autoincrement, " +
      COLUMN_COMMENT + " text, "+
      COLUMN_NAME + " text)";

每当您对数据库结构进行更改时,请确保增加数据库版本以调用onUpgrade ,在该位置应删除旧数据库结构并回调onCreate以使用更改来重建数据库。

This seems simple enough.

You have an error stating that the column doesn't exist in your database.

This is commonly caused by you changing the database, after it was already created in your android environment.

You can remove this by uninstalling the app. and reinstalling it, which would effectively create a new database and should move you on to a working version.

Let me know if this didn't help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM