向sqlite数据库添加新属性

时间:2019-05-17 18:38:42

标签: java android database android-sqlite

我对Android Studio还是很陌生,并且第一次尝试在我的项目中实现数据库。我刚刚在Android Studio的SQLite数据库中添加了一个名为“ noteThema”的新属性。现在,我的ListView(在活动“ Begriffe”中)不再显示数据库中的数据。此外,每次启动时,“ Spielen”活动都会崩溃。但是,该程序不会显示任何错误消息。 如果您能给我一些帮助,我将很高兴!

课堂笔记

public class Note implements Serializable {
private int noteId;
private String noteTitle;
private String noteContent;
private int noteThema;

public Note()  {

}

public Note(  String noteTitle, String noteContent, int noteThema) {
    this.noteTitle= noteTitle;
    this.noteContent= noteContent;
    this.noteThema = noteThema;
}

public Note(int noteId, String noteTitle, String noteContent, int noteThema) {
    this.noteId= noteId;
    this.noteTitle= noteTitle;
    this.noteContent= noteContent;
    this.noteThema = noteThema;
}

public int getNoteId() {
    return noteId;
}

public void setNoteId(int noteId) {
    this.noteId = noteId;
}

public String getNoteTitle() {
    return noteTitle;
}

public void setNoteTitle(String noteTitle) {
    this.noteTitle = noteTitle;
}


public String getNoteContent() {
    return noteContent;
}

public void setNoteContent(String noteContent) {
    this.noteContent = noteContent;
}

public int getNoteThema(){return noteThema;}


public void setNoteThema(int noteThema) {this.noteThema = noteThema;}


@Override
public String toString()  {
    return this.noteTitle;
}

}

贝格里夫课程的一部分

public class Begriffe extends AppCompatActivity {

private ListView listView;


private static final int MY_REQUEST_CODE = 1000;

private final List<Note> noteList = new ArrayList<Note>();
private ArrayAdapter<Note> listViewAdapter;

private Button add;

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


    // Get ListView object from xml
    listView = (ListView) findViewById(R.id.listView);
    add = (Button)findViewById(R.id.add2);

    MyDatabaseHelper db = new MyDatabaseHelper(this);
    db.createDefaultNotesIfNeed();

    List<Note> list =  db.getAllNotes();
    this.noteList.addAll(list);
    Collections.sort(noteList, new NameComparator());



    add.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent(Begriffe.this, AddEditNoteActivity.class);

            // Start AddEditNoteActivity, (with feedback).
            Begriffe.this.startActivityForResult(intent, MY_REQUEST_CODE);
        }
    });


    this.listViewAdapter = new ArrayAdapter<Note>(this,
            android.R.layout.simple_list_item_1, android.R.id.text1, this.noteList);


    // Assign adapter to ListView
    this.listView.setAdapter(this.listViewAdapter);

    // Register the ListView for Context menu
    registerForContextMenu(this.listView);
}

MyDarabaseHelper类

public class MyDatabaseHelper extends SQLiteOpenHelper {

private static final String TAG = "SQLite";

// Database Version
private static final int DATABASE_VERSION = 3;

// Database Name
private static final String DATABASE_NAME = "Note_Manager";

// Table name: Note.
private static final String TABLE_NOTE = "Note";

private static final String COLUMN_NOTE_ID ="Note_Id";
private static final String COLUMN_NOTE_TITLE ="Note_Title";
private static final String COLUMN_NOTE_CONTENT = "Note_Content";
private static final String COLUMN_NOTE_THEMA = "Note_Thema";

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

// Create table
@Override
public void onCreate(SQLiteDatabase db) {
    Log.i(TAG, "MyDatabaseHelper.onCreate ... ");
    // Script.
    String script = "CREATE TABLE " + TABLE_NOTE + "("
            + COLUMN_NOTE_ID + " INTEGER PRIMARY KEY," + COLUMN_NOTE_TITLE + " TEXT,"
            + COLUMN_NOTE_CONTENT + " TEXT" + COLUMN_NOTE_THEMA + "INTEGER" + ")";
    // Execute Script.
    db.execSQL(script);
}


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

    Log.i(TAG, "MyDatabaseHelper.onUpgrade ... ");
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTE);

    // Create tables again
    onCreate(db);
}


// If Note table has no data
// default, Insert 2 records.
public void createDefaultNotesIfNeed()  {
    int count = this.getNotesCount();
    if(count ==0 ) {

        Note note1 = new Note("Intermembranraum", "Erklären", 2);
        Note note2 = new Note("Katalysatoren", "Erklären", 2);


        this.addNote(note1);
        this.addNote(note2);


    }
}


public void addNote(Note note) {
    Log.i(TAG, "MyDatabaseHelper.addNote ... " + note.getNoteTitle());

    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(COLUMN_NOTE_TITLE, note.getNoteTitle());
    values.put(COLUMN_NOTE_CONTENT, note.getNoteContent());
    values.put(COLUMN_NOTE_THEMA, note.getNoteThema());

    // Inserting Row
    db.insert(TABLE_NOTE, null, values);

    // Closing database connection
    db.close();
}


public List<Note> getAllNotes() {
    Log.i(TAG, "MyDatabaseHelper.getAllNotes ... " );

    List<Note> noteList = new ArrayList<Note>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_NOTE;

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

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Note note = new Note();
            note.setNoteId(Integer.parseInt(cursor.getString(0)));
            note.setNoteTitle(cursor.getString(1));
            note.setNoteContent(cursor.getString(2));
            note.setNoteThema(Integer.parseInt(cursor.getString(3)));
            // Adding note to list
            noteList.add(note);
        } while (cursor.moveToNext());
    }

    // return note list
    return noteList;
}

