0

我有一个应用程序,用户可以在其中创建事件,将其保存到数据库中,然后显示在 ListView 中。

这是我将事件添加到数据库的活动:

public class AddEvent extends Activity{

DBAdapter DB;
int day;
int month;
int year;
int hour;
int minute;
String date;
String time;
String description;
String name;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.event);
    openDB();

    DatePicker Date = (DatePicker) findViewById (R.id.DatePicker);
    year = Date.getYear();
    month = Date.getMonth();
    day = Date.getDayOfMonth();
    String yearstr = Integer.toString(year);
    String monthstr = Integer.toString(month);
    String daystr = Integer.toString(day);
    date = monthstr+"/"+daystr+"/"+yearstr;
    TimePicker Time = (TimePicker) findViewById (R.id.TimePicker);
    hour = Time.getCurrentHour();
    minute = Time.getCurrentHour();
    String hourstr;
    if(hour>12){
        hourstr = Integer.toString(hour-12);
    }
    else{
        hourstr = Integer.toString(hour);
    }
    String minutestr = Integer.toString(minute);
    time = hourstr+":"+minutestr;
    EditText namefield = (EditText) findViewById (R.id.EventNameField);
    name = namefield.getText().toString().trim();
    EditText descfield = (EditText) findViewById (R.id.editText2);
        description = descfield.getText().toString().trim();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    closeDB();
}

public void Add(View v){
    DB.insertRow(name, date, time, description, "event");       
    Intent move = new Intent (this, main.class);
    startActivity(move);
}

public void openDB(){
    DB = new DBAdapter(this);
    DB.open();
}

 public void closeDB(){
    DB.close();
   }
}

这是我要显示 ListView 的活动:

public class main extends Activity{

DBAdapter DB;
ListView mainList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    openDB();
    populateListViewFromDB();
}

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    closeDB();
}

public void AddEvent(View v){
    Intent StartAddNew = new Intent(this, AddNew.class);
    startActivity(StartAddNew);
}

public void openDB(){
    DB =  new DBAdapter(this);
    DB.open();
    populateListViewFromDB();
}
public void closeDB(){
    DB.close();
}

public void populateListViewFromDB(){
    Cursor cursor = DB.getAllRows();

    startManagingCursor(cursor);

    // Setup mapping from cursor to view fields:
    String[] fromFieldNames = new String[] 
            { DBAdapter.Value_1, DBAdapter.Value_2, DBAdapter.Value_3,    DBAdapter.Value_4, DBAdapter.Value_5};
    int[] toViewIDs = new int[]
{R.id.itemName,R.id.itemMain,R.id.itemExtra,R.id.itemDescription,R.id.itemType};

    // Create adapter to may columns of the DB onto element in the UI.
    SimpleCursorAdapter myCursorAdapter = 
            new SimpleCursorAdapter(this, R.layout.listitem, cursor,    fromFieldNames, toViewIDs)
    {
        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            final View row = super.getView(position, convertView, parent);
            if (position % 2 == 0)
                row.setBackgroundResource(android.R.color.darker_gray);
            else
                row.setBackgroundResource(android.R.color.background_light);
            return row;
        }
    };

    mainList = (ListView) findViewById (R.id.mainList);
    mainList.setAdapter(myCursorAdapter);
}
}

还有我的 DBAdapter:

public class DBAdapter {

/////////////////////////////////////////////////////////////////////
//  Constants & Data
/////////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";

// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
 * CHANGE 1:
 */
// TODO: Setup your fields here:
public static final String KEY_NAME = "name";
public static final String Value_1 = "value1";
public static final String Value_2 = "value2";
public static final String Value_3 = "value3";
public static final String Value_4 = "value4";
public static final String Value_5 = "value5";

// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_1 = 2;
public static final int COL_2 = 3;
public static final int COL_3 = 4;
public static final int COL_4 = 5;
public static final int COL_5 = 6;


public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, Value_1, Value_2, Value_3, Value_4, Value_5};

// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "MyDb";
public static final String DATABASE_TABLE = "mainTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;   

