Android将字符串保存到数据库

时间:2014-03-09 13:42:16

标签: java android sqlite

我是Android开发的新手,现在我要做的是保存我键入的消息和用户名。我从vogella.com获得了此代码,但它仅针对消息编写。我试图添加用户名,但是我收到错误“java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.testdatabaseactivity / com.example.testdatabaseactivity.TestDatabaseActivity}:android.database.sqlite.SQLiteException:no这样的列:SENDER(代码1):,在编译时:SELECT _id,SENDER,MESSAGE FROM MESSAGES“ 我无法弄清楚出了什么问题。需要一点帮助。

MessagesDataSource.java

package com.example.testdatabaseactivity;

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

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class MessagesDataSource {

  // Database fields
  private SQLiteDatabase database;
  private MySQLiteHelper dbHelper;
  private String[] allColumns = { MySQLiteHelper.COLUMN_ID, MySQLiteHelper.COLUMN_SENDER, MySQLiteHelper.COLUMN_MESSAGE};

  public MessagesDataSource(Context context) {
    dbHelper = new MySQLiteHelper(context);
  }

  public void open() throws SQLException {
    database = dbHelper.getWritableDatabase();
  }

  public void close() {
    dbHelper.close();
  }

  public Message createMessage(String sender, String message) {
    ContentValues values = new ContentValues();
    values.put(MySQLiteHelper.COLUMN_MESSAGE, message);
    values.put(MySQLiteHelper.COLUMN_SENDER, sender);
    long insertId = database.insert(MySQLiteHelper.TABLE_MESSAGES, null,values);
    Cursor cursor = database.query(MySQLiteHelper.TABLE_MESSAGES,allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,null, null, null);
    cursor.moveToFirst();
    Message newMessage = cursorToMessage(cursor);
    cursor.close();
    return newMessage;
  }

  public List<Message> getAllMessages() {
    List<Message> messages = new ArrayList<Message>();

    Cursor cursor = database.query(MySQLiteHelper.TABLE_MESSAGES,allColumns, null, null, null, null, null);

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
      Message message = cursorToMessage(cursor);
      messages.add(message);
      cursor.moveToNext();
    }
    // make sure to close the cursor
    cursor.close();
    return messages;
  }

  private Message cursorToMessage(Cursor cursor) {
    Message message = new Message();
    message.setId(cursor.getLong(0));
    message.setMessage(cursor.getString(2));
    message.setSender(cursor.getString(1));
    return message;
  }
}

Message.java

      package com.example.testdatabaseactivity;

      public class Message {
  private long id;
  private String message;
  private String sender;

  public long getId() {
    return id;
  }

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

  public String getMessage() {
    return message;
  }

  public void setMessage(String message) {
    this.message = message;
  }
  public String getSender() {
        return sender;
      }

      public void setSender(String sender) {
        this.sender = sender;
      }

  // Will be used by the ArrayAdapter in the ListView
  @Override
  public String toString() {
    return message;
  }
} 

MySQLiteHelper.java

package com.example.testdatabaseactivity;

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

public class MySQLiteHelper extends SQLiteOpenHelper {

  public static final String TABLE_MESSAGES = "MESSAGES";
  public static final String COLUMN_ID = "_id";
  public static final String COLUMN_MESSAGE = "MESSAGE";
  public static final String COLUMN_SENDER = "SENDER";

  private static final String DATABASE_NAME = "message.db";
  private static final int DATABASE_VERSION = 1;

  // Database creation sql statement
  private static final String DATABASE_CREATE = "create table " + TABLE_MESSAGES + "(" 
  + COLUMN_ID + " integer primary key autoincrement, " 
  + COLUMN_SENDER + "sender not null, " 
  + COLUMN_MESSAGE + " text not null);";

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

  @Override
  public void onCreate(SQLiteDatabase database) {
    database.execSQL(DATABASE_CREATE);

  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.w(MySQLiteHelper.class.getName(),"Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_MESSAGES);
    onCreate(db);
  }

} 

TestDatabaseActivity.java

package com.example.testdatabaseactivity;

import java.util.List;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;

public class TestDatabaseActivity extends ListActivity {
  private MessagesDataSource datasource;
  public String sender = "Suren";
  EditText edittext;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    edittext = (EditText) findViewById(R.id.txt_message);
    datasource = new MessagesDataSource(this);
    datasource.open();
    List<Message> values = datasource.getAllMessages();

    // use the SimpleCursorAdapter to show the
    // elements in a ListView
    ArrayAdapter<Message> adapter = new ArrayAdapter<Message>(this,android.R.layout.simple_list_item_1, values);
    setListAdapter(adapter);
  }

  // Will be called via the onClick attribute
  // of the buttons in main.xml
  public void onClick(View view) {
    @SuppressWarnings("unchecked")
    String text = edittext.getText().toString();
    ArrayAdapter<Message> adapter = (ArrayAdapter<Message>) getListAdapter();
    Message message = null;
      if(edittext.length() == 0){
        return;
     }else{
      // save the new message to the database
      message = datasource.createMessage(sender, text);
      adapter.add(message);
      edittext.getText().clear();

   }
    adapter.notifyDataSetChanged();
  }

  @Override
  protected void onResume() {
    datasource.open();
    super.onResume();
  }

  @Override
  protected void onPause() {
    datasource.close();
    super.onPause();
  }

} 

2 个答案:

答案 0 :(得分:2)

CREATE TableColumn Name

之间更正Column Type查询需求空间
// Database creation sql statement
private static final String DATABASE_CREATE = "create table " + TABLE_MESSAGES + "(" 
+ COLUMN_ID + " integer primary key autoincrement, " 
+ COLUMN_SENDER + " text not null, " 
+ COLUMN_MESSAGE + " text not null);";

您忘记在查询COLUMN_SENDER + "sender not null, "

中添加空格

答案 1 :(得分:2)

//数据库创建sql语句

private static final String DATABASE_CREATE = "CREATE TABLE " + TABLE_MESSAGES + "(" 
  + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " 
  + COLUMN_SENDER + " text not null, " 
  + COLUMN_MESSAGE + " text not null)";

“发件人”不是一种类型。你需要把“文字”。 并给出适当的空间。