Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android學習--------實現增刪改查數據庫操作以及實現類似微信好友對話管理操作

Android學習--------實現增刪改查數據庫操作以及實現類似微信好友對話管理操作

編輯:關於Android編程

最近的一個實驗用到東西挺多,特地總結一下。

要求功能:

1、第一個頁面添加歌曲名和歌手,跳到第二個頁面列表顯示所有記錄,使用sqlite數據庫

2、對於第二個頁面顯示的信息可以進行刪除和修改操作,並自動刷新

最後我做的效果:

\\

長按列表項彈出單個管理的菜單,像微信好友對話管理一樣。

刪除時可以直接刪除這一條並在列表中直接顯示,更新時彈出對話框更新內容提交後在列表中重新顯示。

\\

做此例遇到的困難:

1、菜單獲取上下文

2、獲取對話框中的內容<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+M6GittS7sL/ysLTFpcztvNO84Mz9ysK8/i0tLS0t16LS4rD8srvSqrW8tO2jumltcG9ydCBhbmRyb2lkLmNvbnRlbnQuRGlhbG9nSW50ZXJmYWNlLk9uQ2xpY2tMaXN0ZW5lcjs8L3A+CjxwPiA8L3A+CjxwPtb30qq0+sLryOfPwqO6PC9wPgo8cD612tK7uPbSs8Pmo7o8YnI+CjwvcD4KPHByZSBjbGFzcz0="brush:java;">package com.example.musiclist; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { SQLiteDatabase db; String music; String singer; Button add; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()+"/music.db3", null); add = (Button)findViewById(R.id.add); add.setOnClickListener(new OnClickListener(){ Cursor cursor = null; public void onClick(View sourse){ music = ((EditText)findViewById(R.id.music)).getText().toString(); singer = ((EditText)findViewById(R.id.singer)).getText().toString(); try{ insertData(db,music,singer); }catch(SQLiteException se){ //primary key autoincrement db.execSQL("create table musiclist(_id integer primary key autoincrement," +"music varchar(30) ," +"singer varchar(30))"); insertData(db,music,singer); }finally{ //cursor.close(); Intent intentSec = new Intent(MainActivity.this,SecondActivity.class); startActivity(intentSec); } } }); } private void insertData(SQLiteDatabase db,String name,String weibo){ //執行插入語句 db.execSQL("insert into musiclist values(null,?,?)",new String[]{music,singer}); } public void onDestroy(){ super.onDestroy(); if(db!=null&&db.isOpen()){ db.close(); } } @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; } }



    
    


第二個頁面:

package com.example.musiclist;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TableLayout;

public class SecondActivity extends Activity {
	SQLiteDatabase db;
	ListView show;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_second);
		show = (ListView)findViewById(R.id.show);
		db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()+"/music.db3", null);
		//顯示列表
		showlist();
		// 添加長按點擊彈出選擇菜單
		show.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
			public void onCreateContextMenu(ContextMenu menu, View v,
					ContextMenuInfo menuInfo) {
				menu.setHeaderTitle("選擇操作");
				menu.add(0, 0, 0, "更新該條");
				menu.add(0, 1, 0, "刪除該條");
			}
		});
	}
	//給菜單項添加事件
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		//info.id得到listview中選擇的條目綁定的id
		String id = String.valueOf(info.id);
		switch (item.getItemId()) {
		case 0:
			updateDialog(id);
			return true;
		case 1:
			//System.out.println("刪除"+info.id);
			deleteData(db,id);
			showlist();
			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}
	//更新對話框
	private void updateDialog(final String id){
		final TableLayout updatemsg = (TableLayout)getLayoutInflater().inflate(R.layout.updatemsg, null);
		new AlertDialog.Builder(this)
		.setTitle("更新該條信息")
		.setView(updatemsg)
		.setPositiveButton("更新",new OnClickListener(){
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				String musicN = ((EditText)updatemsg.findViewById(R.id.musicN)).getText().toString();
				String singerN = ((EditText)updatemsg.findViewById(R.id.singerN)).getText().toString();
				updateData(db,id,musicN,singerN);
				showlist();
			}
		})
		.setNegativeButton("取消", new OnClickListener(){
			public void onClick(DialogInterface dialog,int which){
			}
		})
		.create()
		.show();
	}
	private void updateData(SQLiteDatabase db,String id,String musicN,String singerN){
		db.execSQL("update musiclist set music='"+musicN+"',singer='"+singerN+"' where _id=?",new String[]{id});
	}
	//刪除列表項
	private void deleteData(SQLiteDatabase db,String id){
		db.execSQL("delete from musiclist where _id=?",new String[]{id});
	}
	//顯示列表項
	private void showlist(){
		Cursor cursor = null;
		try{
			cursor = db.rawQuery("select * from musiclist", null);
			inflateList(cursor);
		}catch(SQLiteException se){
			db.execSQL("create table musiclist(_id integer primary key autoincrement," 
					+"music varchar(30) ,"
					+"singer varchar(30))");
			//查詢
			cursor = db.rawQuery("select * from musiclist", null);
			inflateList(cursor);
		}finally{
			//cursor.close();
		}
	}
	private void inflateList(Cursor cursor){
		//填充SimpleCursorAdapter
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(SecondActivity.this,R.layout.line,cursor,
				new String[]{"_id","music","singer"},
				new int[]{R.id.idS,R.id.musicS,R.id.singerS},
				CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		show.setAdapter(adapter);
	}

	public void onDestroy(){
		super.onDestroy();
		if(db!=null&&db.isOpen()){
			db.close();
		}
	}
	@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;
	}
}



    
    

列表 line.xml:



     
    
     
    
    
    
    


對話框:updatemsg.xml



    
        
        
    
    
        
        
    



  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved