1. 程式人生 > >安卓學習之SQLite+ListView完成一個通訊錄

安卓學習之SQLite+ListView完成一個通訊錄

activity_main.xml  含有ListView佈局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.sqlite.MainActivity">

    <ListView
        android:id="@+id/user_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="50dp" />

    <LinearLayout
        android:id="@+id/bottom"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">

        <Button
            android:id="@+id/addUser"
            android:text="新增聯絡人"
            android:textSize="18dp"
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
        <Button
            android:id="@+id/searchUser"
            android:text="查詢聯絡人"
            android:textSize="18dp"
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>

</RelativeLayout>
user_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/user_img"
        android:layout_marginLeft="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/user_name"
        android:textSize="18dp"
        android:layout_marginLeft="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/user_img"/>

    <TextView
        android:id="@+id/telnumber"
        android:layout_marginTop="15dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/user_name"
        android:layout_alignLeft="@+id/user_name"
        android:layout_alignStart="@+id/user_name"/>

</RelativeLayout>
MainActivity.java Main活動,顯示聯絡人ListView,各種點選事件操作
public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private MyDatabaseHelper dbHelper;
    private List<User> UserList = new ArrayList<>();
    private Button addUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        addUser = (Button) findViewById(R.id.addUser);
        addUser.setOnClickListener(this);

        dbHelper = new MyDatabaseHelper(this,"User.db",null,1);

        //初始化資料
        initUser();
        UserAdapter adapter = new UserAdapter(MainActivity.this,
                R.layout.user_item,UserList);
        ListView listView = (ListView) findViewById(R.id.user_list);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent,View view,
                                    int position,long id){
                User user = UserList.get(position);
                String name = user.getName();
                String telnumber = user.getTelnumber();
                Intent intent = new Intent(MainActivity.this,UserActivity.class);
                intent.putExtra("name",name);
                intent.putExtra("telnumber",telnumber);
                startActivity(intent);
            }
        });
    }


    private void initUser(){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.query("User",null,null,null,null,null,null);
        if(cursor.moveToFirst()){
            do{
                //遍歷
                String name = cursor.getString(cursor.getColumnIndex("name"));
                String telnumber = cursor.getString(cursor.getColumnIndex("telnumber"));
                User user = new User(name,telnumber,R.mipmap.ic_launcher);
                UserList.add(user);
            }while(cursor.moveToNext());
        }
        cursor.close();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.addUser:{
                Intent intent = new Intent(MainActivity.this,AddUserActivity.class);
                startActivity(intent);
                this.finish();
            }
                break;
        }
    }
}
User.java 聯絡人類
public class User {
    private int imgId;
    private String name;
    private String telnumber;

    public User(String name,String telnumber,int imgId){
        this.name = name;
        this.telnumber = telnumber;
        this.imgId = imgId;
    }

    public int getImgId(){
        return imgId;
    }

    public String getName(){
        return name;
    }

    public String getTelnumber(){
        return telnumber;
    }
}
UserAdapter.java  ListView的介面卡
public class UserAdapter extends ArrayAdapter<User>{
    private int resourceId;

    public UserAdapter(Context context, int textViewResourceId,List<User> objects){
        super(context,textViewResourceId,objects);
        resourceId = textViewResourceId;
    }

    @Override
    public View getView(int position,View converView,ViewGroup parent){
        User user = getItem(position);//獲取當前User例項
        View view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
        ImageView userimg = (ImageView) view.findViewById(R.id.user_img);
        TextView username = (TextView) view.findViewById(R.id.user_name);
        TextView telphone = (TextView) view.findViewById(R.id.telnumber);

        userimg.setImageResource(user.getImgId());
        username.setText(user.getName());
        telphone.setText(user.getTelnumber());

        return view;
    }
}
AddUserActivity.java 新增聯絡人資訊的活動
public class AddUserActivity extends AppCompatActivity implements View.OnClickListener{

