Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android項目之通訊錄數據庫

android項目之通訊錄數據庫

編輯:關於Android編程

Android通訊錄的制作有很多種方式,網上大部分也都有了,但是用數據庫制作通訊錄的卻少之又少,這裡我就制作一個簡單的app供大家學習

先看一下效果圖,在下面有提供項目源碼
\

首先打開app會有一個全屏的閃屏效果

//全屏顯示welcome畫面

requestWindowFeature(Window.FEATURE_NO_TITLE);

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,

WindowManager.LayoutParams.FLAG_FULLSCREEN);

setContentView(R.layout.start);

//延遲一秒後執行run方法中的頁面跳轉

new Handler().postDelayed(new Runnable() {

 

@Override

public void run() {

Intent intent = newIntent(TongXunLuActivity.this, List.class);

startActivity(intent);

TongXunLuActivity.this.finish();

}

}, 1000);

接下來就是對數據庫的管理了

StudentDAO.Java

 


package com.abc.sqlite; import java.util.ArrayList; import java.util.List; import com.abc.entity.Student; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class StudentDAO { /** * 對數據庫的增刪改查 */ private DBOpenHelper helper;//SQLiteOpenHelper實例對象 private SQLiteDatabase db;//數據庫實例對象 public StudentDAO(Context context) { helper = new DBOpenHelper(context); } public void add(Student student) { // 增刪改查 db = helper.getWritableDatabase();// 鏈接數據庫 db.execSQL("insert into tb_student values(?,?,?,?)", new String[] { student.getId(), student.getName(), student.getSpeciality(), student.getQq() }); db.close(); } /** * // 添加數據 * * @param student */ public void addContentValues(Student student) { db = helper.getWritableDatabase(); ContentValues cv = new ContentValues(); //ContentValues 和HashTable類似都是一種存儲的機制 但是兩者最大的區別就在於,contenvalues只能存儲基本類型的數據, //像string,int之類的,不能存儲對象這種東西,而HashTable卻可以存儲對象。 cv.put("Id", student.getId()); cv.put("Name", student.getName()); cv.put("Speciality", student.getSpeciality()); cv.put("Qq", student.getQq()); db.insert("tb_student", null, cv); db.close(); } /** * 1、查詢所有student數據rawQuery方法 * * @return */ public List quereyTable() { List listStudents = new ArrayList(); db = helper.getReadableDatabase(); // 顯示視圖 Cursor cursor = db.rawQuery("select * from tb_student", null); // 挨個遍歷 while (cursor.moveToNext()) { Student student = new Student(); student.setId(cursor.getString(0)); student.setName(cursor.getString(1)); student.setSpeciality(cursor.getString(2)); student.setQq(cursor.getString(3)); // 添加到集合 listStudents.add(student); db.close(); } return listStudents; } /** * // 查詢單個student數據 * * @param student * @return */ public Student quereyStudentRaw(Student student) { // Student student1 = new Student(); db = helper.getReadableDatabase(); Cursor cursor = db.rawQuery("select * from tb_student where Id=?", new String[] { student.getId() });// 用數組填充占位符 //要創建一個Cursor(游標),必須執行一個查詢,通過SQL使用rawQuery()方法或是更精心的query()方法,而不能使用execSQL(String sql)方法。 while (cursor.moveToNext()) { student.setId(cursor.getString(cursor.getColumnIndex("id")));// 返回指定列的名稱,如果不存在返回-1 // student.setId(cursor.getString(0)); student.setName(cursor.getString(1)); student.setSpeciality(cursor.getString(2)); student.setQq(cursor.getString(3)); db.close(); } return student; } /** * 2、查詢所有student數據query方法 * * @return */ public List queryAll(Student student) { List sList = new ArrayList(); db = helper.getWritableDatabase(); Cursor cursor = db.query("tb_student", null, null, null, null, null, null); while (cursor.moveToNext()) { Student student1 = new Student(cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3)); sList.add(student1); } return sList; } /** * 2、查詢單個student數據query方法 * * @return */ public Student quereyStuden(Student student) { db = helper.getReadableDatabase(); Cursor cursor=db.query("tb_student", null, "id=?", new String[] { student.getId() }, null, null, null); //Cursor cursor = db.query("select * from tb_student where Id=?", // new String[] { student.getId() }); //要創建一個Cursor(游標),必須執行一個查詢,通過SQL使用rawQuery()方法或是更精心的query()方法,而不能使用execSQL(String sql)方法。 while (cursor.moveToNext()) { student.setId(cursor.getString(cursor.getColumnIndex("id")));// 返回指定列的名稱,如果不存在返回-1 // student.setId(cursor.getString(0)); student.setName(cursor.getString(1)); student.setSpeciality(cursor.getString(2)); student.setQq(cursor.getString(3)); db.close(); } return student; } public int getCount() { // TODO 自動生成的方法存根 return 0; } /* * 修改數據庫方法一 */ public void upDate(Student student) { db = helper.getWritableDatabase(); db.execSQL( "update tb_student set Name=?,Speciality=?,Qq=? where Id=?", new String[] { student.getName(), student.getSpeciality(),student.getQq(),student.getId()}); db.close(); } /*public void delete(String id) { // TODO 自動生成的方法存根 db = helper.getWritableDatabase(); Student student = new Student(); db.delete("tb_student", "Id=?", new String[]{student.getId()}); db.close(); }*/ public int delete(String id) { // TODO 自動生成的方法存根 db = helper.getWritableDatabase(); Student student = new Student(); int count=db.delete("tb_student", "Id=?", new String[]{student.getId()}); db.close(); return count; } } 

 



 

接下來是對每個student數據內容的解析現實

Service.java

 

package com.abc.sqlite;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;
import android.util.Xml;

import com.abc.entity.Student;

public class Service {
	/**
	 * 對每個student數據內容的解析現實
	 */
	
	
	private Context context;

	public Service(Context context) {
		super();
		this.context = context;
	}

	public List parserXml(String filesName) throws IOException,
			XmlPullParserException {  
		List students=new ArrayList();
		Student student=null;//初始化一個對象
		AssetManager aManage = context.getAssets();
		InputStream is = null;//1、獲取解析文本	
		XmlPullParser parser =null;
		
		is=aManage.open(filesName);
		parser=	Xml.newPullParser();// 2、創建一個解析器對象
		parser.setInput(is, "utf-8");// 設置輸入字節流與編碼格式
		
		int event = parser.getEventType();// 3、取得事件類型,用於開始解析時的判斷
		while (event!=XmlPullParser.END_DOCUMENT) {
			 switch (event) {
		/*	 case XmlPullParser.START_DOCUMENT:							
				 break;*/
			 case XmlPullParser.START_TAG:	
				 if ("student".equalsIgnoreCase(parser.getName())) {//判斷節點值是否相同
					student=new Student();
					student.setId(parser.getAttributeValue(0));//獲取student的第一個屬性 **********
					Log.v("ID", "55555555555555555555555");
					break;//while循環結束
				}
				 if (student!=null) {//判斷student節點下的文本節點是否為空
					 if ("name".equalsIgnoreCase(parser.getName())) {
						 student.setName(parser.nextText());//nextText獲取具體的數據內容*************
						 Log.v("name", "&&&&&&&&&&&&&&&&&&&&&&&&");
					 }
					 if ("speciality".equalsIgnoreCase(parser.getName())) {
						 student.setSpeciality(parser.nextText());//nextText獲取具體的數據內容*************
						 Log.v("speciality","????????????????????");
					 }
					 if ("qq".equalsIgnoreCase(parser.getName())) {
						student.setQq(parser.nextText());//nextText獲取具體的數據內容*************
						Log.v("qq", "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
					}
					
				}
				 break;
			case XmlPullParser.END_TAG:	
				if ("student".equalsIgnoreCase(parser.getName())) {
					students.add(student);//講解析的一個student對象添加到集合中去
					student=null;//student置空
					Log.v("END_TAG", "END_TAG");
				}
				break;

			default:
				break;
			}
			 event = parser.next();//獲取下一個事件類型
		}
		if(is !=null){
			is.close();
		}
		return students;
	}
}

 

接下來是數據內容位置的填充,並對增刪改查進行監聽事件,這裡的刪除出現了一個問題不能夠實現,如有高見還請分享一下

StudentDetile.java

 

package com.abc.entity;

import com.abc.sqlite.StudentDAO;
import com.abc.tong.List;
import com.abc.tong.R;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

public class StudentDetile extends Activity implements OnClickListener {

	private EditText nameText, Idn;
	private EditText qqText;
	private EditText specialityText;

	private Button saveButton;
	private Button backButton;
	private Button cancelButton;
	private Button callButton;

	private java.util.List sListQuery1=null;
	StudentDAO studentDAO = new StudentDAO(this);// 2 創建對象 /////對數據庫的增刪改查
	
	String qq;
	String id;
	StudentDAO studentDao = new StudentDAO(StudentDetile.this);

	private Context context;
	private java.util.List students;
	Student student;

	public StudentDetile() {
		super();
	}

	public StudentDetile(Context context, java.util.List students) {
		super();
		this.context = context;
		this.students = students;
	}

	protected void onCreate(Bundle savedInstanceState) {
		// TODO 自動生成的方法存根
		super.onCreate(savedInstanceState);

		setContentView(R.layout.student_detile);
		Intent intent = getIntent();
		Bundle bundle = intent.getBundleExtra("bundle");

		String name = bundle.getString("strName");
		qq = bundle.getString("strQq");
		String speciality = bundle.getString("strSpeciality");
		 id = bundle.getString("strId");

		nameText = (EditText) findViewById(R.id.EditName);
		qqText = (EditText) findViewById(R.id.EditQq);
		specialityText = (EditText) findViewById(R.id.EditSpeciality);
		Idn = (EditText) findViewById(R.id.EditId);

		saveButton = (Button) findViewById(R.id.update);
		cancelButton = (Button) findViewById(R.id.delete);
		backButton = (Button) findViewById(R.id.call);
		callButton = (Button) findViewById(R.id.back);

		saveButton.setOnClickListener(this);
		cancelButton.setOnClickListener(this);
		backButton.setOnClickListener(this);
		callButton.setOnClickListener(this);

/*		Idn.setText("學   號:" + id);
		nameText.setText("姓 名:" + name);
		qqText.setText("Q Q:" + qq);
		specialityText.setText("宿 捨:" + speciality);*/
		Idn.setText(id);
		nameText.setText( name);
		qqText.setText(qq);
		specialityText.setText(speciality);

	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(StudentDetile.this, List.class);
		switch (v.getId()) {
		case R.id.update:
			android.content.DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					student = new Student(id, nameText.getText()
							.toString().trim(), qqText.getText().toString()
							.trim(), specialityText.getText().toString().trim());
					updateStudent(student);
					/*student.setName(student.getName()+1);
					updateStudent(student);*/
					Intent intent = new Intent(StudentDetile.this, List.class);
					startActivity(intent);
				}
			};
			// 創建對話框
			Builder builder = new Builder(this);
			builder.setTitle("確定要修改嗎?");// 設置標題
			builder.setPositiveButton("確定", listener);// 設置確定按鈕的文本以及監聽
			builder.setNegativeButton("取消", null);
			builder.show();// 顯示對話框
			break;
		case R.id.delete:
			 
			// 刪除數據之前首先彈出一個對話框
			android.content.DialogInterface.OnClickListener listener1 = new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO 自動生成的方法存根
					sListQuery1=studentDAO.quereyTable();
					student = new Student(Idn.getText().toString(), nameText.getText()
							.toString().trim(), qqText.getText().toString()
							.trim(), specialityText.getText().toString().trim());
					//sListQuery1.remove(student);//從集合中刪除
					studentDao.delete(student.getId());// 從數據庫中刪除 no
					
					Intent intent = new Intent(StudentDetile.this, List.class);
					startActivity(intent);
				}
			};
			// 創建對話框
			Builder builder1 = new Builder(this);
			builder1.setTitle("確定要刪除嗎?");// 設置標題
			builder1.setPositiveButton("確定", listener1);// 設置確定按鈕的文本以及監聽
			builder1.setNegativeButton("取消", null);
			builder1.show();// 顯示對話框
			break;
		case R.id.back:

			startActivity(intent);
			break;
		case R.id.call:
			Intent it = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + qq));
			startActivity(it);
			//StudentDetile.this.startActivity(it);
		default:
			break;
		}
	}

	private void updateStudent(Student student) {
		// TODO 自動生成的方法存根

		studentDao.upDate(student);
	}
}

 

