1. 程式人生 > >Android核心技術-day05-03-學生資訊管理系統小練習

Android核心技術-day05-03-學生資訊管理系統小練習

package com.gaozewen.studentsystem.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.gaozewen.studentsystem.domain.StudentInfo;

/**
 * @author gzw
 * @version $Rev$
 * @des ${TODO}
 * @updateAuthor $Author$
 * @updateDes ${TODO}
 */
public class StudentDao {
    private StudentDBOpenHelper helper;

    public StudentDao(Context context) {
        helper = new StudentDBOpenHelper(context);
    }

    /**
     * 新增一條記錄
     * @param info 學生 domain
     * @return 是否新增成功
     */
    public boolean add(StudentInfo info) {
        return add(String.valueOf(info.getId()),info.getName(),info.getPhone());
    }

    /**
     * 新增一條記錄
     *
     * @param studentid 學生id
     * @param name      學生姓名
     * @param phone     學生電話
     * @return 是否新增成功 true false
     */
    public boolean add(String studentid, String name, String phone) {
        SQLiteDatabase db = helper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("studentid", studentid);
        values.put("name", name);
        values.put("phone", phone);
        long row = db.insert("info", null, values);
        db.close();
        return row != -1;
    }

    /**
     * 刪除一條記錄
     *
     * @param studentid 學生id
     * @return 是否刪除成功 true false
     */
    public boolean delete(String studentid) {
        SQLiteDatabase db = helper.getWritableDatabase();
        long count = db.delete("info", "studentid = ?", new String[]{studentid});
        db.close();
        return count > 0;
    }

    /**
     * 查詢一條記錄
     *
     * @param position 資料在資料庫表裡面的位置
     * @return StudentInfo
     */
    public StudentInfo getStudentInfo(int position) {
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor cursor = db.query("info", new String[]{"studentid", "name", "phone"}, null, null, null, null, null);
        cursor.moveToPosition(position);
        String studentid = cursor.getString(0);
        String name = cursor.getString(1);
        String phone = cursor.getString(2);
        cursor.close();
        db.close();
        StudentInfo result = new StudentInfo();
        result.setId(Integer.valueOf(studentid));
        result.setName(name);
        result.setPhone(phone);
        return result;
    }

    /**
     * 查詢資料庫裡面一共有多少條記錄
     *
     * @return 記錄的條數
     */
    public int getTotalCount() {
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor cursor = db.query("info", null, null, null, null, null, null);
        int count = cursor.getCount();
        cursor.close();
        db.close();
        return count;
    }

    /**
     * 刪除所有的資料
     *
     * @return 是否刪除成功 true false
     */
    public boolean deleteAll() {
        boolean isSuccess = false;
        SQLiteDatabase db = helper.getWritableDatabase();
        try {
            db.beginTransaction();
            Cursor cursor = db.query("info", new String[]{"studentid"}, null, null, null, null, null);
            while (cursor.moveToNext()) {
                String studentid = cursor.getString(0);
                db.delete("info", "studentid = ?", new String[]{studentid});
            }
            cursor.close();
            db.setTransactionSuccessful();
            isSuccess = true;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            db.endTransaction();
            db.close();
        }
        return isSuccess;
    }

}

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

    <TextView
        android:id="@+id/tv_item_id"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center_horizontal"
        android:text="學生id"
        android:textColor="#ff0000" />

    <TextView
        android:id="@+id/tv_item_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center_horizontal"
        android:text="學生name"
        android:textColor="#00ff00" />

    <TextView
        android:id="@+id/tv_item_phone"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center_horizontal"
        android:text="學生phone"
        android:textColor="#0000ff" />

    <ImageView
        android:id="@+id/iv_item_delete"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_marginRight="8dp"
        app:srcCompat="@drawable/block_msg_delete" />
</LinearLayout>

 

package com.gaozewen.studentsystem;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gaozewen.studentsystem.db.StudentDao;
import com.gaozewen.studentsystem.domain.StudentInfo;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;

