通过两个属性订购SQLite

时间:2014-11-04 18:37:39

标签: android sqlite

我为我想要存储在应用中的事件设置了一个普通的SQLite数据库。每个对象都具有以下属性:

private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_GENDER = "gender";
private static final String KEY_CATEGORY = "category";
private static final String KEY_DAY = "day";
private static final String KEY_MONTH = "month";
private static final String KEY_YEAR = "year";

如何按日和月份订购此数据库?我的目标是用这个填充ListView,因此我需要按日期订购正确的订单(不是年份,只有日期和月份)。

1 个答案:

答案 0 :(得分:0)

MyDatabaseHelper.java

public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="dbname";
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_GENDER = "gender";
public static final String KEY_CATEGORY = "category";
public static final String KEY_DAY = "day";
public static final String KEY_MONTH = "month";
public static final String KEY_YEAR = "year";


public DatabaseDomeny(Context context) {
    super(context, DATABASE_NAME2, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL("CREATE TABLE mytable (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, " +
            "gender TEXT, category TEXT, day TEXT, month TEXT, year TEXT);");



}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    android.util.Log.w("mytable", "Upgrading database, which will destroy all old data");
    db.execSQL("DROP TABLE IF EXISTS mytable");
    onCreate(db);
}


}

MyActivity.java

public class MyActivity extends ListActivity {

private SQLiteDatabase db=null;
private Cursor constantsCursor=null;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

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


    list_it();

    ListView lv = getListView();


    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {


        }
    });

}


private void list_it() {
    constantsCursor=db.rawQuery("SELECT * FROM mytable WHERE _id > 0 ORDER BY day, month ",
            null);

    ListAdapter adapter=new SimpleAdapter(this,
            R.layout.mylistxml, constantsCursor,
            new String[] {"name", "gender", "category", "day", "month", "year"},
            new int[] {R.id.name, R.id.gender, R.id.category, R.id.day, R.id.month, R.id.year});

    setListAdapter(adapter);
}




@Override
public void onDestroy() {
    super.onDestroy();

    constantsCursor.close();
    db.close();
}

}