android學習小結4

來源:互聯網
上載者:User

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 shell
cd data/data/
ls
 cd 工程名
mkdir databases
cd databases
sqlite3 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);
 }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.