您的位置:首页 > 移动开发 > Android开发

Android核心技术-day05-03-学生信息管理系统小练习

2018-11-07 11:49 567 查看
版权声明:心灵泽尘 https://blog.csdn.net/github_38313789/article/details/83757306

[code]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;
}

}

[code]<?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>

 

[code]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();
}
}
}

 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: