listview与SQLite结合实现记事本功能
android记事本的demo在网上一搜一大堆,但是大神写的demo往往功能太多导致新手难以着手,很难啃得动;而一些新手写的demo又往往是东拼西凑,代码很多都是copy的别人的,直接放在项目里面用,也不知道代码有什么作用。往往代码特别丑,重复性的代码也比较多。
笔者近期学到此处,自己理解之后也还是打算写个demo供新手学习一下。代码说不上优雅,但在笔者看来已经尽力去让人容易理解了。(源码在文章结尾)
为了便于新手学习,在此也是罗列一下涉及的知识点:
1、sqlite的基本使用,增删查改
2、listview,adapeter的基本使用
3、activity生命周期
4、intent、bundle传递参数
5、alertdialog的基本使用
另外还有一些零碎知识点都可以百度到。
遇到的问题:
sqlite有个问题,就是主键不能够自动排序。比如说主键id为1 2 3 4,共4条记录。现在删除2 3,还剩下1 4记录,当再次插入时,id会变成5,而不是2.假设在初始4条记录的基础上,把这4条记录全都删掉,再次插入时,得到的id是5.
笔者在这点上也是花了比较久的时间,原本为了精简代码,想法是用listview中的arg2直接通过数据库记录的id进行操作,但是由于sqlite的这个问题,所以这种方法就有问题了。
最终,笔者采用的是内容搜索的方法,从listview的每个item中获取内容,然后到数据库中通过内容搜索该记录,最后对其进行操作。
效果:
mainactivity:
import android.app.activity; import android.app.alertdialog.builder; import android.content.dialoginterface; import android.content.intent; import android.database.cursor; import android.database.sqlite.sqlitedatabase; import android.os.bundle; import android.view.view; import android.view.view.onclicklistener; import android.widget.adapterview; import android.widget.adapterview.onitemclicklistener; import android.widget.adapterview.onitemlongclicklistener; import android.widget.button; import android.widget.listview; import android.widget.simpleadapter; import android.widget.textview; import java.util.arraylist; import java.util.hashmap; import java.util.list; import java.util.map; public class mainactivity extends activity implements onitemclicklistener, onitemlongclicklistener { private listview listview; private simpleadapter simple_adapter; private list<map<string, object>> datalist; private button addnote; private textview tv_content; private notedatebasehelper dbhelper; private sqlitedatabase db; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); initview(); } //在activity显示的时候更新listview @override protected void onstart() { super.onstart(); refreshnoteslist(); } private void initview() { tv_content = (textview) findviewbyid(r.id.tv_content); listview = (listview) findviewbyid(r.id.listview); datalist = new arraylist<map<string, object>>(); addnote = (button) findviewbyid(r.id.btn_editnote); dbhelper = new notedatebasehelper(this); db = dbhelper.getreadabledatabase(); listview.setonitemclicklistener(this); listview.setonitemlongclicklistener(this); addnote.setonclicklistener(new onclicklistener() { @override public void onclick(view arg0) { intent intent = new intent(mainactivity.this, noteedit.class); bundle bundle = new bundle(); bundle.putstring("info", ""); bundle.putint("enter_state", 0); intent.putextras(bundle); startactivity(intent); } }); } //刷新listview public void refreshnoteslist() { //如果datalist已经有的内容,全部删掉 //并且更新simp_adapter int size = datalist.size(); if (size > 0) { datalist.removeall(datalist); simple_adapter.notifydatasetchanged(); } //从数据库读取信息 cursor cursor = db.query("note", null, null, null, null, null, null); startmanagingcursor(cursor); while (cursor.movetonext()) { string name = cursor.getstring(cursor.getcolumnindex("content")); string date = cursor.getstring(cursor.getcolumnindex("date")); map<string, object> map = new hashmap<string, object>(); map.put("tv_content", name); map.put("tv_date", date); datalist.add(map); } simple_adapter = new simpleadapter(this, datalist, r.layout.item, new string[]{"tv_content", "tv_date"}, new int[]{ r.id.tv_content, r.id.tv_date}); listview.setadapter(simple_adapter); } // 点击listview中某一项的点击监听事件 @override public void onitemclick(adapterview<?> arg0, view arg1, int arg2, long arg3) { //获取listview中此个item中的内容 string content = listview.getitematposition(arg2) + ""; string content1 = content.substring(content.indexof("=") + 1, content.indexof(",")); intent myintent = new intent(mainactivity.this, noteedit.class); bundle bundle = new bundle(); bundle.putstring("info", content1); bundle.putint("enter_state", 1); myintent.putextras(bundle); startactivity(myintent); } // 点击listview中某一项长时间的点击事件 @override public boolean onitemlongclick(adapterview<?> arg0, view arg1, final int arg2, long arg3) { builder builder = new builder(this); builder.settitle("删除该日志"); builder.setmessage("确认删除吗?"); builder.setpositivebutton("确定", new dialoginterface.onclicklistener() { @override public void onclick(dialoginterface dialog, int which) { //获取listview中此个item中的内容 //删除该行后刷新listview的内容 string content = listview.getitematposition(arg2) + ""; string content1 = content.substring(content.indexof("=") + 1, content.indexof(",")); db.delete("note", "content = ?", new string[]{content1}); refreshnoteslist(); } }); builder.setnegativebutton("取消", new dialoginterface.onclicklistener() { @override public void onclick(dialoginterface dialog, int which) { } }); builder.create(); builder.show(); return true; }
notedatebasehelper:
import android.content.context; import android.database.sqlite.sqlitedatabase; import android.database.sqlite.sqliteopenhelper; public class notedatebasehelper extends sqliteopenhelper { public static final string createnote = "create table note (" + "id integer primary key autoincrement, " + "content text , " + "date text)"; public notedatebasehelper(context context) { super(context, "note", null, 1); } @override public void oncreate(sqlitedatabase db) { db.execsql(createnote); } @override public void onupgrade(sqlitedatabase arg0, int arg1, int arg2) { // todo auto-generated method stub } }
noteedit:
import android.app.activity; import android.content.contentvalues; import android.database.sqlite.sqlitedatabase; import android.os.bundle; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.edittext; import android.widget.textview; import android.widget.toast; import java.text.simpledateformat; import java.util.date; public class noteedit extends activity implements onclicklistener { private textview tv_date; private edittext et_content; private button btn_ok; private button btn_cancel; private notedatebasehelper dbhelper; public int enter_state = 0;//用来区分是新建一个note还是更改原来的note public string last_content;//用来获取edittext内容 @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.edit); initview(); } private void initview() { tv_date = (textview) findviewbyid(r.id.tv_date); et_content = (edittext) findviewbyid(r.id.et_content); btn_ok = (button) findviewbyid(r.id.btn_ok); btn_cancel = (button) findviewbyid(r.id.btn_cancel); dbhelper = new notedatebasehelper(this); //获取此时时刻时间 date date = new date(); simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm"); string datestring = sdf.format(date); tv_date.settext(datestring); //接收内容和id bundle mybundle = this.getintent().getextras(); last_content = mybundle.getstring("info"); enter_state = mybundle.getint("enter_state"); et_content.settext(last_content); btn_cancel.setonclicklistener(this); btn_ok.setonclicklistener(this); } @override public void onclick(view view) { switch (view.getid()) { case r.id.btn_ok: sqlitedatabase db = dbhelper.getreadabledatabase(); // 获取edittext内容 string content = et_content.gettext().tostring(); // 添加一个新的日志 if (enter_state == 0) { if (!content.equals("")) { //获取此时时刻时间 date date = new date(); simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm"); string datestring = sdf.format(date); //向数据库添加信息 contentvalues values = new contentvalues(); values.put("content", content); values.put("date", datestring); db.insert("note", null, values); finish(); } else { toast.maketext(noteedit.this, "请输入你的内容!", toast.length_short).show(); } } // 查看并修改一个已有的日志 else { contentvalues values = new contentvalues(); values.put("content", content); db.update("note", values, "content = ?", new string[]{last_content}); finish(); } break; case r.id.btn_cancel: finish(); break; } } }
activity_main:
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <textview android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="记事本" android:textstyle="bold" android:textsize="22sp" android:padding="15dp" android:background="#000" android:textcolor="#fff" /> <linearlayout android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1" > <listview android:id="@+id/listview" android:layout_margin="5dp" android:layout_width="match_parent" android:layout_height="wrap_content" > </listview> </linearlayout> <button android:id="@+id/btn_editnote" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="添加备忘录" android:padding="10dp" android:textsize="20sp" /> </linearlayout>
edit:
<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <linearlayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#000" android:orientation="vertical" android:padding="15dp"> <textview android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="编辑备忘录" android:textcolor="#fff" android:textsize="22sp" android:textstyle="bold" /> <textview android:id="@+id/tv_date" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="end" android:text="编辑时间" android:textcolor="#fff" /> </linearlayout> <linearlayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:padding="10dp" android:orientation="vertical"> <textview android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="内容编辑:" android:textcolor="#000" android:textsize="20sp" android:layout_margin="10dp" android:textstyle="bold" /> <edittext android:id="@+id/et_content" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:background="@drawable/edit_text_style" android:gravity="start" android:hint="此处记录备忘事件" android:textsize="20sp" /> <linearlayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <button android:id="@+id/btn_cancel" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="取消" /> <button android:id="@+id/btn_ok" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="保存" /> </linearlayout> </linearlayout> </linearlayout>
item:
<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp" android:orientation="vertical"> <textview android:id="@+id/tv_content" android:layout_width="match_parent" android:layout_height="wrap_content" android:singleline="true" android:textsize="20sp" android:textcolor="#000" android:text="large text" /> <textview android:id="@+id/tv_date" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="textview" /> </linearlayout>
最后附上源码:记事本
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
推荐阅读