【问题标题】:Android SQLite database simple assistanceAndroid SQLite 数据库简单辅助
【发布时间】:2014-07-10 01:08:47
【问题描述】:

所以我正在关注本教程:http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/,但似乎仍然没有产生任何结果。有人可以帮助我,因为我不知道为什么它不起作用。谢谢!它只是在 logcat 中给了我错误!

另外,我将如何将这些数据发布到另一个活动中的 textView 或 ListView 中?

public class DatabaseHandler extends SQLiteOpenHelper{

// Database version
private static final int DATABASE_VERSION = 1;
// Database name
private static final String DATABASE_NAME = "athleteProgram";
// Athletes table name
private static final String TABLE_ATHLETES= "athletes";

// Athletes table columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_AGE = "age";

DatabaseHandler(Context context)
{
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating table
@Override
public void onCreate(SQLiteDatabase db)
{
    String CREATE_ATHLETES_TABLE = "CREATE TABLE " + TABLE_ATHLETES + "(" + KEY_ID +
            " INTEGER PRIMARY KEY," + KEY_NAME + "TEXT," + KEY_AGE + " TEXT" + ")";
    db.execSQL(CREATE_ATHLETES_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATHLETES);

    // Create tables again
    onCreate(db);
}
// All CRUD(Create, Read, Update, Delete) Operations

// Adding athlete
void addAthlete(Athlete athlete)
{
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, athlete.getName());
    values.put(KEY_AGE, athlete.getAge());

    // Inserting Row
    db.insert(TABLE_ATHLETES, null, values);
    db.close(); // Closing database connection
}
// Getting single Athlete
public Athlete getAthlete(int id)
{
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_ATHLETES, new String[] {KEY_ID, KEY_NAME, KEY_AGE}, KEY_ID + "=?",
            new String[] {String.valueOf(id)}, null, null, null, null);
    if(cursor != null)
    {
        cursor.moveToFirst();
    }

    Athlete athlete = new Athlete(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1), cursor.getString(2));
    return athlete;
}
// Getting All Athletes
public List<Athlete> getAllAthletes() {
    List<Athlete> athleteList = new ArrayList<Athlete>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_ATHLETES;

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

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Athlete athlete = new Athlete();
            athlete.setID(Integer.parseInt(cursor.getString(0)));
            athlete.setName(cursor.getString(1));
            athlete.setAge(cursor.getString(2));
            // Adding contact to list
            athleteList.add(athlete);
        } while (cursor.moveToNext());
    }

    // return athlete list
    return athleteList;
}
// Updating single athlete
public int updateAthlete(Athlete athlete) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, athlete.getName());
    values.put(KEY_AGE, athlete.getAge());

    // updating row
    return db.update(TABLE_ATHLETES, values, KEY_ID + " = ?",
            new String[] { String.valueOf(athlete.getID()) });
}
// Deleting single athlete
public void deleteAthlete(Athlete athlete) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_ATHLETES, KEY_ID + " = ?",
            new String[] { String.valueOf(athlete.getID()) });
    db.close();
}
// Getting athletes Count
public int getAthletesCount() {
    String countQuery = "SELECT  * FROM " + TABLE_ATHLETES;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();

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

}





public class Athlete {

    //private variables
    int _id;
    String _name;
    String _age;

    // Empty constructor
    public Athlete(){

    }
    // constructor
    public Athlete(int id, String name, String age){
        this._id = id;
        this._name = name;
        this._age = age;
    }

    // constructor
    public Athlete(String name, String age){
        this._name = name;
        this._age = age;
    }
    // getting ID
    public int getID(){
        return this._id;
    }

    // setting id
    public void setID(int id){
        this._id = id;
    }

    // getting name
    public String getName(){
        return this._name;
    }

    // setting name
    public void setName(String name){
        this._name = name;
    }

    // getting age
    public String getAge(){
        return this._age;
    }

    // setting age
    public void setAge(String age){
        this._age = age;
}
}

public class StartingActivity extends ListActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_starting);


}

// Will be called via the onClick attribute
// of the buttons in main.xml
public void onClick(View view) {
    @SuppressWarnings("unchecked")
    EditText editName = (EditText) findViewById(R.id.editName);
    EditText editAge = (EditText) findViewById(R.id.editAge);
    EditText editDate = (EditText) findViewById(R.id.editDate);
    EditText editTier = (EditText) findViewById(R.id.editTier);
    DatabaseHandler db = new DatabaseHandler(this);

    /**
     * CRUD Operations
     * */
    // Inserting Contacts
    Log.d("Insert: ", "Inserting ..");
    db.addAthlete(new Athlete("Joe", "20"));
    db.addAthlete(new Athlete(editName.getText().toString(), editAge.getText().toString()));

    // Reading all contacts
    Log.d("Reading: ", "Reading all contacts..");
    List<Athlete> athletes = db.getAllAthletes();

    for (Athlete ath : athletes) {
        String log = "Id: " + ath.getID() + " ,Name: " + ath.getName() + " ,Phone: " + ath.getAge();
        // Writing Contacts to log
        Log.d("Name: ", log);

    }
}
}

【问题讨论】:

  • 能否显示错误日志。我想我遇到了问题,但我需要错误日志来确认。
  • 发布时间过长。不过我可以pm你
  • 这里只能复制粘贴....
  • 这段代码你调试了吗...如果没有那么先调试并找到错误位置...那我来帮你。
  • 07-10 00:54:28.466 331-331/com.FP.x.firstproject I/Process: 发送信号。 PID: 331 SIG: 9 07-10 00:55:39.756 365-365/com.FP.x.firstproject D/Insert:: 插入 .. 07-10 00:55:39.796 365-365/com.FP.x .firstproject I/Database:sqlite 返回:错误代码 = 1,msg = 表运动员没有名为 age 07-10 00:55:39.806 365-365/com.FP.x.firstproject E/Database 的列:插入 age= 时出错20 name=Joe android.database.sqlite.SQLiteException: 表运动员没有名为 age: 的列,编译时:INSERT INTO sports(age, name) VALUES(?, ?);

标签: java android database eclipse sqlite


【解决方案1】:

试试吧,也许你没有插入主键。我插入示例输入。

 db.addAthlete(new Athlete(1,"Joe", "20"));
 //same on this line
 db.addAthlete(new Athlete(2,editName.getText().toString(), editAge.getText().toString()));

也许能帮上忙 抱歉英语不好

【讨论】:

    【解决方案2】:

    下面的create语句有问题。 KEY_NAME 与其类型之间缺少空格。

    字符串 CREATE_ATHLETES_TABLE = "创建表" + TABLE_ATHLETES + "(" + KEY_ID + “整数主键,”+ KEY_NAME +“文本”,+ KEY_AGE +“文本”+“)”; db.execSQL(CREATE_ATHLETES_TABLE);

    【讨论】:

      猜你喜欢
      • 2013-01-16
      • 1970-01-01
      • 2012-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-08
      • 2011-09-26
      • 2015-12-18
      相关资源
      最近更新 更多