安卓学习记录(五)——体温表APP.2
阅读原文时间:2023年07月10日阅读:2

一、项目结构

二、源码

1.数据层

db+dao+bean

package com.example.tem.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;

public class DBHelper extends SQLiteOpenHelper{
public DBHelper(@Nullable Context context){
super(context,"temperature",null,3);//库名“temperature”
}
@Override
public void onCreate(SQLiteDatabase db){
db.execSQL("create table info(id INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR(50) NOT NULL,sex VARCHAR(20) NOT NULL,date VARCHAR(50) NOT NULL,heat VARCHAR(20) NOT NULL,place CARCHAR(500) NOT NULL)");
//表名“info”
}
@Override
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){

}  

}

DBHelper.class

package com.example.tem.dao;

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

import com.example.tem.db.DBHelper;
import com.example.tem.bean.TemBean;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class TemDao {
private DBHelper helper;
public TemDao(Context context){
helper = new DBHelper(context);
}

public boolean insert(TemBean temBean){//增  
    SQLiteDatabase db = helper.getReadableDatabase();

    Date date0 = new Date();  
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");  
    String date = simpleDateFormat.format(date0);

    ContentValues values = new ContentValues();  
    values.put("name",temBean.getName());  
    values.put("sex",temBean.getSex());  
    values.put("date",date);  
    values.put("heat",temBean.getHeat());  
    values.put("place",temBean.getPlace());  
    long insert = db.insert("info",null,values);  
    //System.out.println(temBean.getPlace());  
    return insert>0;  
}

public  boolean update(TemBean temBean){//改  
    SQLiteDatabase db = helper.getReadableDatabase();  
    ContentValues values = new ContentValues();  
    values.put("name",temBean.getName());  
    values.put("sex",temBean.getSex());  
    values.put("date",temBean.getDate());  
    values.put("heat",temBean.getHeat());  
    values.put("place",temBean.getPlace());  
    long update = db.update("info",values,"id=?",new String\[\]{temBean.getId()+""});  
    System.out.println(temBean.getId());  
    return  update>0;  
}

public List<TemBean> queryAll(){//查  
    List<TemBean> list = new ArrayList<>();  
    TemBean bean = null;  
    SQLiteDatabase db = helper.getReadableDatabase();  
    Cursor c = db.query("info",null,null,null,null,null,null);  
    if(c != null && c.getCount()>0){  
        list = new ArrayList<>();  
        while(c.moveToNext()){  
            bean = new TemBean();  
            bean.setId(c.getInt(c.getColumnIndex("id")));  
            bean.setName(c.getString(c.getColumnIndex("name")));  
            bean.setSex(c.getString(c.getColumnIndex("sex")));  
            bean.setDate(c.getString(c.getColumnIndex("date")));  
            bean.setHeat(c.getString(c.getColumnIndex("heat")));  
            bean.setPlace(c.getString(c.getColumnIndex("place")));  
            list.add(bean);  
        }  
    }  
    return list;  
}

}

TemDao.class

package com.example.tem.bean;

import java.io.Serializable;

public class TemBean implements Serializable{

public Integer id;//设置id便于对数据进行操作  
public String name;  
public String sex;  
public String date;  
public String heat;  
public String place;

public TemBean() {

}

@Override  
public String toString() {  
    return "TemBean{" +  
            "id='" + id +  
            ",name='" + name + '\\'' +  
            ",sex='" + sex + '\\'' +  
            ", date='" + date + '\\'' +  
            ", heat='" + heat + '\\'' +  
            ", place='" + place + '\\'' +  
            '}';  
}

public Integer getId(){  
    return id;  
}

public void setId(Integer id){  
    this.id = id;  
}

public String getName() {  
    return name;  
}

public void setName(String name) {  
    this.name = name;  
}

public String getSex(){  
    return sex;  
}

public void setSex(String sex){  
    this.sex = sex;  
}

public String getDate() {  
    return date;  
}

public void setDate(String date) {  
    this.date = date;  
}

public String getHeat() {  
    return heat;  
}

public void setHeat(String heat) {  
    this.heat = heat;  
}

public String getPlace() {  
    return place;  
}

public void setPlace(String place) {  
    this.place = place;  
}

public TemBean(Integer id,String name,String sex,String date,String heat,String place){  
    this.id = id;  
    this.name = name;  
    this.sex = sex;  
    this.date = date;  
    this.heat = heat;  
    this.place = place;  
}

}

TemBean.class

2.适配器