    private MyDatabaseHelper dbHelper;
    private EditText username,telnumber;
    private Button ok_add,create_database;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_user);

        dbHelper = new MyDatabaseHelper(this,"User.db",null,1);

        username = (EditText) findViewById(R.id.add_user_name);
        telnumber = (EditText) findViewById(R.id.add_user_telnumber);
        ok_add = (Button) findViewById(R.id.ok_add);
        ok_add.setOnClickListener(this);
        create_database = (Button) findViewById(R.id.create_database);
        create_database.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.create_database:{
                dbHelper.getWritableDatabase();
            }
                break;
            case R.id.ok_add:{
                String name = username.getText().toString();
                String tel_number = telnumber.getText().toString();
                if(name == null || tel_number == null){
                    Toast.makeText(this,"使用者名稱和電話不能為空!",Toast.LENGTH_SHORT).show();
                }else{
                    SQLiteDatabase db = dbHelper.getWritableDatabase();
                    ContentValues values = new ContentValues();
                    values.put("name",name);
                    values.put("telnumber",tel_number);
                    db.insert("User",null,values);
                    values.clear();
                    Toast.makeText(this,"新增成功!",Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(AddUserActivity.this,MainActivity.class);
                    startActivity(intent);
                    this.finish();
                }
            }
        }
    }
}
MyDatabaseHelper.java  MyDatabaseHelper類,用來幫助管理資料庫,建立資料庫、更新資料庫
public class MyDatabaseHelper extends SQLiteOpenHelper{

    public static final String Create_User_Table = "create table User ("
            + "id integer primary key autoincrement,"
            + "name text,"
            + "telnumber text)";

    private Context mContext;

    public MyDatabaseHelper(Context context,String name,SQLiteDatabase.CursorFactory factory,
                            int version){
        super(context,name,factory,version);
        mContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(Create_User_Table);
        Toast.makeText(mContext,"建立成功",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}
UserActivity.java用來顯示使用者詳細資訊的活動
public class UserActivity extends AppCompatActivity {

    private TextView name,telnumber;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);

        name = (TextView) findViewById(R.id.text_name);
        telnumber = (TextView) findViewById(R.id.text_number);

        Intent intent = getIntent();
        String user_name = intent.getStringExtra("name");
        name.setText(user_name);
        String telephone = intent.getStringExtra("telnumber");
        telnumber.setText(telephone);
    }
}
activity_add_user.xml新增聯絡人資訊的佈局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.sqlite.AddUserActivity">


    <EditText
        android:id="@+id/add_user_name"
        android:hint="姓名"
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/add_user_telnumber"
        android:hint="電話號碼"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/add_user_name"/>

    <Button
        android:id="@+id/ok_add"
        android:text="新增"
        android:textSize="18dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/add_user_telnumber"/>

    <Button
        android:id="@+id/create_database"
        android:text="建立資料庫"
        android:textSize="18dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/ok_add"/>

</RelativeLayout>
activity_user.xml 點選ListView後顯示聯絡人詳細資訊的
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.sqlite.UserActivity">


    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="92dp"
        android:text="姓名"
        android:textSize="20dp"
        android:layout_marginLeft="70dp"
        android:layout_marginStart="39dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/textView"
        android:layout_alignRight="@+id/textView"
        android:layout_below="@+id/textView"
        android:layout_marginTop="29dp"
        android:text="電話"
        android:textSize="20dp"/>

    <TextView
        android:id="@+id/text_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/textView"
        android:layout_marginLeft="49dp"
        android:layout_marginStart="49dp"
        android:layout_toEndOf="@+id/textView"
        android:layout_toRightOf="@+id/textView"
        android:textSize="20dp"/>

    <TextView
        android:id="@+id/text_number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textView2"
        android:layout_alignStart="@+id/text_name"
        android:layout_alignLeft="@+id/text_name"
        android:layout_alignRight="@+id/text_name"
        android:textSize="20dp"/>
</RelativeLayout>