接下來自定義一個適配器,進行界面數據的綁定,並在list方法中實現,這裡對list進行了一個長按點擊事件——打電話

CustomAdapter.java

 

package com.abc.adapter;

import java.util.ArrayList;
import java.util.List;

import com.abc.entity.Student;
import com.abc.sqlite.Service;
import com.abc.tong.R;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;


public class CustomAdapter extends BaseAdapter {
	
	private List sList;
    /*private  int icons[]={R.drawable.ic_launcher,R.drawable.ic_launcher,
    		R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,
    		R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher};*/
    private Context context;
    


	public CustomAdapter(List sList, Context context) {
		super();
		this.sList = sList;
		this.context = context;
	}

	//sList=service.parserXml("text.xml");
	@Override
	public int getCount() {
		// 返回ListView的Item條目 的總數
		return sList.size();// 返回集合

		// return strStudent.length;//返回數組
	}

	@Override
	public Object getItem(int position) {
		// 返回ListView的Item條目 代表的對象
		return sList.get(position);// 返回集合

		//return strStudent[position];//返回數組
	}

	@Override
	public long getItemId(int position) {
		// 返回ListView的Item條目 的id
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// 將自定義的list_item.xml文件找出來並轉換成View對象
		//Android ListView中每顯示出一條item的時候,都會自動的調用BaseAdapter.getView(int position, View convertView, ViewGroup parent)方法。

		/*
		 * View.inflate(context, resource, root);
		 * 
		 * resource: 布局文件的id,比如R.layout.layout_menu_item
		 * root:這是一個可選參數,resource布局文件中layout_
		 * *參數設置的參照物就是這個root,也就是說inflate方法會根據這個root的大小,
		 * 將resource布局文件中layout_*參數轉換成一個LayoutParam對象
		 */
		// LayoutInflater inflate = LayoutInflater.from(context);
		View view=View.inflate(context, R.layout.list_item,null );
	//特別注意此時context不能寫this,或CustomAdapter。this,因為此時的上下文是List.java
		TextView nameText=(TextView) view.findViewById(R.id.text_name);
		TextView qqText=(TextView) view.findViewById(R.id.text_qq);
		TextView specialityText=(TextView) view.findViewById(R.id.text_speciality);
		 
		nameText.setText((CharSequence)sList.get(position).getName());
		qqText.setText((CharSequence)sList.get(position).getQq());
		specialityText.setText((CharSequence)sList.get(position).getSpeciality());
		
		ImageView imageView=(ImageView) view.findViewById(R.id.imageView);
		//imageView.setBackgroundResource(icons[position]);//數組過多就不寫了,但是它默認會配上圖片
		
		return view;
	}

}

 

