博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
android开发使用SQLite之写日记
阅读量:6291 次
发布时间:2019-06-22

本文共 9865 字,大约阅读时间需要 32 分钟。

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

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

效果例如以下:

         

当LIstView中没有数据显示时,我们须要告诉用户没有数据.

方法有二:

1.

activity继承ListActivity,在布局文件里例如以下编写:

android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/android:list"/>
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<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);					}}

你可能感兴趣的文章
SDUT OJ 数据结构实验之链表五:单链表的拆分
查看>>
c语言学习之基础知识点介绍(四):算术运算符和逗号表达式
查看>>
c语言学习之基础知识点介绍(六):if和switch结构
查看>>
elasticsearch 的Merge
查看>>
网络编程
查看>>
浅析GDAL库C#版本支持中文路径问题
查看>>
快学Scala 第八课 (嵌套类)
查看>>
Linux文件和目录的属性及权限
查看>>
Wannafly挑战赛3
查看>>
解决Ubuntu14.04安装Chrome浏览器打不开的问题
查看>>
INSERT IGNORE 与INSERT INTO的区别
查看>>
JQuery Easy UI 简介
查看>>
【转帖】【面向代码】学习 Deep Learning(四) Stacked Auto-Encoders(SAE)
查看>>
垂直剧中
查看>>
C语言版推箱子
查看>>
BeanPostProcessor出现init方法无法被调用Invocation of init method failed
查看>>
WIN7 X64的运行命令窗口
查看>>
JS Promise API
查看>>
探究JS中的连等赋值问题
查看>>
113. Path Sum II
查看>>