您的位置:首页 > 移动开发 > Android开发

Android SQLite存储——个人日记本开发(二):添加、删除功能的实现

2012-11-14 11:26 886 查看
继续上一篇,个人日记本开发。通过上一篇,日记本的数据库部分已经完成,现在就来实现添加、删除功能:



一:在String中定义:

<resources>

    <string name="app_name">MyDiary01</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_add">添加一篇新日记</string>
      <string name="menu_delete">删除一篇日记</string>
      <string name="label_title">标题</string>
       <string name="label_content">内容</string>
        <string name="save">保存日记</string>
    <string name="title_activity_diary">DiaryActivity</string>

</resources>


二:在menu中的activity_diary.xml中布局菜单:

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_add"
        android:title="@string/menu_add"
        android:icon="@android:drawable/ic_menu_add"//引入添加图标
        android:orderInCategory="100" />
      <item android:id="@+id/menu_delete"
        android:title="@string/menu_delete"
        android:icon="@android:drawable/ic_menu_delete"//引入删除图标
        android:orderInCategory="100" />
</menu>

三:(1)布局activity_diary.xml文件,显示日记内容页面:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/star"
    android:orientation="vertical" >

    <ListView
        android:id="@id/android:list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

//当日记内容为空时:    <TextView
        android:id="@id/android:empty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="你好懒啊,还没开始写日记呢" />
</LinearLayout>

(2)item.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:orientation="horizontal" >

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="right"
        android:textSize="12sp" />

</LinearLayout>



(3)edit.xml:添加日记页面布局

<?xml version="1.0" encoding="utf-8"?>
<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_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/label_title" />

    <EditText
        android:id="@+id/title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/label_content" />

    <EditText
        android:id="@+id/content"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:layout_weight="1" />

    <Button
        android:id="@+id/confirm"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="diaryAdd"//点击事件
        android:text="@string/save" />

</LinearLayout>


四 完善DiaryService内容,增加添加、删除功能:

public class DiaryService {
	private DBHelper dbHelper;
    private SQLiteDatabase sqLiteDatabase;
	public DiaryService(Context context) {
		dbHelper = new DBHelper(context);
	}

	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() });	
	}

	public Cursor getAllDiaries(){
		sqLiteDatabase=dbHelper.getReadableDatabase();
		Cursor cursor=sqLiteDatabase.rawQuery("select * from tb_diary", null);
		return cursor;
	}//代替listview实现列表显示功能
	
	public void delete(Integer id){
		sqLiteDatabase=dbHelper.getWritableDatabase();
		sqLiteDatabase.delete("tb_diary", "_id=?", new String[]{id.toString()});
	}
}


五 完善DiaryTest文件实现添加、删除功能:

public class DiaryTest extends AndroidTestCase {
     public void testOnCreate(){
    	 DBHelper dbHelper=new DBHelper(getContext());
    	 dbHelper.getWritableDatabase();
     }
     
     public void testSave(){
    	 DiaryService diaryService=new DiaryService(getContext());
    	 Diary diary1=new Diary("今天天气不错", "正在学习Sqlite", formate(new Date()));
    	 Diary diary2=new Diary("今天天气阴", "心情很好", formate(new Date()));
    	 diaryService.save(diary1);
    	 diaryService.save(diary2);
     }
     
     public String formate(Date date){
    	 SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy年MM月dd日");
    	 return simpleDateFormat.format(date);
     }
     
     public void testDelete(){
    	 DiaryService diaryService=new DiaryService(getContext());
    	 diaryService.delete(1);
     }
}


基于以上,添加tools包,工具类 DateFormatTools,方便使用:

public class DateFormatTools {
	public static String format(Date date){
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy年MM月dd日");
		return simpleDateFormat.format(date);
	}

}


六 完成处理文件(1)DiaryActivity:

public class DiaryActivity extends ListActivity {
	private int idChoosed;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_diary);
		refreshlist();
		getListView().setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> listview, View view,
					int position, long id) {
				System.out.println("id="+id);
				idChoosed=(int) id;
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
		});

	}

	private void refreshlist() {
		DiaryService diaryService = new DiaryService(this);
		Cursor cursor = diaryService.getAllDiaries();
		//startManagingCursor(cursor);
		SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(this,
				R.layout.item, cursor, new String[] { "title", "pubdate" },
				new int[] { R.id.title, R.id.date });
		setListAdapter(simpleCursorAdapter);
	}//实现快速刷新

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_diary, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case R.id.menu_add:
			Toast.makeText(this, "add",Toast.LENGTH_LONG).show();
			Intent intent=new Intent(this,DiaryAdd.class);
			//startActivity(intent);
			startActivityForResult(intent, 1);
			break;
		case R.id.menu_delete:
			AlertDialog.Builder aBuilder=new AlertDialog.Builder(this);
			aBuilder.setTitle("你确定要删除吗?");
			aBuilder.setPositiveButton("确定", new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					DiaryService diaryService=new DiaryService(DiaryActivity.this);
					diaryService.delete(idChoosed);
					refreshlist();
				}
			});
			aBuilder.setNegativeButton("取消", new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					
				}
			});
			aBuilder.show();			
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (resultCode) {
		case RESULT_OK:
			refreshlist();
			break;

		default:
			break;
		}
	}
}



(2)DiaryAdd,添加页面:

public class DiaryAdd extends Activity {
	private EditText titleText;
	private EditText contentText;
	private Button saveButton;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.edit);
		
		titleText=(EditText) this.findViewById(R.id.title);
		contentText=(EditText) this.findViewById(R.id.content);
		saveButton=(Button) this.findViewById(R.id.confirm);
	    
		
	}
	
	public  void diaryAdd(View view){
		String title=titleText.getText().toString();
		String content=contentText.getText().toString();
		Diary diary=new Diary(title, content, DateFormatTools.format(new Date()));
		DiaryService diaryService=new DiaryService(this);
		diaryService.save(diary);
		Toast.makeText(this, "保存成功", Toast.LENGTH_LONG).show();
		setResult(RESULT_OK);
		finish();
	}

}


页面显示:

(1)如果日记本里没有内容:



(2)添加日记:



(3)日记保存成功:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