Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android開發使用SQLite之寫日記

android開發使用SQLite之寫日記

編輯:關於Android編程

使用數據庫實現對數據的存儲。

下面上一個小例子,寫日記。

效果如下:

\ \\ \


當LIstView中沒有數據顯示時,我們需要告訴用戶沒有數據.<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+t723qNPQtv46PC9wPgo8cD4xLjwvcD4KPHA+YWN0aXZpdHm8zLPQTGlzdEFjdGl2aXR5o6zU2rK8vtbOxLz+1tDI58/CseDQtKO6PC9wPgo8cD48cHJlIGNsYXNzPQ=="brush:java;">
2.

		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;
	
	@Override
	protected 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);
		}
	
		
	}
	
	

	@Override
	public 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);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) { // onContextItemSelected
		AdapterContextMenuInfo 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
	 */
	
	@Override
	protected void onResume() {
		super.onResume();

		refreshList();
		

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	/**
	 * 通過菜單進入“日記添加頁面”
	 */
	@Override
	public 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;
	@Override
	protected 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);
		
	}

	@Override
	public 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 ;
	@Override
	protected 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());
			
			
		}
		
		
		
		
		
	}

	@Override
	public 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.dao

DiaryDao.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 diaries = new ArrayList();
		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.db

DBHelper.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;
	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		db.execSQL("create table diary(_id integer primary key autoincrement,title varchar(20),content varchar(1000),created)");
		
	}

	//用於數據庫的更新
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		
	}

}

cn.edu.bzu.diary.entity

Diary.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;
	}
	

	@Override
	public String toString() {
		return "Diary [title=" + title + ", content=" + content + ", datetime="
				+ datetime + "]";
	}
	

}

cn.edu.bzu.diary.tools

Tool.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);
		
		
	}

}

代碼下載地址











  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved