首页 > 代码库 > android开发使用SQLite之写日记

android开发使用SQLite之写日记

使用数据库实现对数据的存储。

以下上一个小样例,写日记。

效果例如以下:

技术分享     技术分享技术分享    技术分享


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

}

代码下载地址











android开发使用SQLite之写日记