package com.example.tem.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.tem.MainActivity;
import com.example.tem.R;
import com.example.tem.bean.TemBean;
import java.util.List;

public class Temp extends RecyclerView.Adapter{

    private Context mContext;  
    private List<TemBean> list;

    public Temp (Context context, List<TemBean> list){  
        this.mContext=context;  
        this.list=list;  
    }  
    public void setList(List<TemBean> list) {  
        this.list=list;  
    }  
    @NonNull  
    @Override  
    public TempViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {  
        TempViewHolder holder=new TempViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item\_view,parent,false));  
        return holder;

    }

    @Override  
    public void onBindViewHolder(@NonNull TempViewHolder holder, int position) {  
        TemBean temBean=list.get(position);

        holder.tv\_name.setText("姓名:"+temBean.getName());  
        holder.tv\_date.setText(temBean.getDate());  
        holder.tv\_sex.setText("性别:"+temBean.getSex());  
        holder.tv\_heat.setText(temBean.getHeat());  
        holder.tv\_place.setText(temBean.getPlace());

        holder.btn\_edit.setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View v) {  
                Intent intent=new Intent();  
                intent.setClass(mContext, MainActivity.class);  
                intent.putExtra("edititem",temBean);  
                mContext.startActivity(intent);  
            }  
        });  
    }

    @Override  
    public int getItemCount() {  
        return list==null?0:list.size();  
    }

    //绑定单元格空间  
    class TempViewHolder extends RecyclerView.ViewHolder{  
        TextView tv\_name;  
        TextView tv\_date;  
        TextView tv\_heat;  
        TextView tv\_sex;  
        TextView tv\_place;  
        Button btn\_edit;

        public TempViewHolder(@NonNull View itemView) {  
            super(itemView);  
            tv\_name=itemView.findViewById(R.id.tv\_name);  
            tv\_date=itemView.findViewById(R.id.tv\_date);  
            tv\_sex=itemView.findViewById(R.id.tv\_sex);  
            tv\_place=itemView.findViewById(R.id.tv\_place);  
            tv\_heat=itemView.findViewById(R.id.tv\_heat);  
            btn\_edit=itemView.findViewById(R.id.btn\_edit);

        }  
    }

}

adapter

3.百度定位相关

package com.example.tem.location;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.Poi;
import com.example.tem.MainActivity;
import com.example.tem.R;
import com.example.tem.location.LocationService;

public class LocationActivity extends MainActivity {
private LocationService locationService;
private TextView mTextView;
private Button button;

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

    mTextView = findViewById(R.id.textview);  
    button = findViewById(R.id.button);  
    button.setOnClickListener(new View.OnClickListener() {  
        @Override  
        public void onClick(View view) {  
            if (button.getText().toString().equals("添加")) {  
                locationService.start();  
            } else {  
                locationService.stop();  
                button.setText("自动定位");  
                mTextView.setText("");  
            }  
        }  
    });

    locationService = new LocationService(this);  

// 多个activity
// locationService = ((App) getApplication()).locationService;
locationService.registerListener(mListener);
locationService.setLocationOption(locationService.getDefaultLocationClientOption());
}

@Override  
protected void onDestroy() {  
    super.onDestroy();  
    locationService.unregisterListener(mListener); //注销掉监听  
    locationService.stop(); //停止定位服务  
}

/\*\*\*\*\*  
 \*  
 \* 定位结果回调,重写onReceiveLocation方法,可以直接拷贝如下代码到自己工程中修改  
 \*  
 \*/  
private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {

    @Override  
    public void onReceiveLocation(BDLocation location) {  
        // TODO Auto-generated method stub  
        if (null != location && location.getLocType() != BDLocation.TypeServerError) {  
            //button.setText("停止定位");  
            StringBuilder sb = new StringBuilder(256);  

// sb.append("time : ");
/**
* 时间也可以使用systemClock.elapsedRealtime()方法 获取的是自从开机以来,每次回调的时间;
* location.getTime() 是指服务端出本次结果的时间,如果位置不发生变化,则时间不变
*/
// sb.append(location.getTime());
sb.append("\nlocType : ");// 定位类型
sb.append(location.getLocType());
sb.append("\nlocType description : ");// *****对应的定位类型说明*****
sb.append(location.getLocTypeDescription());
// sb.append("\nlatitude : ");// 纬度
// sb.append(location.getLatitude());
// sb.append("\nlontitude : ");// 经度
// sb.append(location.getLongitude());
// sb.append("\nradius : ");// 半径
// sb.append(location.getRadius());
// sb.append("\nCountryCode : ");// 国家码
// sb.append(location.getCountryCode());
// sb.append("\nCountry : ");// 国家名称
// sb.append(location.getCountry());
// sb.append("\ncitycode : ");// 城市编码
// sb.append(location.getCityCode());
// sb.append("\ncity : ");// 城市
// sb.append(location.getCity());
// sb.append("\nDistrict : ");// 区
// sb.append(location.getDistrict());
// sb.append("\nStreet : ");// 街道
sb.append(location.getStreet());
sb.append("\naddr : ");// 地址信息
sb.append(location.getAddrStr());
// sb.append("\nUserIndoorState: ");// *****返回用户室内外判断结果*****
// sb.append(location.getUserIndoorState());
// sb.append("\nDirection(not all devices have value): ");
// sb.append(location.getDirection());// 方向
sb.append("\nlocationdescribe: ");
sb.append(location.getLocationDescribe());// 位置语义化信息
// sb.append("\nPoi: ");// POI信息
// if (location.getPoiList() != null && !location.getPoiList().isEmpty()) {
// for (int i = 0; i < location.getPoiList().size(); i++) {
// Poi poi = (Poi) location.getPoiList().get(i);
// sb.append(poi.getName() + ";");
// }
// }
if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
sb.append("\nspeed : ");
sb.append(location.getSpeed());// 速度 单位:km/h
sb.append("\nsatellite : ");
sb.append(location.getSatelliteNumber());// 卫星数目
sb.append("\nheight : ");
sb.append(location.getAltitude());// 海拔高度 单位:米
sb.append("\ngps status : ");
sb.append(location.getGpsAccuracyStatus());// *****gps质量判断*****
sb.append("\ndescribe : ");
sb.append("gps定位成功");
} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
// 运营商信息
if (location.hasAltitude()) {// *****如果有海拔高度*****
sb.append("\nheight : ");
sb.append(location.getAltitude());// 单位:米
}
sb.append("\noperationers : ");// 运营商信息
sb.append(location.getOperators());
sb.append("\ndescribe : ");
sb.append("网络定位成功");
} else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
sb.append("\ndescribe : ");
sb.append("离线定位成功,离线定位结果也是有效的");
} else if (location.getLocType() == BDLocation.TypeServerError) {
sb.append("\ndescribe : ");
sb.append("服务端网络定位失败,可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com,会有人追查原因");
} else if (location.getLocType() == BDLocation.TypeNetWorkException) {
sb.append("\ndescribe : ");
sb.append("网络不同导致定位失败,请检查网络是否通畅");
} else if (location.getLocType() == BDLocation.TypeCriteriaException) {
sb.append("\ndescribe : ");
sb.append("无法获取有效定位依据导致定位失败,一般是由于手机的原因,处于飞行模式下一般会造成这种结果,可以试着重启手机");
}
logMsg(sb.toString());
}
}

};

/\*\*  
 \* 显示请求字符串  
 \*/  
public void logMsg(final String str) {  
    try {  
        new Thread(new Runnable() {  
            @Override  
            public void run() {  
                mTextView.post(new Runnable() {  
                    @Override  
                    public void run() {  
                        mTextView.setText(str);  
                    }  
                });  
            }  
        }).start();  
    } catch (Exception e) {  
        e.printStackTrace();  
    }  
}  

}

LocationActivity

package com.example.tem.location;
import android.content.Context;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;

