1

我正在尝试为 android 上的 SQlite 数据库创建一个表。该表有 5 列,Int id、URL 链接、字符串标题、字符串描述和日期日期。

为了构建我的代码,我一直在使用thisthis作为参考,但都没有展示如何向光标添加除字符串之外的任何内容。

这是我的代码:

public class Chapter {

final SimpleDateFormat FORMATTER = 
        new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
    private String title;
    private URL link;
    private String description;
    private Date date;
    private int id;

    //Constructor for table includes ID.
    public Chapter(int id, URL link, String title, String description, Date date) {
        this.id = id;
        this.link = link;
        this.title = title;
        this.description = description;
        this.date = date;
    }

    //Empty Constructor
    public Chapter() {
        // TODO Auto-generated constructor stub
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title.trim();
    }
    // getters and setters omitted for brevity 
    public URL getLink() {
        return link;
    }

    public void setLink(String link) {
        try {
            this.link = new URL(link);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description.trim();
    }

    public String getDate() {
        return FORMATTER.format(this.date);
    }

    public void setDate(String date) {
        // pad the date if necessary
        while (!date.endsWith("00")){
            date += "0";
        }
        date = "";
        try {
            this.date = FORMATTER.parse(date.trim());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    public Chapter copy(){
        Chapter copy = new Chapter();
        copy.title = title;
        copy.link = link;
        copy.description = description;
        copy.date = date;
        return copy;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Title: ");
        sb.append(title);
        sb.append('\n');
        sb.append("Date: ");
        sb.append(this.getDate());
        sb.append('\n');
        sb.append("Link: ");
        sb.append(link);
        sb.append('\n');
        sb.append("Description: ");
        sb.append(description);
        return sb.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((date == null) ? 0 : date.hashCode());
        result = prime * result
                + ((description == null) ? 0 : description.hashCode());
        result = prime * result + ((link == null) ? 0 : link.hashCode());
        result = prime * result + ((title == null) ? 0 : title.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Chapter other = (Chapter) obj;
        if (date == null) {
            if (other.date != null)
                return false;
        } else if (!date.equals(other.date))
            return false;
        if (description == null) {
            if (other.description != null)
                return false;
        } else if (!description.equals(other.description))
            return false;
        if (link == null) {
            if (other.link != null)
                return false;
        } else if (!link.equals(other.link))
            return false;
        if (title == null) {
            if (other.title != null)
                return false;
        } else if (!title.equals(other.title))
            return false;
        return true;
    }

    public int compareTo(Chapter another) {
        if (another == null) return 1;
        // sort descending, most recent first
        return another.date.compareTo(date);
    }

    public int getId() {
        // TODO Auto-generated method stub
        return id;
    }

    public void setId(int parseInt) {
        // TODO Auto-generated method stub
        this.id = id;
    }

    public void setImage(String string) {
        // TODO Auto-generated method stub

    }

和我的助手类:

public class ChapterSQLiteOpenHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "chaptertable";
  private static final int DATABASE_VERSION = 1;

  // Database table
  public static final String TABLE_CHAPTER = "Chapter";
  public static final String COLUMN_ID = "_id";
  public static final String COLUMN_LINK = "link";
  public static final String COLUMN_TITLE = "title";
  public static final String COLUMN_DESCRIPTION = "description";
  public static final String COLUMN_PUBDATE = "pubdate";
  public static final String COLUMN_IMAGEID = "imageid";

  // Database creation SQL statement
  private static final String DATABASE_CREATE = "create table " 
      + TABLE_CHAPTER
      + "(" 
      + COLUMN_ID + " integer primary key autoincrement, " 
      + COLUMN_LINK + " text not null, " 
      + COLUMN_TITLE + " text not null," 
      + COLUMN_DESCRIPTION + " text not null" 
      + COLUMN_PUBDATE + " text not null," 
      + COLUMN_IMAGEID + " text not null," 
      + ");";



  public ChapterSQLiteOpenHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }

  // Method is called during creation of the database
  @Override
  public void onCreate(SQLiteDatabase database) {
        database.execSQL(DATABASE_CREATE);
      }

  // Method is called during an upgrade of the database,
  // e.g. if you increase the database version
  // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CHAPTER);

        // Create tables again
        onCreate(db);
    }


  /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    // Adding new contact
    void addContact(Chapter chapter) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_ID, chapter.getId()); // Chapter ID
        values.put(COLUMN_LINK, chapter.getLink()); // Chapter Link
        values.put(COLUMN_TITLE, chapter.getTitle()); // Chapter Title
        values.put(COLUMN_DESCRIPTION, chapter.getDescription()); // Chapter Description
        values.put(COLUMN_PUBDATE, chapter.getDate()); // Chapter Date
        //values.put(COLUMN_IMAGEID, chapter.getImage()); // Chapter Image

        // Inserting Row
        db.insert(TABLE_CHAPTER, null, values);
        db.close(); // Closing database connection
    }

    // Getting single contact
    Chapter getChapter(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_CHAPTER, new String[] { COLUMN_ID,
                COLUMN_ID, COLUMN_LINK }, COLUMN_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Chapter chapter = new Chapter(Integer.parseInt(cursor.getString(0)), cursor.getURL(1), cursor.getString(2), cursor.getString(3), cursor.getString(4));
        // return contact
        return chapter;
    }

    // Getting All Contacts
    public List<Chapter> getAllContacts() {
        List<Chapter> chapterList = new ArrayList<Chapter>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_CHAPTER;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Chapter chapter = new Chapter();
                chapter.setId(Integer.parseInt(cursor.getString(0)));
                chapter.setLink(cursor.getURL(1));
                chapter.setTitle(cursor.getString(2));
                chapter.setDescription(cursor.getString(3));
                chapter.setDate(cursor.getString(4));
                //chapter.setImage(cursor.getString(5));
                // Adding chapter to list
                chapterList.add(chapter);
            } while (cursor.moveToNext());
        }

        // return contact list
        return chapterList;
    }

    // Updating single contact
    public int updateContact(Chapter chapter) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_ID, chapter.getId());
        values.put(COLUMN_LINK, chapter.getLink());
        values.put(COLUMN_TITLE, chapter.getTitle());
        values.put(COLUMN_DESCRIPTION, chapter.getDescription());
        values.put(COLUMN_PUBDATE, chapter.getDate());
        //values.put(COLUMN_IMAGEID, chapter.getImage());

        // updating row
        return db.update(TABLE_CHAPTER, values, COLUMN_ID + " = ?",
                new String[] { String.valueOf(chapter.getId()) });
    }

    // Deleting single contact
    public void deleteContact(Chapter chapter) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_CHAPTER, COLUMN_ID + " = ?",
                new String[] { String.valueOf(chapter.getId()) });
        db.close();
    }

    // Getting contacts Count
    public int getChaptersCount() {
        String countQuery = "SELECT  * FROM " + TABLE_CHAPTER;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        // return count
        return cursor.getCount();
    }

我在 values.put 行上得到编译错误链接,以及 Chapter chapter = new Chapter... 行。

4

1 回答 1

1

您需要在copy()方法中使用 setter 方法设置属性,例如:

public Chapter copy(){
    Chapter copy = new Chapter();
    copy.setTitle(this.title);
    copy.setLink(this.link);
    copy.setDescription(this.description);
    copy.setDate(this.date);
    return copy;
}
于 2012-08-22T17:51:26.200 回答