用于评论功能的 SQLite 数据库

SQLite Database for Commenting function

代码没有错误。但是,我正在尝试构建一个评论部分,其中名称和评论将保存在数据库 (SQLite) 中。

1) 从另一个页面返回后,它不会留在 Textview 中。 2)例子,我评论了一次,评论显示。我又评论了,居然把之前的评论和新的评论一起重新显示了。

public class BuyerHome extends AppCompatActivity {
DatabaseHelper2 myDB;
//EditText name,comment;

EditText nameIn;
EditText commentIn;
TextView viewComment;

Button postComment;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_buyer_home);

    nameIn = (EditText) findViewById(R.id.nameInput);
    commentIn = (EditText) findViewById(R.id.commentText);
    viewComment = (TextView) findViewById(R.id.viewCommentText);
    myDB = new DatabaseHelper2(this);



    postComment = (Button) findViewById(R.id.buttonComment);

    postComment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String name = nameIn.getText().toString();
            String comment = commentIn.getText().toString();

            if(nameIn.length()!=0 && commentIn.length()!=0){
                AddData(name,comment);
                nameIn.setText("");
                commentIn.setText("");
            }else{
                Toast.makeText(BuyerHome.this, "Insert fields", 
Toast.LENGTH_SHORT).show();
            }

            Cursor data = myDB.getContents();

            if(data.getCount()==0){
                Toast.makeText(BuyerHome.this, "Database empty", 
Toast.LENGTH_SHORT).show();
            }
            else{

                while(data.moveToNext()){
                    viewComment.append(data.getString(1));
                    viewComment.append(data.getString(2)+"\n");
                }
            }

            //viewComment.append("\n"+name+":"+comment);




    }
});
}
    public void AddData(String name,String comment){
    boolean insertData = myDB.insertData(name,comment);

    if(insertData==true){
        Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
    }else{
        Toast.makeText(this, "Fail", Toast.LENGTH_SHORT).show();
    }
      }
}

1) 只要页面可用,我希望过去的评论一直存在。 2) 我希望只显示最新的评论(在过去的评论之上),而不是过去的评论(再次重新显示)和新评论。

我建议也许对较旧的评论使用第二个视图。您还需要一种方法来确定最新的评论而不是旧的评论。

在下面的示例中,第二个视图是一个列表视图(这将使您能够单击特定消息,可能会引用它,可能会提取名称)。

该示例通过 id column 满足两种确定最后发布评论的方式(注意 _id 实际上用作列名称,这样就可以将游标适配器用于 ListView,这可能是有利的)。

为了便于在 returning onResume 方法后显示评论,activity。

这是代码:-

DatabaseHelper2.java

public class DatabaseHelper2 extends SQLiteOpenHelper {

    private final static String DBNAME = "buyerdb";
    private final static int DBVERSION = 1;

    public final static String TBL_COMMENT = "comment";
    public final static String COL_COMMENT_ID = BaseColumns._ID;
    public final static String COL_COMMENT_NAME = "name";
    public final static String COL_COMMENT_COMMENT = "comment";
    public final static String COl_COMMENT_TIMESTAMP = "timestamp";

    private String crt_tbl_comment = "CREATE TABLE IF NOT EXISTS " + TBL_COMMENT + "(" +
            COL_COMMENT_ID + " INTEGER PRIMARY KEY, " +
            COL_COMMENT_NAME + " TEXT," +
            COL_COMMENT_COMMENT + " TEXT, " +
            COl_COMMENT_TIMESTAMP + " TEXT DEFAULT CURRENT_TIMESTAMP" +
            ")";

    SQLiteDatabase mDB;

    public DatabaseHelper2(Context context) {
        super(context, DBNAME, null, DBVERSION);
        mDB = this.getWritableDatabase();
    }

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

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

    }

    public long addData(String name, String comment) {
        ContentValues cv = new ContentValues();
        cv.put(COL_COMMENT_NAME,name);
        cv.put(COL_COMMENT_COMMENT,comment);
        return mDB.insert(TBL_COMMENT,null,cv);
    }

    public Cursor getLatestComment() {
        return mDB.query(TBL_COMMENT,null,null,null,null,null,COl_COMMENT_TIMESTAMP + " DESC","1");
    }

    public Cursor getAllButLatestComment() {
        String whereclause = COL_COMMENT_ID + " < (SELECT max(" +
                COL_COMMENT_ID +
                ") FROM " + TBL_COMMENT +
                ")";
        return mDB.query(TBL_COMMENT,null,whereclause,null,null,null,COl_COMMENT_TIMESTAMP + " DESC");
    }
}
  • 请注意,timestamp 列尚未使用,但可以使用,因为添加行(评论)时,当前时间戳将自动用于设置列。

  • 请注意 getLatestComment 和 getAllButLatestComment 方法return 具有适当行的 Cursor。

BuyerHome.java

public class BuyerHome extends AppCompatActivity {

    EditText nameIn;
    EditText commentIn;
    TextView viewComment;
    Button postComment;
    ListView olderComments; //<<<<<<<<<< Added (Listview needs to be added to the layout)

    DatabaseHelper2 myDB;
    Cursor oldermessages, latestmessage; //<<<<<<<<<< Added
    SimpleCursorAdapter sma; //<<<<<<<<<< Added adapter for the ListView

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buyer_home);

        nameIn = (EditText) findViewById(R.id.nameInput);
        commentIn = (EditText) findViewById(R.id.commentText);
        viewComment = (TextView) findViewById(R.id.viewCommentText);
        olderComments = (ListView) findViewById(R.id.olderComments); //<<<<<<<<<< Added

        myDB = new DatabaseHelper2(this);
        postComment = (Button) findViewById(R.id.buttonComment);
        postComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = nameIn.getText().toString();
                String comment = commentIn.getText().toString();

                if (nameIn.length() != 0 && commentIn.length() != 0) {
                    myDB.addData(name, comment); //<<<<<<<<<< method starts changed lower case a
                    nameIn.setText("");
                    commentIn.setText("");
                } else {
                    Toast.makeText(BuyerHome.this, "Insert fields",
                            Toast.LENGTH_SHORT).show();
                }
                displayComments(); //<<<<<<<<<< added to refresh the display according to the latest comments
            }
        });
    }

    //<<<<<<<<<< ADDED so will display comments whenever called including returning from another activity
    @Override
    protected void onResume() {
        super.onResume();
        displayComments();
    }

    //<<<<<<<<<< ADDED entire method for displaying comments
    private void displayComments() {
        latestmessage = myDB.getLatestComment();
        if (latestmessage.moveToFirst()) {
            viewComment.setText(latestmessage.getString(latestmessage.getColumnIndex(DatabaseHelper2.COL_COMMENT_NAME)) +
                    " said :- " +
                    latestmessage.getString(latestmessage.getColumnIndex(DatabaseHelper2.COL_COMMENT_COMMENT)));
        } else {
            viewComment.setText("");
        }
        oldermessages = myDB.getAllButLatestComment();
        if (sma == null) {
            sma = new SimpleCursorAdapter(
                    this,
                    android.R.layout.simple_list_item_2,oldermessages,
                    new String[]{DatabaseHelper2.COL_COMMENT_NAME,DatabaseHelper2.COL_COMMENT_COMMENT},
                    new int[]{android.R.id.text1,android.R.id.text2},
                    0
            );
            olderComments.setAdapter(sma);
        } else {
            sma.swapCursor(oldermessages);
        }
    }
}

结果

  • 突出显示的行是最新评论。
  • 最新评论后面是所有其他评论的列表。