public class LocationService {
private LocationClient client = null;
private LocationClientOption mOption,DIYoption;
private Object objLock = new Object();

public LocationService(Context locationContext){  
    synchronized (objLock) {  
        if(client == null){  
            client = new LocationClient(locationContext);  
            client.setLocOption(getDefaultLocationClientOption());  
        }  
    }  
}

// 注册  
public boolean registerListener(BDAbstractLocationListener listener){  
    boolean isSuccess = false;  
    if(listener != null){  
        client.registerLocationListener(listener);  
        isSuccess = true;  
    }  
    return  isSuccess;  
}

// 注销  
public void unregisterListener(BDAbstractLocationListener listener){  
    if(listener != null){  
        client.unRegisterLocationListener(listener);  
    }  
}

//设置配置  
public boolean setLocationOption(LocationClientOption option){  
    boolean isSuccess = false;  
    if(option != null){  
        if(client.isStarted())  
            client.stop();  
        DIYoption = option;  
        client.setLocOption(option);  
    }  
    return isSuccess;  
}

//默认Option设置  
public LocationClientOption getDefaultLocationClientOption(){  
    if(mOption == null){  
        mOption = new LocationClientOption();  
        mOption.setLocationMode(LocationMode.Hight\_Accuracy);//可选,默认高精度,设置定位模式,高精度,低功耗,仅设备  
        mOption.setCoorType("bd09ll");//可选,默认gcj02,设置返回的定位结果坐标系,如果配合百度地图使用,建议设置为bd09ll;  
        mOption.setScanSpan(3000);//可选,默认0,即仅定位一次,设置发起连续定位请求的间隔需要大于等于1000ms才是有效的  
        mOption.setIsNeedAddress(true);//可选,设置是否需要地址信息,默认不需要  
        mOption.setIsNeedLocationDescribe(true);//可选,设置是否需要地址描述  
        mOption.setNeedDeviceDirect(false);//可选,设置是否需要设备方向结果  
        mOption.setLocationNotify(false);//可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果  
        mOption.setIgnoreKillProcess(true);//可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死  
        mOption.setIsNeedLocationDescribe(true);//可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近”  
        mOption.setIsNeedLocationPoiList(true);//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到  
        mOption.SetIgnoreCacheException(false);//可选,默认false,设置是否收集CRASH信息,默认收集  
        mOption.setOpenGps(true);//可选,默认false,设置是否开启Gps定位  
        mOption.setIsNeedAltitude(false);//可选,默认false,设置定位时是否需要海拔信息,默认不需要,除基础定位版本都可用

    }  
    return mOption;  
}

//自定义Option设置  
public LocationClientOption getOption(){  
    if(DIYoption == null) {  
        DIYoption = new LocationClientOption();  
    }  
    return DIYoption;  
}

public void start(){  
    synchronized (objLock) {  
        if(client != null && !client.isStarted()){  
            client.start();  
        }  
    }  
}  
public void stop(){  
    synchronized (objLock) {  
        if(client != null && client.isStarted()){  
            client.stop();  
        }  
    }  
}

public boolean isStart() {  
    return client.isStarted();  
}

public boolean requestHotSpotState(){  
    return client.requestHotSpotState();  
}  

}

LocationService

4.布局


recycler_item.xml


<Button  
    android:id="@+id/btn\_add"  
    android:layout\_width="wrap\_content"  
    android:layout\_height="wrap\_content"  
    android:layout\_marginTop="1dp"  
    android:layout\_marginEnd="3dp"  
    android:layout\_marginRight="3dp"  
    android:text="添加"  
    android:background="@drawable/btn\_right"  
    app:layout\_constraintEnd\_toEndOf="parent"  
    app:layout\_constraintTop\_toTopOf="parent" />

<Button  
    android:id="@+id/btn\_back"  
    android:layout\_width="wrap\_content"  
    android:layout\_height="wrap\_content"  
    android:layout\_marginStart="3dp"  
    android:layout\_marginLeft="3dp"  
    android:layout\_marginTop="1dp"  
    android:text="退出"  
    android:background="@drawable/btn\_left"  
    app:layout\_constraintStart\_toStartOf="parent"  
    app:layout\_constraintTop\_toTopOf="parent" />

<TextView  
    android:id="@+id/textView"  
    android:layout\_width="wrap\_content"  
    android:layout\_height="wrap\_content"  
    android:layout\_marginStart="85dp"  
    android:layout\_marginLeft="85dp"  
    android:layout\_marginTop="6dp"  
    android:layout\_marginEnd="85dp"  
    android:layout\_marginRight="85dp"  
    android:text="体温统计"  
    android:textSize="30dp"  
    android:textColor="#F44336"  
    app:layout\_constraintEnd\_toStartOf="@+id/btn\_add"  
    app:layout\_constraintStart\_toEndOf="@+id/btn\_back"  
    app:layout\_constraintTop\_toTopOf="parent" />

<androidx.constraintlayout.widget.Guideline  
    android:id="@+id/guideline"  
    android:layout\_width="wrap\_content"  
    android:layout\_height="wrap\_content"  
    android:orientation="horizontal"  
    app:layout\_constraintGuide\_begin="56dp" />

<androidx.recyclerview.widget.RecyclerView  
    android:id="@+id/rec"  
    android:layout\_width="match\_parent"  
    android:layout\_height="match\_parent"  
    android:layout\_marginTop="60dp"  
    app:layout\_constraintTop\_toTopOf="parent"  
    tools:layout\_editor\_absoluteX="17dp" />

activity_index.xml


手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器