import java.io.File;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private EditText mEt_id;
    private EditText mEt_name;
    private EditText mEt_phone;
    private ListView mLv;
    private ArrayList<StudentInfo> mList;
    private StudentDao dao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initView();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.item_save:
                Toast.makeText(this, "上傳到雲伺服器", Toast.LENGTH_SHORT).show();
                // 上傳資料到雲伺服器的方法
                uploadDBToServer();
                break;
            case R.id.item_delet_all:
                boolean isSuccess = dao.deleteAll();
                Toast.makeText(this, isSuccess ? "刪除資料成功" : "刪除資料失敗", Toast.LENGTH_SHORT).show();
                if (isSuccess) {
                    // 重新整理介面
                    mLv.setAdapter(new MyAdapter());
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 上傳資料到伺服器
     */
    private void uploadDBToServer() {
        File file = new File("/data/data/com.gaozewen.studentsystem/databases/student.db");
        if (file.exists() && file.length() > 0) {
            try {
                AsyncHttpClient client = new AsyncHttpClient();
                RequestParams params = new RequestParams();
                params.put("file", file);
                client.post("http://192.168.1.102:8080/upload", params, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                        Toast.makeText(MainActivity.this, "上傳成功", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                        Toast.makeText(MainActivity.this, "上傳失敗", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onProgress(int bytesWritten, int totalSize) {
                        System.out.println(bytesWritten + "/" + totalSize);
                        super.onProgress(bytesWritten, totalSize);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(MainActivity.this, "上傳失敗", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "檔案不存在或者內容為空", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 初始化介面
     */
    private void initView() {
        setContentView(R.layout.activity_main);
        mEt_id = (EditText) findViewById(R.id.et_id);
        mEt_name = (EditText) findViewById(R.id.et_name);
        mEt_phone = (EditText) findViewById(R.id.et_phone);
        mLv = (ListView) findViewById(R.id.lv);

        mList = new ArrayList<>();

        dao = new StudentDao(this);
        // 顯示 ListView
        mLv.setAdapter(new MyAdapter());
    }

    /**
     * button 的點選事件,用來新增學生資訊
     *
     * @param view
     */
    public void addStudent(View view) {
        String id = mEt_id.getText().toString().trim();
        String name = mEt_name.getText().toString().trim();
        String phone = mEt_phone.getText().toString().trim();
        if (TextUtils.isEmpty(id) || TextUtils.isEmpty(name) || TextUtils.isEmpty(phone)) {
            Toast.makeText(this, "資料不能為空", Toast.LENGTH_SHORT).show();
        } else {
            // 儲存資料到資料庫,並且同步顯示到介面
            StudentInfo info = new StudentInfo();
            info.setId(Integer.valueOf(id));
            info.setName(name);
            info.setPhone(phone);
            boolean isAddSuccess = dao.add(info);
            if (isAddSuccess) {
                Toast.makeText(this, "新增成功", Toast.LENGTH_SHORT).show();
                mLv.setAdapter(new MyAdapter());
            }

        }
    }

    private class MyAdapter extends BaseAdapter {
        @Override
        public View getView(final int i, View convertView, ViewGroup viewGroup) {
            View view = View.inflate(MainActivity.this, R.layout.item, null);
            TextView tv_item_id = (TextView) view.findViewById(R.id.tv_item_id);
            TextView tv_item_name = (TextView) view.findViewById(R.id.tv_item_name);
            TextView tv_item_phone = (TextView) view.findViewById(R.id.tv_item_phone);
            ImageView iv_item_delete = (ImageView) view.findViewById(R.id.iv_item_delete);

            iv_item_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    boolean isDeleteSuccess = dao.delete(String.valueOf(getItemId(i)));
                    if (isDeleteSuccess) {
                        Toast.makeText(MainActivity.this, "刪除成功", Toast.LENGTH_SHORT).show();
                        mLv.setAdapter(new MyAdapter());
                    }
                }
            });
            StudentInfo item = getItem(i);
            tv_item_id.setText(String.valueOf(item.getId()));
            tv_item_name.setText(item.getName());
            tv_item_phone.setText(item.getPhone());
            return view;
        }

        @Override
        public int getCount() {
            return dao.getTotalCount();
        }

        @Override
        public StudentInfo getItem(int i) {
            return dao.getStudentInfo(i);
        }

        @Override
        public long getItemId(int i) {
            return dao.getStudentInfo(i).getId();
        }
    }
}