public int getNotesCount() {
    Log.i(TAG, "MyDatabaseHelper.getNotesCount ... " );

    String countQuery = "SELECT  * FROM " + TABLE_NOTE;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);

    int count = cursor.getCount();

    cursor.close();

    // return count
    return count;
}


public int updateNote(Note note) {
    Log.i(TAG, "MyDatabaseHelper.updateNote ... "  + note.getNoteTitle());

    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(COLUMN_NOTE_TITLE, note.getNoteTitle());
    values.put(COLUMN_NOTE_CONTENT, note.getNoteContent());
    values.put(COLUMN_NOTE_THEMA, note.getNoteThema());

    // updating row
    return db.update(TABLE_NOTE, values, COLUMN_NOTE_ID + " = ?",
            new String[]{String.valueOf(note.getNoteId())});
}

public void deleteNote(Note note) {
    Log.i(TAG, "MyDatabaseHelper.updateNote ... " + note.getNoteTitle() );

    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_NOTE, COLUMN_NOTE_ID + " = ?",
            new String[] { String.valueOf(note.getNoteId()) });
    db.close();
}

}

Spielen类的一部分

public class Spielen extends AppCompatActivity {

private TextView TextView1;
private TextView TextView2;
private Button skip;
private Button weiter;
private TextView score2;
private int score;
private Button restart;
private ProgressBar simpleProgressBar;
private ProgressBar simpleProgressBar2;

private int COUNTDOWN_IN_MILLIS;
private CountDownTimer countDownTimer;
private long timeLeftInMillis;
private List<Integer> myList = new ArrayList<Integer>();
private int i2;
private Note begriff;
private List<Note> list;
private Boolean skip2;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_spielen);
    score = 0;
    skip = (Button)findViewById(R.id.button_save);
    weiter = (Button)findViewById(R.id.button_cancel);
    score2 = (TextView)findViewById(R.id.Score);
    restart = (Button)findViewById(R.id.restart);
    COUNTDOWN_IN_MILLIS = getIntent().getExtras().getInt("time");
    skip2 = getIntent().getExtras().getBoolean("skip");
    simpleProgressBar=(ProgressBar)findViewById(R.id.time3);
    simpleProgressBar2=(ProgressBar)findViewById(R.id.time4);
    simpleProgressBar.setMax(COUNTDOWN_IN_MILLIS);
    simpleProgressBar.setProgress(COUNTDOWN_IN_MILLIS);

    start();


}

public void start(){
    timeLeftInMillis = COUNTDOWN_IN_MILLIS;

    if (skip2 == true){
        skip.setEnabled(false);
        skip.setVisibility(View.GONE);
    }else{

    }

    score2.setText("Score: 0");
    score = 0;
    startCountDown();
    erstellen();
}

public void erstellen() {

    TextView1 = (TextView) findViewById(R.id.begriff);
    TextView2 = (TextView) findViewById(R.id.art);

    MyDatabaseHelper db = new MyDatabaseHelper(this);
    db.createDefaultNotesIfNeed();

    list = db.getAllNotes();
    int i = list.size();
    int i3 = i - 30;
    int i4 = myList.size();
    Random rand = new Random();
    i2 = rand.nextInt(i);

    if (i3 == i4){
        myList.clear();
        erstellen2();
    }else{
        erstellen2();
    }
}

public void erstellen2(){
    boolean check = contains(myList, i2);


    if(check == true){
        erstellen();
    }else {
        begriff = list.get(i2);
        String begriff2 = begriff.getNoteTitle();
        String begriff3 = begriff.getNoteContent();

        TextView1.setText(begriff2);
        TextView2.setText(begriff3);

        userEingabe();
    }


}

2 个答案:

答案 0 :(得分:2)

您可以使用String script = "CREATE TABLE " + TABLE_NOTE + "(" + COLUMN_NOTE_ID + " INTEGER PRIMARY KEY," + COLUMN_NOTE_TITLE + " TEXT," + COLUMN_NOTE_CONTENT + " TEXT," + COLUMN_NOTE_THEMA + " INTEGER" + ")";。这有两件事,它将在Note_content和Note_thema之间添加一个逗号,并在INTEGER之前的Note_thema之后添加空格。

答案 1 :(得分:1)

使用

String script = "CREATE TABLE " + TABLE_NOTE + "("
            + COLUMN_NOTE_ID + " INTEGER PRIMARY KEY," + COLUMN_NOTE_TITLE + " TEXT,"
            + COLUMN_NOTE_CONTENT + " TEXT" + COLUMN_NOTE_THEMA + "INTEGER" + ")";

在第2列和第3列之间已省略2个问题,在最后一个列名称和类型之间已省略了空格。

更改为使用:-

String script = "CREATE TABLE " + TABLE_NOTE + "(" + 
    COLUMN_NOTE_ID + " INTEGER PRIMARY KEY," + 
    COLUMN_NOTE_TITLE + " TEXT," + 
    COLUMN_NOTE_CONTENT + " TEXT," + //<<<<<<<<<< COMMA ADDED TO seperate column definitions
    COLUMN_NOTE_THEMA + " INTEGER" + //<<<<<<<<<< SPACE ADDED between column name and column type
    ")";
  • 注意,进行更改后,删除应用程序的数据或卸载应用程序,或增加DATABASE_VERSION的值。完成一项后,重新运行该应用程序。
    • 请注意,所有现有数据都将丢失,如果您需要保留现有数据,则需要使用ALTER命令添加该列。