原文链接:https://www.f2er.com/sqlite/201622.html效果图:当程序运行后,首先进入日记列表,显示如图:
点击menu后,显示如图:
具体实现方法:
实体类:
package cn.bzu.mydiary.model; public class Diary { private int id; private String title; private String content; private String pubdate; public int getId() { return id; } public void setId(int 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 getPubdate() { return pubdate; } public void setPubdate(String pubdate) { this.pubdate = pubdate; } public Diary(String title,String content,String pubdate) { super(); this.title = title; this.content = content; this.pubdate = pubdate; } public Diary(int id,String title,String pubdate) { super(); this.id = id; this.title = title; this.content = content; this.pubdate = pubdate; } public Diary(int id,String content) { super(); this.id = id; this.title = title; this.content = content; } }创建数据库的类(数据库保存在DDMS/data/data/cn.bzu.mydiary/database/diary.db)
package cn.bzu.mydiary.db; import android.content.Context; import android.database.sqlite.sqliteDatabase; import android.database.sqlite.sqliteOpenHelper; public class DBHelper extends sqliteOpenHelper{ private static String DATABASE_NAME="diary.db"; private static int DATABASE_VERSION=1; public DBHelper(Context context) { super(context,DATABASE_NAME,null,DATABASE_VERSION); } @Override public void onCreate(sqliteDatabase db) { db.execsql("create table tb_diary(_id integer primary key autoincrement,title verchar(20),content verchar(1000),pubdate)"); } @Override public void onUpgrade(sqliteDatabase db,int oldVersion,int newVersion) { } }数据库操作类
package cn.bzu.mydiary.service; import java.util.ArrayList; import java.util.List; import java.util.Map; import android.content.Context; import android.database.Cursor; import android.database.sqlite.sqliteDatabase; import cn.bzu.mydiary.db.DBHelper; import cn.bzu.mydiary.model.Diary; public class DiaryService { private DBHelper dbHelper; sqliteDatabase sqliteDatabase = null; public DiaryService(Context context) { dbHelper = new DBHelper(context); } /** * 保存日记 * * @param diary */ public void save(Diary diary) { sqliteDatabase = dbHelper.getWritableDatabase(); String sql = "insert into tb_diary(title,content,pubdate) values (?,?,?)"; sqliteDatabase.execsql( sql,new String[] { diary.getTitle(),diary.getContent(),diary.getPubdate() }); sqliteDatabase.close(); } // 查询日志 public List<Diary> getAllDiary() { Diary diary = null; List<Diary> diaryList = new ArrayList<Diary>(); sqliteDatabase = dbHelper.getReadableDatabase(); // 得到游标,最多只有一条数据 Cursor cursor = sqliteDatabase.rawQuery("select * from tb_diary",null); while (cursor.moveToNext()) { int id = cursor.getInt(0); String title = cursor.getString(cursor.getColumnIndex("title")); String content = cursor.getString(cursor.getColumnIndex("content")); String pubdate = cursor.getString(cursor.getColumnIndex("pubdate")); diary = new Diary(id,title,pubdate); diaryList.add(diary); } cursor.close(); sqliteDatabase.close(); return diaryList; } /** * 根据id删除日记 * * @param id * 日记的id号 */ public void delete(Integer id) { sqliteDatabase = dbHelper.getReadableDatabase(); sqliteDatabase.execsql("delete from tb_diary where _id=?",new Object[] { id }); sqliteDatabase.close(); } /** * 更新日记 * * @param diary */ public void update(Diary diary) { sqliteDatabase = dbHelper.getReadableDatabase(); sqliteDatabase.execsql( "update tb_diary set title=?,content=?,pubdate=? where _id=?",new Object[] { diary.getTitle(),diary.getPubdate(),diary.getId() }); sqliteDatabase.close(); } // //获取记录总数 // public long count(){ // long count=0; // sqliteDatabase sqliteDatabase=dbHelper.getReadableDatabase(); // Cursor cursor=sqliteDatabase.rawQuery("select count(*) from tb_diary",// null); // cursor.moveToFirst(); // count=cursor.getLong(0); // return count; // } }相应的布局文件:activity_add_diary.xml
<?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:background="@drawable/back" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/title" /> <EditText android:id="@+id/title" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/content" /> <EditText android:id="@+id/content" android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="textMultiLine" android:lines="6" /> <Button android:id="@+id/save" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/save" /> </LinearLayout>activity_diary.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:background="@drawable/back" android:layout_height="fill_parent" > <ListView android:id="@+id/diary" android:layout_width="fill_parent" android:layout_height="wrap_content" > </ListView> <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" > <Button android:id="@+id/add" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/add" android:visibility="invisible" /> <Button android:id="@+id/delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/delete" android:visibility="invisible" /> </RelativeLayout> </RelativeLayout>list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="left" /> <TextView android:id="@+id/pubdate" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="right" /> </LinearLayout>DiaryActivity.java
package cn.bzu.mydiary; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import cn.bzu.mydiary.model.Diary; import cn.bzu.mydiary.service.DiaryService; import android.os.Bundle; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.ListView; import android.widget.SimpleAdapter; public class DiaryActivity extends Activity { private List<Map<String,?>> diary; private ListView diaryList; private Button add,delete; DiaryService diaryService; AlertDialog deleteDiaryAlert; SimpleAdapter simpleAdapter; int id; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_diary); onRestart(); } @Override protected void onRestart() { super.onRestart(); diaryList = (ListView) this.findViewById(R.id.diary); add = (Button) this.findViewById(R.id.add); delete = (Button) this.findViewById(R.id.delete); diary = getDiary(); simpleAdapter = new SimpleAdapter(this,diary,R.layout.list_item,new String[] { "title","pubdate" },new int[] { R.id.title,R.id.pubdate }); diaryList.setAdapter(simpleAdapter); //获取删除时需要的id diaryList.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0,View arg1,int position,long arg3) { id = (Integer) diary.get(position).get("id"); } }); //长时间按该日志,可以跳转至修改页面 diaryList.setOnItemLongClickListener(new OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> arg0,long arg3) { id = (Integer) diary.get(position).get("id"); String title = (String) diary.get(position).get("title"); String content = (String) diary.get(position).get("content"); Diary d = new Diary(id,content); Intent intent = new Intent(); intent.setClass(DiaryActivity.this,AddDiaryActivity.class); Bundle bundle = new Bundle(); bundle.putInt("id",id); bundle.putString("title",title); bundle.putString("content",content); intent.putExtra("diary",bundle); startActivity(intent); return false; } }); } private List<Map<String,?>> getDiary() { List<Map<String,?>> data = new ArrayList<Map<String,?>>(); Map<String,Object> item = null; diaryService = new DiaryService(DiaryActivity.this); List<Diary> list = diaryService.getAllDiary(); for (int i = 0; i < list.size(); i++) { Diary d = list.get(i); item = new HashMap<String,Object>(); item.put("id",d.getId());// ID item.put("title",d.getTitle());// 标题 item.put("content",d.getContent()); item.put("pubdate",d.getPubdate());// 出版日期 data.add(item); } return data; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); // 创建菜单,并设置图表 menu.add(0,R.id.add,"编辑新日志").setIcon( android.R.drawable.ic_input_add); menu.add(0,R.id.delete,1,"删除该日志").setIcon( android.R.drawable.ic_input_delete); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.add: Intent intent = new Intent(); intent.setClass(DiaryActivity.this,AddDiaryActivity.class); startActivity(intent); break; case R.id.delete: deleteDiaryDialog(); deleteDiaryAlert.show(); break; } return super.onOptionsItemSelected(item); } // 删除日志 private void deleteDiaryDialog() { AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); alertDialog.setTitle("请确定是否删除日记"); alertDialog.setPositiveButton("确定",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { // System.out.print("id:"+id); diaryService.delete(id); onRestart(); } }); alertDialog.setNegativeButton("取消",int which) { dialog.cancel(); } }); deleteDiaryAlert = alertDialog.create(); } }AddDiaryActivity.java
package cn.bzu.mydiary; import java.text.SimpleDateFormat; import java.util.Date; import cn.bzu.mydiary.model.Diary; import cn.bzu.mydiary.service.DiaryService; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.graphics.Shader.TileMode; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.support.v4.app.NavUtils; public class AddDiaryActivity extends Activity { private EditText titleText; private EditText contentText; private Button save; int id; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_diary); titleText=(EditText) this.findViewById(R.id.title); contentText=(EditText) this.findViewById(R.id.content); save=(Button) this.findViewById(R.id.save); final Bundle bundle = this.getIntent().getBundleExtra("diary"); if(bundle==null){ save.setOnClickListener(new OnClickListener() { public void onClick(View v) { String title=titleText.getText().toString(); String content=contentText.getText().toString(); DiaryService diaryService=new DiaryService(AddDiaryActivity.this); Diary diary=new Diary(title,fomate()); diaryService.save(diary); Intent intent=new Intent(); intent.setClass(AddDiaryActivity.this,DiaryActivity.class); startActivity(intent); } }); }else{ titleText.setText(bundle.getString("title")); contentText.setText(bundle.getString("content")); id =bundle.getInt("id"); save.setOnClickListener(new OnClickListener() { public void onClick(View v) { String title=titleText.getText().toString(); String content=contentText.getText().toString(); DiaryService diaryService=new DiaryService(AddDiaryActivity.this); Diary diary=new Diary(id,fomate()); diaryService.update(diary); Intent intent=new Intent(); intent.setClass(AddDiaryActivity.this,DiaryActivity.class); startActivity(intent); } }); } } public String fomate(){ SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy年MM月dd日 hh时:mm分:ss秒"); return simpleDateFormat.format(new Date()); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_add_diary,menu); return true; } }
可以先建测试类测试一下,确认无误后,再运行,若要测试勿忘在AndroidManifest.xml中配置哦
package cn.bzu.mydiary; import java.text.SimpleDateFormat; import java.util.Date; import cn.bzu.mydiary.model.Diary; import cn.bzu.mydiary.service.DiaryService; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.graphics.Shader.TileMode; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.support.v4.app.NavUtils; public class AddDiaryActivity extends Activity { private EditText titleText; private EditText contentText; private Button save; int id; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_diary); titleText=(EditText) this.findViewById(R.id.title); contentText=(EditText) this.findViewById(R.id.content); save=(Button) this.findViewById(R.id.save); final Bundle bundle = this.getIntent().getBundleExtra("diary"); if(bundle==null){ save.setOnClickListener(new OnClickListener() { public void onClick(View v) { String title=titleText.getText().toString(); String content=contentText.getText().toString(); DiaryService diaryService=new DiaryService(AddDiaryActivity.this); Diary diary=new Diary(title,menu); return true; } }
package cn.bzu.mydiary; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import cn.bzu.mydiary.model.Diary; import cn.bzu.mydiary.service.DiaryService; import android.os.Bundle; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.ListView; import android.widget.SimpleAdapter; public class DiaryActivity extends Activity { private List<Map<String,int which) { dialog.cancel(); } }); deleteDiaryAlert = alertDialog.create(); } }
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="left" /> <TextView android:id="@+id/pubdate" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="right" /> </LinearLayout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:background="@drawable/back" android:layout_height="fill_parent" > <ListView android:id="@+id/diary" android:layout_width="fill_parent" android:layout_height="wrap_content" > </ListView> <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" > <Button android:id="@+id/add" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/add" android:visibility="invisible" /> <Button android:id="@+id/delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/delete" android:visibility="invisible" /> </RelativeLayout> </RelativeLayout>
<?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:background="@drawable/back" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/title" /> <EditText android:id="@+id/title" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/content" /> <EditText android:id="@+id/content" android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="textMultiLine" android:lines="6" /> <Button android:id="@+id/save" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/save" /> </LinearLayout>
package cn.bzu.mydiary.service; import java.util.ArrayList; import java.util.List; import java.util.Map; import android.content.Context; import android.database.Cursor; import android.database.sqlite.sqliteDatabase; import cn.bzu.mydiary.db.DBHelper; import cn.bzu.mydiary.model.Diary; public class DiaryService { private DBHelper dbHelper; sqliteDatabase sqliteDatabase = null; public DiaryService(Context context) { dbHelper = new DBHelper(context); } /** * 保存日记 * * @param diary */ public void save(Diary diary) { sqliteDatabase = dbHelper.getWritableDatabase(); String sql = "insert into tb_diary(title,// null); // cursor.moveToFirst(); // count=cursor.getLong(0); // return count; // } }
package cn.bzu.mydiary.db; import android.content.Context; import android.database.sqlite.sqliteDatabase; import android.database.sqlite.sqliteOpenHelper; public class DBHelper extends sqliteOpenHelper{ private static String DATABASE_NAME="diary.db"; private static int DATABASE_VERSION=1; public DBHelper(Context context) { super(context,int newVersion) { } }