標籤:版本 raw android super this androi menuitem method oncreate
使用資料庫實現對資料的儲存。
以下上一個小範例,寫日記。
效果例如以下:
當LIstView中沒有資料顯示時,我們須要告訴使用者沒有資料.
方法有二:
1.
activity繼承ListActivity,在布局檔案裡例如以下編寫:
<TextView android:id="@id/android:empty" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="你好懶啊。還沒開始寫日記呢" /> <ListView <span style="white-space:pre"></span> android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/android:list"/>
2.
<span style="white-space:pre"></span>if(adapter.isEmpty()&&textView==null){textView = new TextView(MainActivity.this);textView.setText("主人非常懶,什麼也沒留下");textView.setVisibility(View.GONE); ((ViewGroup) listView.getParent()).addView(textView); listView.setEmptyView(textView);}else{listView.setAdapter(simpleCursorAdapter);}
資料庫的使用(安卓本身內建SQLite,假設想使用其它的資料庫,那就得使用Web Server):
繼承SQLiteOpenHelper。
public DBHelper(Context context) //資料庫的名字,資料庫的版本號碼public void onCreate(SQLiteDatabase db)////建立資料庫public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)//更新資料庫
詳細代碼例如以下:
cn.edu.bzu.diary.activity
MainActivity.java
public class MainActivity extends Activity {ListView listView;Cursor diaries;//遊標TextView textView = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);listView = (ListView) findViewById(R.id.listview);refreshList();this.registerForContextMenu(listView);}/** * 重新整理Adapter */public void refreshList(){DiaryDao diaryDao = new DiaryDao(this);diaries = diaryDao.getAllDairies();SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(MainActivity.this, R.layout.item, diaries, new String[] { "title","created" }, new int[] { R.id.title, R.id.created });if(simpleCursorAdapter.isEmpty()&&textView==null){textView = new TextView(MainActivity.this);textView.setText("主人非常懶,什麼也沒留下");textView.setVisibility(View.GONE); ((ViewGroup) listView.getParent()).addView(textView); listView.setEmptyView(textView);}else{listView.setAdapter(simpleCursorAdapter);}}@Overridepublic void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {menu.setHeaderTitle("操作");menu.add(0, 1, Menu.NONE, "編輯");menu.add(0, 2, Menu.NONE, "刪除");super.onCreateContextMenu(menu, v, menuInfo);}@Overridepublic boolean onContextItemSelected(MenuItem item) { // onContextItemSelectedAdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();switch (item.getItemId()) {case 1:Intent intent = new Intent();Bundle bundle = new Bundle();bundle.putInt("id", (int)menuInfo.id);intent.putExtras(bundle);intent.setClass(MainActivity.this, DiaryEditAcitivity.class);startActivity(intent);break;case 2:DiaryDao dao = new DiaryDao(MainActivity.this);dao.delete((int) menuInfo.id);//menuInfo.id與資料庫的ID一致refreshList();break;}return super.onContextItemSelected(item);}/** * 在退出日記加入中。利用生命週期重新整理Adapter */@Overrideprotected void onResume() {super.onResume();refreshList();}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.main, menu);return true;}/** * 通過菜單進入“日記加入頁面” */@Overridepublic boolean onOptionsItemSelected(MenuItem item) {switch (item.getItemId()) {case R.id.save:Intent intent = new Intent();intent.setClass(MainActivity.this, DiaryAddAcitivity.class);startActivity(intent);break;}return super.onOptionsItemSelected(item);}}
DiaryAddAcitivity.java
public class DiaryAddAcitivity extends Activity {DiaryDao diaryDao = new DiaryDao(DiaryAddAcitivity.this);Button button;EditText editText,editText2;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.diaryadd_acitivity);editText = (EditText) findViewById(R.id.et_diaryadd);//標題editText2 = (EditText) findViewById(R.id.et02_diaryadd);//內容button = (Button) findViewById(R.id.but);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.diary_add_acitivity, menu);return true;}public void click(View view){String title = editText.getText().toString();String content = editText2.getText().toString();Diary diary = new Diary(title, content, Tool.dateChange(new Date()));DiaryDao diaryDao = new DiaryDao(this);diaryDao.save(diary);finish();}}
DiaryEditAcitivity.java
public class DiaryEditAcitivity extends Activity {DiaryDao diaryDao = new DiaryDao(DiaryEditAcitivity.this);Button button;EditText editText,editText2;int id ;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.diaryadd_acitivity);editText = (EditText) findViewById(R.id.et_diaryadd);//標題editText2 = (EditText) findViewById(R.id.et02_diaryadd);//內容button = (Button) findViewById(R.id.but);Bundle bundle = this.getIntent().getExtras();if(bundle!=null){id = bundle.getInt("id");Diary diary = diaryDao.getDiaryById(id);editText.setText(diary.getTitle());editText2.setText(diary.getContent());}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.diary_add_acitivity, menu);return true;}public void click(View view){String title = editText.getText().toString();String content = editText2.getText().toString();Diary diary = new Diary(title, content, Tool.dateChange(new Date()));diary.setId(id);DiaryDao diaryDao = new DiaryDao(this);diaryDao.update(diary);finish();}}
cn.edu.bzu.diary.daoDiaryDao.java
public class DiaryDao {private DBHelper dbHelper;private SQLiteDatabase sqLiteDatabase;public DiaryDao(Context context) {dbHelper = new DBHelper(context);}/** * 加入日記 * @param diary */public void save(Diary diary) {String sql = "insert into diary(title,content,created) values(?,?,?)";sqLiteDatabase = dbHelper.getWritableDatabase();sqLiteDatabase.execSQL(sql,new String[] { diary.getTitle(), diary.getContent(),diary.getDatetime() });}/** * 依據id刪除日記 * * @param id * 日記的id號 */public void delete(Integer id) {sqLiteDatabase = dbHelper.getWritableDatabase();// 得到的是同一個資料庫執行個體sqLiteDatabase.execSQL("delete from diary where _id=?
",new Object[] { id });}/** * 更新日記 * * @param diary */public void update(Diary diary) {sqLiteDatabase = dbHelper.getWritableDatabase();// 得到的是同一個資料庫執行個體sqLiteDatabase.execSQL("update diary set title=?,content=?,created=? where _id=?",new Object[] { diary.getTitle(), diary.getContent(),diary.getDatetime(), diary.getId() });}/** * 返回一個遊標。也能夠使用凝視部分。返回一個List集合(使用SimpleAdapter),在這裡使用遊標,主要是由於 * AdapterContextMenuInfo中的ID是和資料庫中一致的 * @return cursor */public Cursor getAllDairies() {//Diary diary = null;//List<Diary> diaries = new ArrayList<Diary>();sqLiteDatabase = dbHelper.getReadableDatabase();Cursor cursor = sqLiteDatabase.rawQuery("select * from diary ", null);/* * while(cursor.moveToNext()){ String title = * cursor.getString(cursor.getColumnIndex("title")); String content = * cursor.getString(cursor.getColumnIndex("content")); String created = * cursor.getString(cursor.getColumnIndex("created")); diary = new * Diary(title, content, created); diaries.add(diary); } */return cursor;}/** * 擷取記錄總數 */public long count() {long count = 0;sqLiteDatabase = dbHelper.getReadableDatabase();Cursor cursor = sqLiteDatabase.rawQuery("select count(*) from diary ",null);cursor.moveToFirst();count = cursor.getLong(0);return count;}public Diary getDiaryById(int id) {sqLiteDatabase = dbHelper.getWritableDatabase();Diary diary = null;Cursor cursor = sqLiteDatabase.rawQuery("select * from diary where _id= ?", new String[] { id + "" });if (cursor.moveToFirst()) {String title = cursor.getString(cursor.getColumnIndex("title"));String content = cursor.getString(cursor.getColumnIndex("content"));String created = cursor.getString(cursor.getColumnIndex("created"));diary = new Diary(title, content, created);}return diary;}}
cn.edu.bzu.diary.dbDBHelper.java
public class DBHelper extends SQLiteOpenHelper{public static final String DATABASE_NAME="diary.db";public static final int VERSION = 1; //資料庫的名字。資料庫的版本號碼public DBHelper(Context context) {super(context, DATABASE_NAME, null, VERSION);// TODO Auto-generated constructor stub}//建立資料庫,欄位:id(主鍵),title,content,created。@Overridepublic void onCreate(SQLiteDatabase db) {// TODO Auto-generated method stubdb.execSQL("create table diary(_id integer primary key autoincrement,title varchar(20),content varchar(1000),created)");}//用於資料庫的更新@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {// TODO Auto-generated method stub}}
cn.edu.bzu.diary.entityDiary.java
public class Diary {private Integer id;private String title;private String content;private String datetime;public Diary(){}public Diary(String title,String content,String datetime){this.title = title;this.content = content;this.datetime = datetime;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}public String getDatetime() {return datetime;}public void setDatetime(String datetime) {this.datetime = datetime;}@Overridepublic String toString() {return "Diary [title=" + title + ", content=" + content + ", datetime="+ datetime + "]";}}
cn.edu.bzu.diary.toolsTool.java
public class Tool {/** * 時間顯示樣式 * @param date * @return */public static String dateChange(Date date){SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 hh時:mm分:ss秒");return simpleDateFormat.format(date);}}
代碼
android開發使用SQLite之寫日記