Android SQLite存儲——個人日記本開發(二):添加、刪除功能的實現

繼續上一篇,個人日記本開發。通過上一篇,日記本的數據庫部分已經完成,現在就來實現添加、刪除功能:

一:在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)日記保存成功:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章