List.java

 

package com.abc.tong;

import java.io.IOException;

import org.xmlpull.v1.XmlPullParserException;

import com.abc.adapter.CustomAdapter;
import com.abc.entity.Student;
import com.abc.entity.StudentDetile;
import com.abc.sqlite.Service;
import com.abc.sqlite.StudentDAO;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

public class List extends Activity implements OnItemLongClickListener {
	private Student student = null;
	private java.util.List sList = null;
	private java.util.List sListQuery = null;
	private ListView listv;

	private EditText nameText, Idn;
	private EditText qqText;
	private EditText specialityText;
	String strQq;

	@Override
	// 當退出app時彈出對話框
	// 但是這個退出程序,可能並未完全退出,如果你進入管理APP界面,會看到程序仍在運行。如果想完全退出程序,需要進行進一步處理。
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 如果是返回鍵,直接返回到桌面
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			showExitGameAlert();
		}

		return super.onKeyDown(keyCode, event);
	}

	private void showExitGameAlert() {

		Builder a = new AlertDialog.Builder(List.this);
		a.setMessage("確定退出通訊錄嗎")
				.setPositiveButton("確定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						System.exit(0);
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				}).show();
	}

	protected void onCreate(Bundle savedInstanceState) {
		// TODO 自動生成的方法存根
		super.onCreate(savedInstanceState);

		setContentView(R.layout.list_contacts);

		nameText = (EditText) findViewById(R.id.EditName);
		qqText = (EditText) findViewById(R.id.EditQq);
		specialityText = (EditText) findViewById(R.id.EditSpeciality);
		Idn = (EditText) findViewById(R.id.EditId);

		listv = (ListView) findViewById(R.id.list);
		Service service = new Service(this);// 1 創建對象 /////對每個student數據內容的解析現實

		try {
			sList = service.parserXml("text.xml");
		} catch (IOException e) {
			// TODO 自動生成的 catch 塊
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO 自動生成的 catch 塊
			e.printStackTrace();
		}
		String[] strStudent = new String[sList.size()];// 初始化數組大小
		StudentDAO studentDAO = new StudentDAO(this);// 2 創建對象 /////對數據庫的增刪改查
		// huoqu yianjia xianshi
		int i = 0;// 定義一個開始標識
		for (Student student : sList) {
			strStudent[i] = student.getId() + student.getName()
					+ student.getQq() + student.getSpeciality();

			studentDAO.addContentValues(student);// 將每一個student添加到studentDAO
			// studentDAO.addContentValues(sList.get(i));//
			// 將每一個student添加到studentDAO
			i++;// ***************************

		}
		// sListQuery=studentDAO.queryAll(student);//從數據庫查詢出所有數據,此方法有bug
		sListQuery = studentDAO.quereyTable();
		CustomAdapter adapter = new CustomAdapter(sListQuery,
				getApplicationContext());

		/*
		 * ArrayAdapter adapter = new ArrayAdapter(this,
		 * android.R.layout.simple_expandable_list_item_1, strStudent);
		 */// 數據集合
		listv.setAdapter(adapter);

		listv.setOnItemLongClickListener(this);

		listv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView parent, View view,
					int position, long id) {
				// TODO 自動生成的方法存根
				// String strinfo=(String) ((TextView)view).getText();

				/*
				 * String strId=strinfo.substring(0,strinfo.indexOf("888888"));
				 * String
				 * strName=strinfo.substring(1,strinfo.indexOf("8888888"));
				 * String
				 * strSpeciality=strinfo.substring(2,strinfo.indexOf("6666666"
				 * )); String
				 * strQq=strinfo.substring(3,strinfo.indexOf("6666666"));
				 */
				// 獲取點擊內容
				/*
				 * String strId=Idn.getText().toString().trim(); String
				 * strName=nameText.getText().toString().trim(); String
				 * strSpeciality=specialityText.getText().toString().trim();
				 * String strQq=qqText.getText().toString().trim();
				 * 
				 * Idn.setText("姓 名:"+strId); nameText.setText("姓 名:"+strName);
				 * qqText.setText("Q Q:"+strQq);
				 * specialityText.setText("宿 捨:"+strSpeciality);
				 */

				String strId = sListQuery.get(position).getId();
				String strName = sListQuery.get(position).getName();
				String strSpeciality = sListQuery.get(position).getSpeciality();
				strQq = sListQuery.get(position).getQq();

				Intent intent = new Intent(List.this, StudentDetile.class);

				// Student stu_intent=new Student();

				Bundle bundle = new Bundle();

				bundle.putString("strId", strId);
				bundle.putString("strQq", strQq);
				bundle.putString("strName", strName);
				bundle.putString("strSpeciality", strSpeciality);

				intent.putExtra("bundle", bundle);
				startActivity(intent);
			}
		});
	}

	public boolean onItemLongClick(AdapterView arg0, View view,
			int position, long arg3) {
		// TODO 自動生成的方法存根
		strQq = sListQuery.get(position).getQq();
		Log.e("mxmxmxmmxmxmxmxmm", view.toString() + "position=" + position);
		Intent it = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + strQq));
		// Intent it = new Intent(List.this, StudentDetile.class);
		List.this.startActivity(it);

		return true;// 為了區分點擊事件和長按事件,長按事件裡的return false; 改為true就好了
	}

}
部分簡單代碼與布局文件在這裡就不貼出來了,水滴石穿。

 

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