android_SQLite運用_生活筆記demo

>>>實現功能


主要是對對SQLite編輯和修改

分析代碼結構,需要NotePadList類用於展示筆記,NotePadAdd類用於實現筆記的添加,需要NotePadDetil實現修改筆記,需要NotePadProvieder實現對數據庫操作。
-------------------------------------------------------
第一步,編寫NotePadList
xml部分
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".NotePadList" >

    <ListView
        android:id="@+id/id_listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>


java部分
public class NotePadList extends Activity {
	private NotePadProvider nProvider = new NotePadProvider(this);
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		setNoteListView();
	}
	SimpleCursorAdapter adapter;
	private void setNoteListView() {
		c = qurydata();
		//lsitviw
		ListView lsv = (ListView) findViewById(R.id.id_listview);
		//simpleadapter
		adapter=new SimpleCursorAdapter(this,
				R.layout.notepadlist,
				c, new String[]{"content","created"},
			    new int[]{R.id.lsit_textview,R.id.lsit_textview2},
			    CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		lsv.setAdapter(adapter);
		lsv.setOnItemClickListener(new OnItemClickListener() {            //長按實現頁面跳轉,到notepaddetil

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			c.moveToPosition(position);//獲取點擊位置的Cursor
			String content = c.getString(c.getColumnIndex("content"));//查詢取值
				Intent intent =  new Intent(NotePadList.this, NotepadDetil.class);
				intent.putExtra("contentKey",content);//通過intent傳遞相應的值
				intent.putExtra("idKey",String.valueOf(position+1));
				
				startActivityForResult(intent, 100);//傳遞請求碼以便執行刷新
			}
		});
	}
	Cursor c;/**查詢*/
	private Cursor qurydata() {
		String sql="select * from notetab";
		c =nProvider.query(sql, null);
		return c;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		
		return true;
	}
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {//點擊添加按鈕菜單,跳轉添加界面
    	if (item.getItemId() == R.id.noteAddId) {
			startActivityForResult(new Intent(this, NotePadAdd.class),
					100);//請求碼
		}
    	return super.onOptionsItemSelected(item);
    }
/**刷新*/
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode==100&&resultCode==200) {
			c = qurydata();<span style="font-family: Arial, Helvetica, sans-serif;">//再次獲取</span>

			adapter.changeCursor(c);
		}
	}
}
menu-xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/noteAddId"
        android:orderInCategory="100"
        android:showAsAction="always"
        android:title="添加"
        android:icon="@android:drawable/ic_menu_add"/>

</menu>
------------------------------------------------------------------
第二步,書寫notePadProvider類,實現對數據庫的操作
java代碼
public class NotePadProvider {
private DBHelper dbHelper;
	public NotePadProvider(Context context) {
		dbHelper=new DBHelper(context,
		"notepad.db", null, 1);
	}
	/**寫入數據*/
	public long insert(String table,ContentValues values){
		SQLiteDatabase sdb=dbHelper.getWritableDatabase();//獲取數據庫的寫入功能
		long id=sdb.insert(table, null, values);
		sdb.close();
		return id;
	}
	/**更新*/
	public long updata(String table, ContentValues values, String whereClause, String[] whereArgs){
		SQLiteDatabase sdb = dbHelper.getWritableDatabase();
		long id = sdb.update(table, values, whereClause, whereArgs);
		return id;
	}
	/**查詢*/
	public Cursor query(String sql,String whereArgs[]){
		SQLiteDatabase sdb=
		dbHelper.getReadableDatabase();<span style="font-family: Arial, Helvetica, sans-serif;">//獲取數據庫的讀入功能</span>

		return sdb.rawQuery(sql, whereArgs);
	}
	/**操作SQLite的一個工具類*/
	class DBHelper extends SQLiteOpenHelper{
		public DBHelper(Context context, String name, CursorFactory factory,
				int version) {
			super(context, name, factory, version);
		}
		/**數據庫創建時執行,且只執行一次*/
		@Override
		public void onCreate(SQLiteDatabase db) {
		   String sql=
		   "create table if not exists notetab(" +
		   "_id integer primary key autoincrement," +
		   "content text not null," +
		   "created text not null)";
		   
		   db.execSQL(sql);
		   
		   Log.i("TAG", "table create ok!");
		}
		/**數據庫版本升級時執行*/
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.i("TAG", "onUpgrade");
		}
	}
}


-------------------------------------------------------------------
第三步:編寫NotePadAdd類,實現增加筆記功能
public class NotePadAdd extends Activity {
private EditText et;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_note_pad);
		et = (EditText) findViewById(R.id.editText1);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.note_pad, menu);
		
		return true;
	}
	@SuppressLint("SimpleDateFormat")
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		NotePadProvider nProvider = new NotePadProvider(this);
		if (item.getItemId() == R.id.save) {
			//獲得頁面數據
			String content = et.getText().toString();
			//對數據進行非空驗證
			if (TextUtils.isEmpty(content)) {
				et.setError("null");
				return true;
			}
			//將數據寫到數據庫
			ContentValues values = new ContentValues();
			values.put("content", content);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			values.put("created", sdf.format(new Date()));
			long id = nProvider.insert("notetab", values);
			if (id==-1) {
				Toast.makeText(this, "insert error", 0).show();
				return true;
			}
			//關閉當前頁面
			setResult(200);//跳轉回notepadlist主界面的時候,自動刷新主界面
			finish();
		}
		
		return super.onOptionsItemSelected(item);
	}
}
xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".NotePadAdd" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginLeft="22dp"
        android:layout_marginTop="31dp"
        android:ems="10" 
        android:hint="輸入">

        <requestFocus />
    </EditText>

</RelativeLayout>
menu
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/save"
        android:orderInCategory="100"
        android:showAsAction="always"
        android:title="保存"
        android:icon="@android:drawable/ic_menu_save"></item>
</menu>
---------------------------------------------------------------------
第四步,編寫NotePadDetil,實現修改
java

public class NotepadDetil extends Activity {
private EditText et;
private MenuItem et_save;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_notepad_detil);
		initView();
		et.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				et.setFocusableInTouchMode(true);
				et_save.setVisible(true);
				
			}
		});
	}

	private void initView() {
		et = (EditText) findViewById(R.id.id_editText);
		
		Intent intent = getIntent();
		String contentNew = intent.getStringExtra("contentKey");
		String contentOld = et.getText().toString();
		if (TextUtils.isEmpty(contentOld)) {//非空判斷
			et.setText(contentNew);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.notepad_detil, menu);
		et_save = menu.findItem(R.id.edt_save);
		et_save.setVisible(false);
		
		return true;
	}
	@Override
		public boolean onOptionsItemSelected(MenuItem item) {
			if (item.getItemId() == R.id.edt_save) {
				//獲取當前頁面的數據
				String newcontent = et.getText().toString();
				NotePadProvider nProvider=new NotePadProvider(this);
				  ContentValues values=new ContentValues();
				  values.put("content", newcontent);
				  
				  Intent intent=getIntent();
				  String id=intent.getStringExtra("idKey");
				  nProvider.updata("notetab",
				  values, "_id=?", new String[]{id});
				  //4.關閉頁面
				  setResult(200);//跳轉後刷新
				  finish();
			}
			return super.onOptionsItemSelected(item);
		}

}
menu
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/edt_save"
        android:orderInCategory="100"
        android:showAsAction="always"
        android:title="保存"
        
        android:icon="@android:drawable/ic_menu_save"/>

</menu>
xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".NotepadDetil" >

    <EditText
        android:layout_width="wrap_content"
        android:id="@+id/id_editText"
        android:layout_height="wrap_content"
        android:focusable="false"
        android:background="@null"/>

</RelativeLayout>







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