上一篇主要是学习布局界面,是对AddNewActivity.java的xml文件进行增加,那这次主要是要将增加联系人的内容保存到数据库中去,在这里主要是用到Android内置的一个轻量级的数据库sqlite.
1、需要一个实体类Entity javaBean。 包为test.contact.entity 类名为用户的信息,即User.java
package test.contact.entity;
public class User {
public int _id;
public int imageId;
public String name;
public String mobilePhone;
public String familyPhone;
public String position;
public String company;
public String address;
public String zipCode;
public String email;
public String otherContact;
public String remark;
public String officePhone;
}
2、在数据库需要一个DBHelper的类,这个类主要是SQLiteOpenHelper的子类,在这里完成表的创建以及其他操作
package test.contact.db;
import test.contact.entity.User;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
//将DBHelper构造成一个单例模式(1.写成私有 2.)
public final static String DB_NAME = "contact";
public final static int VERSION = 3;//数据库的版本
private static DBHelper instance = null;
private SQLiteDatabase db;//用这个SQLIiteDBHelper主要是为了初始化这个数据库
//单例模式
public static DBHelper getInstance(Context context){
if(instance==null){
instance = new DBHelper(context);
}
return instance;
}
private void openDatabase(){
if(db==null){
db = this.getWritableDatabase();
}
}
private DBHelper(Context context) {
super(context, DB_NAME,null, VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {//在这里把表建立起来,这个方法只执行一次,如果有表了,就不执行这个方法了
// TODO Auto-generated method stub
StringBuffer tableCreate = new StringBuffer();
tableCreate.append("create table user( _id integer primary key autoincrement,")
.append("name text,")
.append("mobilePhone text,")
.append("familyPhone text,")
.append("officePhone text,")
.append("address text,")
.append("position text, ")
.append("company text,")
.append("email text,")
.append("otherContact text ,")
.append("zipCode text,")
.append("remark text,")
.append("imageId int)");
db.execSQL(tableCreate.toString());
}
//如果数据库版本不一致才执行,一般做法是:清除数据库然后重新建表
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
String sql = "drop table if exists user";
db.execSQL(sql);
onCreate(db);
}
//保存,把user当作一个对象,将增加联系人的信息都存到这里来
public void save(User user){
openDatabase();//每次增加记录的时候,open一下
ContentValues value = new ContentValues();
value.put("name", user.name);
value.put("mobilePhone", user.mobilePhone);
value.put("familyPhone", user.familyPhone);
value.put("officePhone", user.officePhone);
value.put("address", user.address);
value.put("position", user.position);
value.put("company", user.company);
value.put("email", user.email);
value.put("otherContact", user.otherContact);
value.put("zipCode", user.zipCode);
value.put("remark", user.remark);
value.put("imageId", user.imageId);
db.insert("user", null, value);
}
}
3、如上中,需要getInstance(Context context),这里的上下文就是需要添加联系人这个类的上下文,以及这里有个保存的方法,需要调用增加联系人类的东西,即AddNewActivity.java,所以需要对AddNewActivity进行修改,(PS:为防止弄错,这里的AddNewActivity包含了上一篇中的该类代码,一些注释在类中有体现)
package test.contact;
import test.contact.db.DBHelper;
import test.contact.entity.User;//引入user的包
import test.contact.entity.User;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;
public class AddNewActivity extends Activity {
ImageButton btn_img;
AlertDialog imageChooseDialog;
Gallery gallery;
ImageSwitcher is;
int imagePosition;//在图片选择中确定按钮是提交的图片的id,如果默认的话,值为0
//增加联系人信息的这个界面里的那些编辑框
EditText et_name;
EditText et_mobliePhone;
EditText et_familyPhone;
EditText et_officePhone;
EditText et_position;
EditText et_company;
EditText et_address;
EditText et_zipCode;
EditText et_email;
EditText et_otherContact;
EditText et_remark;
Button btn_save;
Button btn_return;
private int[] images={
R.drawable.icon,
R.drawable.image1,R.drawable.image2,
R.drawable.image3,R.drawable.image4,
R.drawable.image5,R.drawable.image6,
R.drawable.image7,R.drawable.image8,
R.drawable.image9,R.drawable.image10};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addnew);
initWidget();//初始化这个界面里的EditText和两个Button
//响应"保存"按钮事件
btn_save = (Button)this.findViewById(R.id.btn_save);
btn_save.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name = et_name.getText().toString();
if(name.equals("")){
Toast.makeText(AddNewActivity.this, "姓名不能为空", Toast.LENGTH_LONG).show();
return;
}
String mobilePhone = et_mobliePhone.getText().toString();
String officePhone = et_officePhone.getText().toString();
String familyPhone = et_familyPhone.getText().toString();
String position = et_position.getText().toString();
String company = et_company.getText().toString();
String address = et_address.getText().toString();
String email = et_email.getText().toString();
String zipCode = et_zipCode.getText().toString();
String otherContact = et_otherContact.getText().toString();
String remark = et_remark.getText().toString();
//如果没有给Image赋图像,那么imageId默认为0,
//所以在上面的Image里的第一个是icon,作为默认的那个图片
int imageId = images[imagePosition];
//联系人
User user = new User();
user.address = address;
user.company = company;
user.email = email;
user.familyPhone = familyPhone;
user.imageId = imageId;
user.mobilePhone = mobilePhone;
user.otherContact = otherContact;
user.name = name;
user.officePhone = officePhone;
user.position = position;
user.remark = remark;
user.zipCode = zipCode;
//保存用户信息到数据库,执行后就到了DBHelper里的save方法了
DBHelper.getInstance(AddNewActivity.this).save(user);
}
});
//实现的主要是修改Image按钮里的东西
btn_img=(ImageButton)this.findViewById(R.id.btn_img);
btn_img.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
initImageChooseDialog(); //当点击选择图片(即名字旁边的图片按钮时的方法)
imageChooseDialog.show();
}
});
}
//写个方法将这个界面的编辑框和保存取消等控件都初始化
public void initWidget(){
et_name=(EditText)this.findViewById(R.id.et_name);
et_mobliePhone=(EditText)this.findViewById(R.id.et_mobilephone);
et_familyPhone=(EditText)this.findViewById(R.id.et_familyphone);
et_officePhone=(EditText)this.findViewById(R.id.et_officephone);
et_position=(EditText)this.findViewById(R.id.et_position);
et_company=(EditText)this.findViewById(R.id.et_company);
et_address=(EditText)this.findViewById(R.id.et_address);
et_zipCode=(EditText)this.findViewById(R.id.et_zipcode);
et_email=(EditText)this.findViewById(R.id.et_email);
et_otherContact=(EditText)this.findViewById(R.id.et_other);
et_remark=(EditText)this.findViewById(R.id.et_remark);
}
private void initImageChooseDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("请选择图像");
//添加选择和取消图片的按钮
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
btn_img.setImageResource(images[imagePosition]);//在选中一张图片后,获得这个图片的id,才能选中它了
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.imageswitch, null);
//1、Gallery的东西需要显示出来,
gallery = (Gallery) view.findViewById(R.id.img_gallery);
gallery.setAdapter(new ImageAdapter(this));
gallery.setSelection(images.length/2);//定位中中间的图片
//2、Switcher方面,选中图片
is=(ImageSwitcher) view.findViewById(R.id.image_switcher);
is.setFactory(new MyViewFactory(this));
//1.1 Gallery的响应事件
gallery.setOnItemSelectedListener(new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
imagePosition = position;
is.setImageResource(images[position]);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
builder.setView(view);
imageChooseDialog = builder.create();
}
//Gallery的Adapter,实现BaseAdapter内部类
class ImageAdapter extends BaseAdapter{
private Context context;
public ImageAdapter(Context context){
this.context=context;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return images.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView iv = new ImageView(context);
iv.setImageResource(images[position]);
iv.setAdjustViewBounds(true);//设置适应视图的大小
iv.setLayoutParams(new Gallery.LayoutParams(80,80));//设置其大小
//设置图片之间的间隔
iv.setPadding(15, 10, 15, 10);
return iv;
}
}
//Switcher的Factory,实现ViewFactory的内部类
class MyViewFactory implements ViewFactory{
private Context context;//需要的上下文
public MyViewFactory(Context context){
this.context=context;
}
@Override
public View makeView() {
// TODO Auto-generated method stub
ImageView iv = new ImageView(context);
iv.setLayoutParams(new ImageSwitcher.LayoutParams(90,90));
return iv;
}
}
}
4、启动ADT,对添加联系人的页面进行填写,然后单击保存按钮,而要查看我们所运行的增加联系人页面上填写的内容是否写入到了后台数据库sqlite的数据库名为contact ,表名为user的表中,则要进入Linux后台查看,具体的一些命令为:(先进入到我们安装的sdk的tool目录下(这里我安装的目录是f:\\Android\android-sdk-windows\tools
> f:
> cd Android\android-sdk-windows\tools
# adb shell ----------进入了Linux后台
# ls
# cd /data # ls
# cd data # ls
# cd test.contact # ls
# cd databases; # ls
# sqlite3 contact
# select * from user
获得的结果为: