android学习小结4

    技术2024-07-08  77

    1 activity可以继承扩展 ListActivity 比如:class DummyNote extends ListActivity { private String[] note_array = {                  "gasolin",            "crota",            "louk",            "magicion"               };  ListAdapter adapter = new ArrayAdapter<String>(this,                    android.R.layout.simple_list_item_1,                    note_array);        setListAdapter(adapter);

    }

    2 使用sqlite  在新建立工程后,打开模拟器后,在sdk的tools下运行adb shellcd data/data/ls cd 工程名mkdir databasescd databasessqlite3 notes.db (建立了一个notes.db数据库)create talbe notes......;sqlite>.databases  (查看当前目录下的数据库列表)sqllite>.tables  (查看所有数据表)     .schema notes (查看指定表的结构)离开sqllite:  .exit

    3  CRUD的典型例子 public class NotesDbAdapter {  private static final String DATABASE_NAME = "notes.db";    private static final int DATABASE_VERSION = 1;

        private static final String DATABASE_TABLE = "notes";

        private static final String DATABASE_CREATE =    "create table notes("        +"_id INTEGER PRIMARY KEY,"        +"note TEXT,"        +"created INTEGER,"        +"modified INTEGER"    +");";

     private static class DatabaseHelper extends SQLiteOpenHelper {

      public DatabaseHelper(Context context) {   super(context, DATABASE_NAME, null, DATABASE_VERSION);   // TODO Auto-generated constructor stub  }

      @Override  public void onCreate(SQLiteDatabase db) {   // TODO Auto-generated method stub   db.execSQL(DATABASE_CREATE);  }

      @Override  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {   // TODO Auto-generated method stub   db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE);   onCreate(db);  }

        }     private Context mCtx = null;    private DatabaseHelper dbHelper ;    private SQLiteDatabase db;

        /** Constructor */    public NotesDbAdapter(Context ctx) {        this.mCtx = ctx;    }

        public NotesDbAdapter open () throws SQLException {        dbHelper = new DatabaseHelper(mCtx);        db = dbHelper.getWritableDatabase();        return this;    }

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

        //start query    public static final String KEY_ROWID = "_id";    public static final String KEY_NOTE = "note";    public static final String KEY_CREATED = "created";

        String[] strCols = new String[] {        KEY_ROWID,        KEY_NOTE,        KEY_CREATED    };

        /*    public Cursor getall() {        return db.rawQuery("SELECT * FROM notes", null);    }    */        /*    // get all entries    public Cursor getall() {        return db.query(DATABASE_TABLE, //Which table to Select             strCols,// Which columns to return             null, // WHERE clause             null, // WHERE arguments             null, // GROUP BY clause             null, // HAVING clause             null //Order-by clause             );    }    */        // get all entries    public Cursor getall() {        return db.query(DATABASE_TABLE,            new String[] {KEY_ROWID, KEY_NOTE, KEY_CREATED},            null, null, null, null, null);    }

        // add an entry    public long create(String Note) {        Date now = new Date();        ContentValues args = new ContentValues();        args.put(KEY_NOTE, Note);        args.put(KEY_CREATED, now.getTime());

            return db.insert(DATABASE_TABLE, null, args);    }

        //remove an entry    public boolean delete(long rowId) {        return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;    }        //query single entry    public Cursor get(long rowId) throws SQLException {        Cursor mCursor = db.query(true,                DATABASE_TABLE,                new String[] {KEY_ROWID, KEY_NOTE, KEY_CREATED},                KEY_ROWID + "=" + rowId,                null, null, null, null, null);        if (mCursor != null) {            mCursor.moveToFirst();        }        return mCursor;    }

        //update    public boolean update(long rowId, String note) {        ContentValues args = new ContentValues();        args.put(KEY_NOTE, note);

            return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;    }

    }

    主程序调用:    private NotesDbAdapter mDbHelper;    private Cursor mNotesCursor;        private void setAdapter() {     mDbHelper = new NotesDbAdapter(this);        mDbHelper.open();        fillData();

    }   private void fillData() {        mNotesCursor = mDbHelper.getall();        startManagingCursor(mNotesCursor);

            String[] from = new String[]{"note"};        int[] to = new int[]{android.R.id.text1};

            // Now create a simple cursor adapter        SimpleCursorAdapter adapter =                    new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, mNotesCursor, from, to);        setListAdapter(adapter);    }    新增记录:   public long create(String Note) {        Date now = new Date();        ContentValues args = new ContentValues();        args.put(KEY_NOTE, Note);       。。。。。。

            return db.insert(DATABASE_TABLE, null, args);    }删除记录:   public boolean delete(long rowId) {        return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;    }  mDbHelper.delete(getListView().getSelectedItemId());//这里用getListView().getSelectedItemId()获得选定删除哪一条记录

    查询记录://query single entry    public Cursor get(long rowId) throws SQLException {        Cursor mCursor = db.query(true,                DATABASE_TABLE,                new String[] {KEY_ROWID, KEY_NOTE, KEY_CREATED},                KEY_ROWID + "=" + rowId,                null, null, null, null, null);        if (mCursor != null) {            mCursor.moveToFirst();        }        return mCursor;    }更新记录: //update    public boolean update(long rowId, String note) {        ContentValues args = new ContentValues();        args.put(KEY_NOTE, note);

            return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;    }4 activity中的相关,比如选了A中的记录,然后打开B来编辑,B编辑完后,再返回A。   首先在B中,接收BUNDLE: private void showViews(Bundle savedInstanceState) {        //mRowId = savedInstanceState != null ? savedInstanceState.getLong(NotesDbAdapter.KEY_ROWID) : null;        if (mRowId == null) {            Bundle extras = getIntent().getExtras();            mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID) : null;        }

     //把编辑的数据拿出来  if (mRowId != null) {            Cursor note = mDbHelper.get(mRowId);            startManagingCursor(note);

                field_note.setText(note.getString(                    note.getColumnIndexOrThrow(NotesDbAdapter.KEY_NOTE)                ));        }  当编辑成功提交后,     public void onClick(View view) {                mDbHelper.update(mRowId, field_note.getText().toString());                setResult(RESULT_OK);                finish();   这里的setResult,表示这个activity成功,返回

    在调用方中,如果是一个LISTVIEW的列表的话,点某一个列  protected void onListItemClick(ListView l, View v, int position, long id) {     super.onListItemClick(l, v, position, id);     Intent intent = new Intent(this, NoteEdit.class);     intent.putExtra(NotesDbAdapter.KEY_ROWID, id);     startActivityForResult(intent, ACTIVITY_EDIT); }   这里的startActivityForResult表示的是要调用另外一个activity,并且要求结果返回同时:  protected void onActivityResult(int requestCode, int resultCode,                                 Intent intent) {     super.onActivityResult(requestCode, resultCode, intent);     fillData(); }

    5 长按菜单    A 在oncreate函数中,注册     registerForContextMenu(getListView());//说明点listview时会使用长按菜单   B public void onCreateContextMenu(ContextMenu menu, View v,   ContextMenuInfo menuInfo) {  // TODO Auto-generated method stub  menu.add(0, MENU_DELETE, 0,  "删除记事");        menu.setHeaderTitle("要怎么处理这个项目");  super.onCreateContextMenu(menu, v, menuInfo); }

     

    本文来自博客,转载请标明出处:http://blog.csdn.net/jackyrongvip/archive/2010/02/09/5303823.aspx

    最新回复(0)