private static final String DATABASE_CREATE_SQL = 
        "create table " + DATABASE_TABLE 
        + " (" + KEY_ROWID + " integer primary key autoincrement, "

        /*
         * CHANGE 2:
         */
        // TODO: Place your fields here!
        // + KEY_{...} + " {type} not null"
        //  - Key is the column name you created above.
        //  - {type} is one of: text, integer, real, blob
        //      (http://www.sqlite.org/datatype3.html)
        //  - "not null" means it is a required field (must be given a value).
        // NOTE: All must be comma separated (end of line!) Last one must have NO comma!!
        + KEY_NAME + " text not null, "
        + Value_1 + " text not null, "
        + Value_2 + " text not null, "
        + Value_3 + " text not null, "
        + Value_4 + " text not null, "
        + Value_5 + " text not null"

        // Rest  of creation:
        + ");";

// Context of application who uses us.
private final Context context;

private DatabaseHelper myDBHelper;
private SQLiteDatabase db;

/////////////////////////////////////////////////////////////////////
//  Public methods:
/////////////////////////////////////////////////////////////////////

public DBAdapter(Context ctx) {
    this.context = ctx;
    myDBHelper = new DatabaseHelper(context);
}

// Open the database connection.
public DBAdapter open() {
    db = myDBHelper.getWritableDatabase();
    return this;
}

// Close the database connection.
public void close() {
    myDBHelper.close();
}

// Add a new set of values to the database.
public long insertRow(String Value1, String Value2, String Value3, String Value4, String Value5) {
    /*
     * CHANGE 3:
     */     
    // TODO: Update data in the row with new fields.
    // TODO: Also change the function's arguments to be what you need!
    // Create row's data:
    ContentValues initialValues = new ContentValues();
    initialValues.put(Value_1, Value1);
    initialValues.put(Value_2, Value2);
    initialValues.put(Value_3, Value3);
    initialValues.put(Value_4, Value4);
    initialValues.put(Value_5, Value5);

    // Insert it into the database.
    return db.insert(DATABASE_TABLE, null, initialValues);
}

// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
    String where = KEY_ROWID + "=" + rowId;
    return db.delete(DATABASE_TABLE, where, null) != 0;
}

public void deleteAll() {
    Cursor c = getAllRows();
    long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
    if (c.moveToFirst()) {
        do {
            deleteRow(c.getLong((int) rowId));              
        } while (c.moveToNext());
    }
    c.close();
}

// Return all data in the database.
public Cursor getAllRows() {
    String where = null;
    Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS, 
                        where, null, null, null, null, null);
    if (c != null) {
        c.moveToFirst();
    }
    return c;
}

// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
    String where = KEY_ROWID + "=" + rowId;
    Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS, 
                    where, null, null, null, null, null);
    if (c != null) {
        c.moveToFirst();
    }
    return c;
}

// Change an existing row to be equal to new data.
public boolean updateRow(int rowId, String Value1, String Value2, String Value3, String Value4, String Value5) {
    String where = KEY_ROWID + "=" + rowId;

    /*
     * CHANGE 4:
     */
    // TODO: Update data in the row with new fields.
    // TODO: Also change the function's arguments to be what you need!
    // Create row's data:
    ContentValues newValues = new ContentValues();
    newValues.put(Value_1, Value1);
    newValues.put(Value_2, Value2);
    newValues.put(Value_3, Value3);
    newValues.put(Value_4, Value4);
    newValues.put(Value_5, Value5);

    // Insert it into the database.
    return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}



/////////////////////////////////////////////////////////////////////
//  Private Helper Classes:
/////////////////////////////////////////////////////////////////////

/**
 * Private class which handles database creation and upgrading.
 * Used to handle low-level database access.
 */
private static class DatabaseHelper extends SQLiteOpenHelper
{
    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase _db) {
        _db.execSQL(DATABASE_CREATE_SQL);           
    }

    @Override
    public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading application's database from version " + oldVersion
                + " to " + newVersion + ", which will destroy all old data!");

        // Destroy old database:
        _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

        // Recreate new database:
        onCreate(_db);
    }
}
}

当我运行应用程序时,SimpleCursorAdapter 不会填充 ListView,但是不会引发任何错误。我该怎么做才能让我的数据出现在 ListView 中?

4

0 回答 0