【Android原生开发】个人小助手

一、 项目开发的背景

用于安卓手机的个人日常管理系统的设计与开发,实现个人收支管理、日程管理、闹钟提醒、日程数据库的添删改查等功能,系统使用SQLite数据库实现了日程记录数据的管理,挥SQLite占用资源少、操作简单、运行效率高的优势。
日程管理是将每天计划、工作和事务安排在日期中,并做一个有效的记录,方便管理日程的工作和事务,达到工作备忘的目的。闹钟提醒服务是重要功能之一,将闹钟提醒设为开机启动服务,读取系统时间与日程表时间相匹配,定时提供闹钟提醒,用户可选择提醒的闹钟铃声。
让用户在移动终端上体验方便、快捷的个人助理管理。满足用户将学习工作计划、会议安排等事务随时记录到此系统中,并且可以方便得实现收支、日程记录的查找、添加、修改,删除。查找模块提供全部日程查找,还可以根据类型、重要性、日期等实现丰富的查询功能。
可以对某一日程记录进行留言,记录该日程的处理情况。

二、涉及的技术

使用Android原生开发

三、项目真机运行

运行视频

四、开发过程

A、加载界面\引导页\登录界面

界面展示

在这里插入图片描述在这里插入图片描述

配置说明

package com.example.time;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Window;
import android.widget.Toast;

import com.example.time.GuidePage.GuideActivity;

import org.json.JSONObject;

import java.lang.reflect.Method;

import static com.example.time.MainActivity.REQUEST_CODE;

public class LoadingPage extends Activity {
    public static final String lodingPageSuccess = "lodingPageSuccess";
    private Context mContext = this;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loading_page);
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                }
            }
        }
        new FetchData().execute();
        //不要标题
    }
    public class FetchData extends AsyncTask<String, Void, JSONObject> {

        @Override
        protected JSONObject doInBackground(String... strings) {
//            后台获取处理数据
//            链接云端数据库的数据
            try {
                if (!permission()) {
                    Toast.makeText(mContext, "请同意相关权限,否则应用的一些功能会无法使用",Toast.LENGTH_LONG).show();
                    requestAlertWindowPermission();
                }
                Thread.sleep(7000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(JSONObject jsonObject) {
//            更新前端界面-跳转界面
            Intent mainIntent = new Intent(LoadingPage.this, GuideActivity.class);
            mainIntent.putExtra(lodingPageSuccess,"success");
            startActivity(mainIntent);
            finish();
        }
    }

    public boolean permission(){
        //判断权限
        Boolean result = true;
        if (Build.VERSION.SDK_INT >= 23) {
            try {
                Class<Settings> clazz = Settings.class;
                Method canDrawOverlays;
                canDrawOverlays = clazz.getDeclaredMethod("canDrawOverlays", Context.class);
                result = (Boolean) canDrawOverlays.invoke(null, mContext);
            } catch (Exception e) {
                Log.e("TAG", Log.getStackTraceString(e));
            }
        }
        return result;
    }

    //申请权限,跳转到系统的权限申请界面
    private void requestAlertWindowPermission() {
        Intent intent = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
        }
        assert intent != null;
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivityForResult(intent, REQUEST_CODE);
    }
}

加载界面得过程中,获取云端数据库的数据,以及一些权限的获取。

B、引导页

建立适配器

public class GuideAdapter extends PagerAdapter {
    public List<View> viewList;
    public GuideAdapter(List<View> viewList) {
        this.viewList = viewList;
    }
    @Override
    public int getCount() {
        return viewList.size();
    }
    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view==object;
    }
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        container.addView(viewList.get(position));
        return viewList.get(position);
    }
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView(viewList.get(position));
    }
}

创建引导页活动

在这里插入图片描述

监听页面变化

private class MyPageChangeListener implements ViewPager.OnPageChangeListener {
    @Override
    public void onPageScrollStateChanged(int arg0) {
    }
    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }
    @Override
    public void onPageSelected(int arg0) {
        if (arg0 == resources.length -1){
            start.setVisibility(View.VISIBLE);
        }else {
            start.setVisibility(View.INVISIBLE);
        }
    }
}

增加跳过按钮

在这里插入图片描述

对应的xml界面布局

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".GuidePage.GuideActivity"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <androidx.viewpager.widget.ViewPager
        android:id="@+id/guide_viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0"/>
    <Button
        android:id="@+id/start"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_marginBottom="20dp"
        app:layout_constraintVertical_bias="0.9"
        android:background="@drawable/morning_bg"
        android:text="GO"
        android:textColor="@color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/skip"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_marginBottom="20dp"
        android:background="@drawable/morning_bg"
        app:layout_constraintVertical_bias="0.1"
        app:layout_constraintHorizontal_bias="0.85"
        android:text="Skip"
        android:textColor="@color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

新建登录活动

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_login);
    context = this;
    //绑定界面
    bindView();
    //初始化QQ第三方登录
    QQLogin.INSTANCE.initQQ(LoginActivity.this);
    //监听事件
    this.addListener();
}

除了基本的界面绑定控件,还设计了密码登录及第三方授权登录

密码登录

private void loginByPassword(){
    String inputAccountStr = inputAccount.getText().toString();
    String inputPasswordStr = inputPassword.getText().toString();
    if(inputAccountStr.equals("wyj")&&inputPasswordStr.equals("wyj")){
        Intent intent = new Intent();
        intent.putExtra("user","login");
        setResult(RESULT_OK, intent);
        Intent intent1 = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent1);
        finish();
    }else{
        Toast t = Toast.makeText(context,"password error !",Toast.LENGTH_LONG);
        t.show();
    }
}

QQ第三方授权登录

单例模式下构建qq登录管理服务,外部无法new出一个实例,只能调用该类中的public方法
在这里插入图片描述
基本的方法包括初始化QQ,登录QQ,获取QQ授权后返回的用户数据,保存用户登录状态

public void gotoQQLogout(Context context){
    if (mTencent != null) {
        //注销登录
        mTencent.logout(context);
        Toast.makeText(context, "你已注销~", Toast.LENGTH_LONG).show();
        saveLoginStatus(context,false);
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
        ((Activity) context).finish();
    }
}
public void initQQ(final Context context){
    String APP_ID = "1110586725";
    mTencent = Tencent.createInstance(APP_ID, context);
    loginListener = new IUiListener() {
        @Override
        public void onComplete(Object o) {
            try {
                JSONObject jo = (JSONObject) o;
                int ret = jo.getInt("ret");
                System.out.println("json=" + String.valueOf(jo));
                if (ret == 0) {
                    String openID = jo.getString("openid");
                    String accessToken = jo.getString("access_token");
                    String expires = jo.getString("expires_in");
                    mTencent.setOpenId(openID);
                    mTencent.setAccessToken(accessToken, expires);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        @Override
        public void onError(UiError uiError) {}
        @Override
        public void onCancel() {
        }
    };
    userInfoListener = new IUiListener() {
        @Override
        public void onError(UiError arg0) {
        }
        @Override
        public void onComplete(Object arg0) {
            if(arg0 == null){
                return;
            }
            try {
                JSONObject jo = (JSONObject) arg0;
                int ret = jo.getInt("ret");
                String gender = jo.getString("gender");
                nickName = jo.getString("nickname");
                logo = jo.getString("figureurl_qq_2");
                //跳转至主界面
                saveLoginStatus(context,true);
                Intent intent1 = new Intent(context, MainActivity.class);
                context.startActivity(intent1);
                ((Activity) context).finish();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        @Override
        public void onCancel() {
            saveLoginStatus(context,false);
        }
    };
}
public void loginByQQ(Context context){
    baseApiListener = new BaseApiListener();
    if (!mTencent.isSessionValid()) {
        //开始qq授权登录
        mTencent.login((Activity) context, "all", loginListener);
    }else {
        Toast.makeText(context, "你已登录!", Toast.LENGTH_LONG).show();
    }
}

这里保存了用户登录状态为true(若授权成功),采用的是SharedPreferences的方法来保存

public void saveLoginStatus(Context context,boolean key){
    //    使用sharepreference来保存登录状态的数据
    SharedPreferences.Editor editor = context.getSharedPreferences("data",MODE_PRIVATE).edit();
    editor.putBoolean("loginStatus",key);
    editor.apply();
}

第三方登录的调用方法

QQLogin.INSTANCE.initQQ(LoginActivity.this);
QQLogin.INSTANCE.loginByQQ(LoginActivity.this);
QQLogin.INSTANCE.onActivityResultHandle(requestCode,resultCode,data, LoginActivity.this);

获取QQ头像链接图片函数

public static Bitmap getHttpBitmap(String url) {
    URL myFileUrl = null;
    Bitmap bitmap = null;
    try {
        myFileUrl = new URL(url);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    try {
        HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
        conn.setConnectTimeout(0);
        conn.setDoInput(true);
        conn.connect();
        InputStream is = conn.getInputStream();
        bitmap = BitmapFactory.decodeStream(is);
        is.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bitmap;
}

C、主界面

界面展示

在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述

绘制主界面(xml)

<androidx.drawerlayout.widget.DrawerLayout
    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:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">
    <include
        layout="@layout/activity_main_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <com.google.android.material.navigation.NavigationView
        android:background="@drawable/main_activity_bg2"
        android:id="@+id/navigationView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:itemIconTint="@color/black"
        app:itemTextColor="@color/black"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/nav_menu" />

</androidx.drawerlayout.widget.DrawerLayout>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    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="match_parent">
    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay"
        android:background="@color/mainTextColor"
        app:elevation="0dp">
        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="45dp"
            app:popupTheme="@style/AppTheme"
            app:navigationIcon="@drawable/ce_bian_lan_logo"
            app:menu="@menu/tool_bar"/>
    </com.google.android.material.appbar.AppBarLayout>
    <include layout="@layout/activity_main_content"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

设置一个ScrollView,里面放四个子布局,分别是上午、中午、下午、晚上的布局
在这里插入图片描述

<include
    android:id="@+id/morning"
    layout="@layout/schedule_morning"
    android:layout_width="match_parent"
    android:layout_height="394dp"
    android:layout_marginTop="150dp"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintBottom_toTopOf="@+id/noon"/>

schedule_morning布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/color2">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/mainTextColor"
            android:text="上午"
            android:padding="8dp"
            android:textSize="20dp"/>
        <ImageView
            android:layout_width="8dp"
            android:layout_height="8dp"
            android:src="@drawable/point"
            android:layout_marginTop="25dp"/>
        <ImageView
            android:layout_width="10dp"
            android:layout_height="match_parent"
            android:background="@drawable/vertical_line"/>
        <com.example.time.scollListView.ScollListView
            android:id="@+id/schedule_morning"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"/>
    </LinearLayout>
</RelativeLayout>

ScrollListView类

由于是ScrollView嵌套子布局,会有滑动手势的冲突,当手指滑动scrollview里面的scrollview时,是不让上层的父组件接受滑动的事件,但是当滑动至底部或者顶部时,则父组件接受滑动事件

public class ScollListView extends ListView {
    private float mLastY;
    public ScollListView(Context context) {
        super(context);
    }
    public ScollListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public ScollListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public ScollListView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        //重点在这里
        int action = ev.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                super.onInterceptTouchEvent(ev);
                //不允许上层viewGroup拦截事件.
                getParent().requestDisallowInterceptTouchEvent(true);
                break;
            case MotionEvent.ACTION_MOVE:
                //满足listView滑动到顶部,如果继续下滑,那就让scrollView拦截事件
                if (getFirstVisiblePosition() == 0 && (ev.getY() - mLastY) > 0) {
                    //允许上层viewGroup拦截事件
                    getParent().requestDisallowInterceptTouchEvent(false);
                }
                //满足listView滑动到底部,如果继续上滑,那就让scrollView拦截事件
                else if (getLastVisiblePosition() == getCount() - 1 && (ev.getY() - mLastY) < 0) {
                    //允许上层viewGroup拦截事件
                    getParent().requestDisallowInterceptTouchEvent(false);
                } else {
                    //不允许上层viewGroup拦截事件
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                break;
            case MotionEvent.ACTION_UP:
                //不允许上层viewGroup拦截事件
                getParent().requestDisallowInterceptTouchEvent(true);
                break;
        }
        mLastY = ev.getY();
        return super.dispatchTouchEvent(ev);
    }
}

日程界面

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mainActivityDatabase = new MainActivityDataBase(MainActivity.this);
    this.bingView();
    this.initSchedules();
    this.setRightCeBianLan();
    this.addListener();
}

双击退出程序

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        if (mIsExit) {
            this.finish();
        } else {
            Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mIsExit = true;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mIsExit = false;
                }
            }, 2000);
        }
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

菜单界面中按钮的设置

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.tool_bar,menu);//加载menu布局
    return true;
}
@Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()){
            case  R.id.action_search:
                Toast.makeText(MainActivity.this,"action_search",Toast.LENGTH_SHORT).show();
                break;
        }
        return true;
    }

侧边栏按钮

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()){
        case R.id.beifen:
            Toast.makeText(MainActivity.this,"beifen",Toast.LENGTH_LONG).show();
            break;
        case R.id.recover:
            Toast.makeText(MainActivity.this,"recover",Toast.LENGTH_LONG).show();
            break;
        case R.id.download:
            Toast.makeText(MainActivity.this,"download",Toast.LENGTH_LONG).show();
            break;
        case R.id.close:
            drawerLayout.closeDrawer(GravityCompat.START);
            break;
    }
    drawerLayout.closeDrawers();
    return true;
}

日程界面的所有点击事件

@Override
public void onClick(View view) {
    switch(view.getId()){
        case R.id.add_schedule:
            initFloatingWindow();
            break;
        case R.id.floatActionButtonLogin:
            if(loginStatus){
                Toast.makeText(MainActivity.this,"已登录",Toast.LENGTH_LONG).show();
            }else{
                Intent mainIntent = new Intent(MainActivity.this,LoginActivity.class);
                startActivity(mainIntent);
                finish();
            }
            break;
        case R.id.date_select:
            Calendar c = Calendar.getInstance();
            new DatePickerDialog(MainActivity.this,
                    new DatePickerDialog.OnDateSetListener() {
                        @SuppressLint("SetTextI18n")
                        @Override
                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                            date.setText((dataformat(monthOfYear+1)) + "月" + dataformat(dayOfMonth)+"日");
                            nowDateTime = year + "-" + (dataformat(monthOfYear+1)) + "-" + dataformat(dayOfMonth);
                            scheduleListMorning.clear();
                            scheduleListMorning.addAll(query(1));
                            morningScheduleAdapter.notifyDataSetChanged();
                            scheduleListNoon.clear();
                            scheduleListNoon.addAll(query(2));
                            noonScheduleAdapter.notifyDataSetChanged();
                            scheduleListAfternoon.clear();
                            scheduleListAfternoon.addAll(query(3));
                            afternoonScheduleAdapter.notifyDataSetChanged();
                            scheduleListNight.clear();
                            scheduleListNight.addAll(query(4));
                            nightScheduleAdapter.notifyDataSetChanged();
                        }
                    },c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)).show();
            break;
        case R.id.loginOut:
            QQLogin.INSTANCE.gotoQQLogout(MainActivity.this);
            break;
    }
}

界面内组件绑定

private void bingView(){
    toolbar = findViewById(R.id.toolbar);
    navigationView = findViewById(R.id.navigationView);
    drawerLayout = findViewById(R.id.drawer_layout);
    addSchedule = findViewById(R.id.add_schedule);
    date_select = findViewById(R.id.date_select);
    date = findViewById(R.id.date);
    navigationViewLogin =  navigationView.getHeaderView(0).findViewById(R.id.floatActionButtonLogin);
    loginOut = navigationView.getHeaderView(0).findViewById(R.id.loginOut);
    loginState = navigationView.getHeaderView(0).findViewById(R.id.LoginStatue);
    textView1 = navigationView.getHeaderView(0).findViewById(R.id.textView1);
    //初始化未登录的登录情况
    preferences = getSharedPreferences("data",MODE_PRIVATE);
    loginStatus = preferences.getBoolean("loginStatus",false);
    navigationViewLogin.setImageBitmap(BitmapFactory.decodeFile("/storage/self/primary/Pictures/WeiXin/mmexport1593936099206.jpg"));
    if(loginStatus){
        loginState.setText(QQLogin.INSTANCE.getNickName());
        textView1.setText("");
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = getHttpBitmap("http://thirdqq.qlogo.cn/g?b=oidb&k=NSgvxXicLuHedhztS6gPhgA&s=100&t=1557060644");
                navigationViewLogin.setImageBitmap(bitmap);
            }
        }).start();
    }
    //设置头部的工具栏
    setSupportActionBar(toolbar);
    actionBar = getSupportActionBar();
    if(actionBar != null){
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
    //设置侧边栏
    navigationView.setCheckedItem(R.id.home);
    resource = getBaseContext().getResources();
    csl= resource.getColorStateList(R.color.navigation_menu_item_color);
    navigationView.setItemTextColor(csl);
    //日程表
    schedules_morning = findViewById(R.id.schedule_morning);
    schedules_noon = findViewById(R.id.schedule_noon);
    schedules_afternoon = findViewById(R.id.schedule_afternoon);
    schedules_night = findViewById(R.id.schedule_night);
    //获取数据库中的数据
    new initdatabase().execute();
}

获取QQ授权后设置用户的头像

public static Bitmap getHttpBitmap(String url) {
    URL myFileUrl = null;
    Bitmap bitmap = null;
    try {
        myFileUrl = new URL(url);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    try {
        HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
        conn.setConnectTimeout(0);
        conn.setDoInput(true);
        conn.connect();
        InputStream is = conn.getInputStream();
        bitmap = BitmapFactory.decodeStream(is);
        is.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bitmap;
}

构建日程的数据结构(builder设计模式)

public class ScheduleRecord {
    private String name;
    private String type;
    private String level;
    private String message;
    private String alarmClock;
    private ScheduleRecord(){}
    public static class scheduleRecordBuilder{
        ScheduleRecord scheduleRecord = new ScheduleRecord();
        public scheduleRecordBuilder basicInfo(String name, String type){
            scheduleRecord.name = name;
            scheduleRecord.type = type;
            return this;
        }
        public scheduleRecordBuilder level(String level){
            scheduleRecord.level = level;
            return this;
        }
        public scheduleRecordBuilder message(String message){
            scheduleRecord.message = message;
            return this;
        }
        public scheduleRecordBuilder alarmClock(String alarmClock){
            scheduleRecord.alarmClock = alarmClock;
            return this;
        }
        public ScheduleRecord build(){
            return scheduleRecord;
        }
    }

    public String getName() {
        return name;
    }

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

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getLevel() {
        return level;
    }

    public void setLevel(String level) {
        this.level = level;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getAlarmClock() {
        return alarmClock;
    }

    public void setAlarmClock(String alarmClock) {
        this.alarmClock = alarmClock;
    }
}

主界面的数据库

新建对应数据结构的数据库

public class MainActivityDataBase extends SQLiteOpenHelper {
    
    public MainActivityDataBase(Context context) {
        super(context,"mainActivityDataBase",null,1);
    }
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        //创建日程表格
        String sql = "CREATE TABLE schedules (\n" +
                "    name VARCHAR(20),\n" +
                //日程名称
                "    type VARCHAR(20),\n" +
                //日程类型
                "    level VARCHAR(20),\n" +
                //重要性
                "    message VARCHAR(20),\n" +
                //留言
                "    alarmClock DATETIME)";
                //闹钟时间
        sqLiteDatabase.execSQL(sql);
    }

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

    }
}

利用contentprovider访问数据库

public class MainActivityDataBase extends SQLiteOpenHelper {
    
    public MainActivityDataBase(Context context) {
        super(context,"mainActivityDataBase",null,1);
    }
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        //创建日程表格
        String sql = "CREATE TABLE schedules (\n" +
                "    name VARCHAR(20),\n" +
                //日程名称
                "    type VARCHAR(20),\n" +
                //日程类型
                "    level VARCHAR(20),\n" +
                //重要性
                "    message VARCHAR(20),\n" +
                //留言
                "    alarmClock DATETIME)";
                //闹钟时间
        sqLiteDatabase.execSQL(sql);
    }

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

    }
}

创建对应数据结构的适配器,并适配其适配器。同时为达到点击删除按钮进行删除,我采用更新数据库,以及修改对应的数据列表,来实现界面的实时更新
在这里插入图片描述

public class NewListAdapter extends ArrayAdapter<ScheduleRecord> {
    private int resourceId;
    private Context context;
    private SQLiteDatabase db;
    public NewListAdapter(Context context, int ViewResourceId, List<ScheduleRecord> objects, SQLiteDatabase db) {
        super(context,ViewResourceId,objects);
        resourceId = ViewResourceId;
        this.context = context;
        this.db = db;
    }
    @Nullable
    @Override
    public ScheduleRecord getItem(int position) {
        return super.getItem(position);
    }
    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        @SuppressLint("ViewHolder")
        ScheduleRecord sr = getItem(position);
        View view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
        TextView taskTime = view.findViewById(R.id.time);
        TextView name = view.findViewById(R.id.text_data);
        TextView level = view.findViewById(R.id.level);
        TextView type = view.findViewById(R.id.type);
        TextView theMessage = view.findViewById(R.id.theMessage);
        CheckBox check = view.findViewById(R.id.check);

        taskTime.setText(sr.getAlarmClock().substring(11));
        name.setText(sr.getName());
        level.setText(sr.getLevel());
        theMessage.setText(sr.getMessage());
        type.setText(sr.getType());
        check.setChecked(false);
        return view;
    }
}

新增一条日程-浮动窗口

private void initFloatingWindow(){
    if (permission()) {
        windowUtils = new WindowUtils();
        windowUtils.showPopupWindow(MainActivity.this);
    } else {
        requestAlertWindowPermission();
    }
}
//申请权限,跳转到系统的权限申请界面
private void requestAlertWindowPermission() {
    Intent intent = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
    }
    assert intent != null;
    intent.setData(Uri.parse("package:" + getPackageName()));
    startActivityForResult(intent, REQUEST_CODE);
}
public boolean permission(){
    //判断权限
    Boolean result = true;
    if (Build.VERSION.SDK_INT >= 23) {
        try {
            Class<Settings> clazz = Settings.class;
            Method canDrawOverlays;
            canDrawOverlays = clazz.getDeclaredMethod("canDrawOverlays", Context.class);
            result = (Boolean) canDrawOverlays.invoke(null, MainActivity.this);
        } catch (Exception e) {
            Log.e("TAG", Log.getStackTraceString(e));
        }
    }
    return result;
}

浮动窗口类

class WindowUtils {
    private  View mView = null;
    private  WindowManager mWindowManager = null;
    private  Context mContext = null;
    Boolean isShown = false;
    void showPopupWindow(Context context) {
        if (isShown) {
            return;
        }
        isShown = true;
        mContext = context;
        mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        mView = setUpView(context);
        final WindowManager.LayoutParams params = new WindowManager.LayoutParams();
        params.type = WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL;
        params.format = PixelFormat.TRANSLUCENT;
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = WindowManager.LayoutParams.MATCH_PARENT;
        params.gravity = Gravity.CENTER;
        mWindowManager.addView(mView, params);
    }
    void hidePopupWindow() {
        if (isShown && null != mView) {
            mWindowManager.removeView(mView);
            isShown = false;
        }
    }
    private  View setUpView(final Context context) {
        @SuppressLint("InflateParams") View view = LayoutInflater.from(context).inflate(R.layout.popupwindow, null);
        ImageView dateValueBtn = (ImageView) view.findViewById(R.id.content6);
        ImageView timeValueBtn = (ImageView) view.findViewById(R.id.content7);
        Button positiveBtn = (Button) view.findViewById(R.id.positiveBtn);
        Button negativeBtn = (Button) view.findViewById(R.id.negativeBtn);
        final TextView dateValue = (TextView)view.findViewById(R.id.dateValue);
        final TextView timeValue = (TextView)view.findViewById(R.id.timeValue);
        final EditText edit1 = (EditText) view.findViewById(R.id.edit1);
        final MyGridView icon_group = (MyGridView) view.findViewById(R.id.icon_group);
        final EditText edit3 = (EditText) view.findViewById(R.id.edit3);
        final MyGridView level_group = (MyGridView) view.findViewById(R.id.level_group);

        icon_group.setNumColumns(5);
        icon_group.setAdapter(new GridImageAdapter(MainActivity.this,listicon,listname));
        icon_group.setChoiceMode(GridView.CHOICE_MODE_SINGLE);
        icon_group.setItemChecked(0,true);
        icon_group.setSelection(0);
        position[0] = 0;
        icon_group.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position1, long id) {
                view.setSelected(true);
                position[0] = position1;
            }
        });

        level_group.setNumColumns(5);
        level_group.setAdapter(new GridImageAdapter(MainActivity.this,listicon2,list_English_name2));
        level_group.setChoiceMode(GridView.CHOICE_MODE_SINGLE);
        level_group.setItemChecked(0,true);
        level_group.setSelection(0);
        position2[0] = 0;
        level_group.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position1, long id) {
                view.setSelected(true);
                position2[0] = position1;
            }
        });

        dateValueBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar c = Calendar.getInstance();
                new DatePickerDialog(context,
                        new DatePickerDialog.OnDateSetListener() {
                            @SuppressLint("SetTextI18n")
                            @Override
                            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                                dateValue.setText(year + "-" + (dataformat(monthOfYear+1)) + "-" + dataformat(dayOfMonth));
                            }
                        },c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)).show();
            }
        });
        timeValueBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar c = Calendar.getInstance();
                new TimePickerDialog(context,
                        new TimePickerDialog.OnTimeSetListener() {
                            @SuppressLint("SetTextI18n")
                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                timeValue.setText(dataformat(hourOfDay) + ":" + dataformat(minute)+":00");
                            }
                        },c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true).show();
            }
        });
        positiveBtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
            String name = edit1.getText().toString();
            String type = list_English_name2[position[0]];
            String message = edit3.getText().toString();
            String level = list_English_name2[position2[0]];
            String dateTime = dateValue.getText().toString()+" "+timeValue.getText().toString();
            SQLiteDatabase db = mainActivityDatabase.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put("name",name);
            values.put("type", type);
            values.put("level",level);
            values.put("message",message);
            values.put("alarmClock",dateTime);
            db.insert("schedules", null, values);

            scheduleListMorning.clear();
            scheduleListNoon.clear();
            scheduleListAfternoon.clear();
            scheduleListNight.clear();

            scheduleListMorning.addAll(query(1));
            scheduleListNoon.addAll(query(2));
            scheduleListAfternoon.addAll(query(3));
            scheduleListNight.addAll(query(4));

            morningScheduleAdapter.notifyDataSetChanged();
            noonScheduleAdapter.notifyDataSetChanged();
            afternoonScheduleAdapter.notifyDataSetChanged();
            nightScheduleAdapter.notifyDataSetChanged();
            windowUtils.hidePopupWindow();
            }
        });
        negativeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                windowUtils.hidePopupWindow();
            }
        });
        final View popupWindowView = view.findViewById(R.id.popup_window);// 非透明的内容区域
        view.setOnTouchListener(new View.OnTouchListener() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int x = (int) event.getX();
                int y = (int) event.getY();
                Rect rect = new Rect();
                popupWindowView.getGlobalVisibleRect(rect);
                if (!rect.contains(x, y)) {
                    windowUtils.hidePopupWindow();
                }
                return false;
            }
        });
        view.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    windowUtils.hidePopupWindow();
                    return true;
                }
                return false;
            }
        });
        return view;
    }
}

浮动窗口界面的绘制

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_gravity="center"
    android:background="@color/color14"
    android:alpha="0.9"
    android:gravity="center"
    android:orientation="vertical">
    <RelativeLayout
        android:id="@+id/popup_window"
        android:layout_width="325dp"
        android:layout_height="600dp"
        android:alpha="0.8"
        android:background="@drawable/form"
        android:orientation="vertical" >
        <TextView
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:gravity="center"
            android:text="(•◡•) / 日程基本信息 \ (•◡•) /"
            android:textColor="#ffffff"
            android:textSize="19dp" />
        <View
            android:id="@+id/title_divider"
            android:layout_width="match_parent"
            android:layout_height="2dp"
            android:layout_below="@id/title"
            android:background="@color/black" />

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="35dp">
            <TextView
                android:id="@+id/content1"
                android:layout_width="wrap_content"
                android:layout_height="20dp"
                android:layout_marginTop="45dp"
                android:text="Key1: 日程名称"
                android:textColor="@color/black"
                android:textSize="14dp"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <EditText
                android:id="@+id/edit1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:hint="  get done some tasks......"
                android:textSize="12dp"
                android:layout_marginStart="5dp"
                app:layout_constraintHorizontal_bias="0.306"
                app:layout_constraintLeft_toRightOf="@+id/content1"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintBottom_toBottomOf="@id/content1"
                app:layout_constraintTop_toTopOf="@+id/content1" />

            <TextView
                android:id="@+id/content2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:text="Key-2: 选择该的日程类型"
                android:textColor="@color/black"
                android:textSize="14dp"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/edit1" />

            <com.example.time.myGridView.MyGridView
                android:id="@+id/icon_group"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:columnWidth="120dp"
                android:numColumns="auto_fit"
                android:padding="2dp"
                android:stretchMode="columnWidth"
                android:layout_marginTop="5dp"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/content2" />

            <TextView
                android:id="@+id/content3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Key-3: 日程的备注(可选*)"
                android:textColor="@color/black"
                android:textSize="14dp"
                android:layout_marginTop="10dp"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/icon_group"
                app:layout_constraintRight_toRightOf="parent"/>

            <EditText
                android:id="@+id/edit3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="  get done some tasks......"
                android:textSize="12dp"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/content3" />

            <TextView
                android:id="@+id/content4"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Key-4: 选择该日程的等级"
                android:textColor="@color/black"
                android:textSize="14dp"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@id/edit3"/>

            <com.example.time.myGridView.MyGridView
                android:id="@+id/level_group"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:columnWidth="140dp"
                android:numColumns="auto_fit"
                android:padding="2dp"
                android:stretchMode="columnWidth"
                android:layout_marginTop="5dp"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/content4" />

            <TextView
                android:id="@+id/content5"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Key-5: 选择该日程的日期的和时间"
                android:textColor="@color/black"
                android:layout_marginTop="7dp"
                android:textSize="14dp"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@id/level_group" />

            <ImageView
                android:id="@+id/content6"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_marginTop="12dp"
                android:src="@drawable/date"
                app:layout_constraintRight_toLeftOf="@id/dateValue"
                app:layout_constraintStart_toStartOf="@+id/content5"
                app:layout_constraintTop_toBottomOf="@+id/content5" />

            <TextView
                android:id="@+id/dateValue"
                android:layout_width="80dp"
                android:layout_height="20dp"
                android:layout_marginTop="10dp"
                android:layout_marginLeft="10dp"
                android:hint="date"
                app:layout_constraintBottom_toBottomOf="@id/content6"
                app:layout_constraintTop_toTopOf="@id/content6"
                app:layout_constraintVertical_bias="1.0"
                app:layout_constraintLeft_toRightOf="@+id/content6"
                tools:layout_editor_absoluteX="39dp" />

            <ImageView
                android:id="@+id/content7"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_marginStart="12dp"
                android:layout_marginTop="10dp"
                android:src="@drawable/time"
                app:layout_constraintBottom_toBottomOf="@+id/content6"
                app:layout_constraintStart_toEndOf="@+id/dateValue"
                app:layout_constraintTop_toBottomOf="@+id/content5"
                app:layout_constraintVertical_bias="1.0" />

            <TextView
                android:id="@+id/timeValue"
                android:layout_width="80dp"
                android:layout_height="20dp"
                android:layout_marginStart="12dp"
                android:hint="time"
                app:layout_constraintBottom_toBottomOf="@+id/content7"
                app:layout_constraintStart_toEndOf="@+id/content7"
                app:layout_constraintTop_toTopOf="@+id/content7" />
        </androidx.constraintlayout.widget.ConstraintLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:orientation="horizontal"
            android:paddingBottom="20dp"
            android:paddingLeft="20dp"
            android:paddingRight="20dp" >
            <Button
                android:id="@+id/negativeBtn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="@drawable/form"
                android:focusable="true"
                android:padding="5dp"
                android:text="no"
                android:textColor="@color/black"
                android:textSize="15dp" />
            <Button
                android:id="@+id/positiveBtn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="18dp"
                android:layout_weight="1"
                android:background="@drawable/form"
                android:focusable="true"
                android:padding="5dp"
                android:text="Yes"
                android:textColor="@color/black"
                android:textSize="15dp" />
        </LinearLayout>
    </RelativeLayout>

</LinearLayout>

RoundImageView类圆形头像

package com.example.time.circleImageView;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.ImageView;

import androidx.appcompat.widget.AppCompatImageView;

import com.example.time.R;

public class RoundImageView extends AppCompatImageView {

    private static final ScaleType SCALE_TYPE = ImageView.ScaleType.CENTER_CROP;

    private static final Bitmap.Config BITMAP_CONFIG = Bitmap.Config.ARGB_8888;
    private static final int COLOR_DRAWABLE_DIMENSION = 2;

    private static final int DEFAULT_BORDER_WIDTH = 0;
    private static final int DEFAULT_BORDER_COLOR = Color.BLACK;

    private final RectF mDrawableRect = new RectF();
    private final RectF mBorderRect = new RectF();

    private final Matrix mShaderMatrix = new Matrix();
    private final Paint mBitmapPaint = new Paint();
    private final Paint mBorderPaint = new Paint();

    private int mBorderColor = DEFAULT_BORDER_COLOR;
    private int mBorderWidth = DEFAULT_BORDER_WIDTH;

    private Bitmap mBitmap;
    private BitmapShader mBitmapShader;
    private int mBitmapWidth;
    private int mBitmapHeight;

    private float mDrawableRadius;
    private float mBorderRadius;

    private ColorFilter mColorFilter;

    private boolean mReady;
    private boolean mSetupPending;

    public RoundImageView(Context context) {
        super(context);

        init();
    }

    public RoundImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView, defStyle, 0);

        mBorderWidth = a.getDimensionPixelSize(R.styleable.CircleImageView_civ_border_width, DEFAULT_BORDER_WIDTH);
        mBorderColor = a.getColor(R.styleable.CircleImageView_civ_border_color, DEFAULT_BORDER_COLOR);

        a.recycle();

        init();
    }

    private void init() {
        super.setScaleType(SCALE_TYPE);
        mReady = true;

        if (mSetupPending) {
            setup();
            mSetupPending = false;
        }
    }

    @Override
    public ScaleType getScaleType() {
        return SCALE_TYPE;
    }

    @Override
    public void setScaleType(ScaleType scaleType) {
        if (scaleType != SCALE_TYPE) {
            throw new IllegalArgumentException(String.format("ScaleType %s not supported.", scaleType));
        }
    }

    @Override
    public void setAdjustViewBounds(boolean adjustViewBounds) {
        if (adjustViewBounds) {
            throw new IllegalArgumentException("adjustViewBounds not supported.");
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (getDrawable() == null) {
            return;
        }

        canvas.drawCircle(getWidth() / 2, getHeight() / 2, mDrawableRadius, mBitmapPaint);
        if (mBorderWidth != 0) {
            canvas.drawCircle(getWidth() / 2, getHeight() / 2, mBorderRadius, mBorderPaint);
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldW, int oldH) {
        super.onSizeChanged(w, h, oldW, oldH);
        setup();
    }

    public int getBorderColor() {
        return mBorderColor;
    }

    public void setBorderColor(int borderColor) {
        if (borderColor == mBorderColor) {
            return;
        }

        mBorderColor = borderColor;
        mBorderPaint.setColor(mBorderColor);
        invalidate();
    }

    public int getBorderWidth() {
        return mBorderWidth;
    }

    public void setBorderWidth(int borderWidth) {
        if (borderWidth == mBorderWidth) {
            return;
        }

        mBorderWidth = borderWidth;
        setup();
    }

    @Override
    public void setImageBitmap(Bitmap bm) {
        super.setImageBitmap(bm);
        mBitmap = bm;
        setup();
    }

    @Override
    public void setImageDrawable(Drawable drawable) {
        super.setImageDrawable(drawable);
        mBitmap = getBitmapFromDrawable(drawable);
        setup();
    }

    @Override
    public void setImageResource(int resId) {
        super.setImageResource(resId);
        mBitmap = getBitmapFromDrawable(getDrawable());
        setup();
    }

    @Override
    public void setImageURI(Uri uri) {
        super.setImageURI(uri);
        mBitmap = getBitmapFromDrawable(getDrawable());
        setup();
    }

    @Override
    public void setColorFilter(ColorFilter cf) {
        if (cf == mColorFilter) {
            return;
        }

        mColorFilter = cf;
        mBitmapPaint.setColorFilter(mColorFilter);
        invalidate();
    }

    private Bitmap getBitmapFromDrawable(Drawable drawable) {
        if (drawable == null) {
            return null;
        }

        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        try {
            Bitmap bitmap;

            if (drawable instanceof ColorDrawable) {
                bitmap = Bitmap.createBitmap(COLOR_DRAWABLE_DIMENSION, COLOR_DRAWABLE_DIMENSION, BITMAP_CONFIG);
            } else {
                bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), BITMAP_CONFIG);
            }

            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
            drawable.draw(canvas);
            return bitmap;
        } catch (OutOfMemoryError e) {
            return null;
        }
    }

    private void setup() {
        if (!mReady) {
            mSetupPending = true;
            return;
        }

        if (mBitmap == null) {
            return;
        }

        mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

        mBitmapPaint.setAntiAlias(true);
        mBitmapPaint.setShader(mBitmapShader);

        mBorderPaint.setStyle(Paint.Style.STROKE);
        mBorderPaint.setAntiAlias(true);
        mBorderPaint.setColor(mBorderColor);
        mBorderPaint.setStrokeWidth(mBorderWidth);

        mBitmapHeight = mBitmap.getHeight();
        mBitmapWidth = mBitmap.getWidth();

        mBorderRect.set(0, 0, getWidth(), getHeight());
        mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2, (mBorderRect.width() - mBorderWidth) / 2);

        mDrawableRect.set(mBorderWidth, mBorderWidth, mBorderRect.width() - mBorderWidth, mBorderRect.height() - mBorderWidth);
        mDrawableRadius = Math.min(mDrawableRect.height() / 2, mDrawableRect.width() / 2);

        updateShaderMatrix();
        invalidate();
    }

    private void updateShaderMatrix() {
        float scale;
        float dx = 0;
        float dy = 0;

        mShaderMatrix.set(null);

        if (mBitmapWidth * mDrawableRect.height() > mDrawableRect.width() * mBitmapHeight) {
            scale = mDrawableRect.height() / mBitmapHeight;
            dx = (mDrawableRect.width() - mBitmapWidth * scale) * 0.5f;
        } else {
            scale = mDrawableRect.width() / mBitmapWidth;
            dy = (mDrawableRect.height() - mBitmapHeight * scale) * 0.5f;
        }

        mShaderMatrix.setScale(scale, scale);
        mShaderMatrix.postTranslate((int) (dx + 0.5f) + mBorderWidth, (int) (dy + 0.5f) + mBorderWidth);

        mBitmapShader.setLocalMatrix(mShaderMatrix);
    }

}

设置contentprovider访问数据库

public class scheduleProvider extends ContentProvider {
    private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
    static {
        matcher.addURI("com.example.time.contentProvider.scheduleProvider","/schedules",1);
        matcher.addURI("com.example.time.contentProvider.scheduleProvider","/schedules/#",2);
    }
    private MainActivityDataBase mainActivityDataBase;

    @Override
    public boolean onCreate() {
        Log.e("TAG","scheduleProvider onCreate()");
        mainActivityDataBase = new MainActivityDataBase(getContext());
        return false;
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        Log.e("TAG","scheduleProvider query()");
        //得到链接对象
        SQLiteDatabase database = mainActivityDataBase.getReadableDatabase();
        int code = matcher.match(uri);
        if(code==1){
            //不跟据id进行查询
            Cursor cursor = database.query("schedules",projection,selection,selectionArgs,null,null,sortOrder);
            return cursor;
        }else if(code==2){
            //根据id进行查询
            long id = ContentUris.parseId(uri);
            Cursor cursor;
            cursor = database.query("schedules",projection,null,null,null,null,null);;
            return cursor;
        }else{
            throw new RuntimeException("查询的uri不合法");
        }
    }

    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        Log.e("TAG","scheduleProvider getType()");
        return null;
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
        Log.e("TAG","scheduleProvider insert()");
        return null;
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String s, @Nullable String[] strings) {
        Log.e("TAG","scheduleProvider delete()");
        return 0;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s, @Nullable String[] strings) {
        Log.e("TAG","scheduleProvider update()");
        return 0;
    }
}

闹钟提醒

public enum AlarmClock {
    INSTANCE;
    public void createAlarm(Context context, String message, int hour, int minutes, int resId) {
        ArrayList<Integer> testDays = new ArrayList<>();
//        testDays.add(Calendar.MONDAY);//周一
        String packageName = context.getPackageName();
        Uri ringtoneUri = Uri.parse("android.resource://" + packageName + "/" + resId);

        Intent intent = new Intent(android.provider.AlarmClock.ACTION_SET_ALARM)
                //闹钟的小时
                .putExtra(android.provider.AlarmClock.EXTRA_HOUR, hour)
                //闹钟的分钟
                .putExtra(android.provider.AlarmClock.EXTRA_MINUTES, minutes)
                //响铃时提示的信息
                .putExtra(android.provider.AlarmClock.EXTRA_MESSAGE, message)
                //用于指定该闹铃触发时是否振动
                .putExtra(android.provider.AlarmClock.EXTRA_VIBRATE, true)
                //一个 content: URI,用于指定闹铃使用的铃声,也可指定 VALUE_RINGTONE_SILENT 以不使用铃声。
                //如需使用默认铃声,则无需指定此 extra。
                .putExtra(android.provider.AlarmClock.EXTRA_RINGTONE, ringtoneUri)
                //对于一次性闹铃,无需指定此 extra
                .putExtra(android.provider.AlarmClock.EXTRA_DAYS, testDays)
                //如果为true,则调用startActivity()不会进入手机的闹钟设置界面
                .putExtra(android.provider.AlarmClock.EXTRA_SKIP_UI, true);
        if(intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        }
    }
}

D、个人收支管理

界面展示

在这里插入图片描述

设计过程

构建数据结构

public class JiZhang_ShouRu_ZhiZhu_listview_Item_Message {
    private String name;
    private int imaged;
    private String money;
    private String time;

    public JiZhang_ShouRu_ZhiZhu_listview_Item_Message(String name, int imaged, String money, String time) {
        this.name = name;
        this.imaged = imaged;
        this.money = money;
        this.time = time;
    }

    public String getName() {
        return name;
    }

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

    public int getImaged() {
        return imaged;
    }

    public void setImaged(int imaged) {
        this.imaged = imaged;
    }

    public String getMoney() {
        return money;
    }

    public void setMoney(String money) {
        this.money = money;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }
}

存放数据的列表

private List<JiZhang_ShouRu_ZhiZhu_listview_Item_Message> ShouRuList = new ArrayList<>();
private List<JiZhang_ShouRu_ZhiZhu_listview_Item_Message> ZhiChuList = new ArrayList<>();

构造适配器

public class JiZhang_ShouRu_ZhiZhu_listView_Item_Adapter extends ArrayAdapter<JiZhang_ShouRu_ZhiZhu_listview_Item_Message> {
    private int resourceId;
    public JiZhang_ShouRu_ZhiZhu_listView_Item_Adapter(Context context, int ViewResourceId, List<JiZhang_ShouRu_ZhiZhu_listview_Item_Message> objects){
        super(context,ViewResourceId,objects);
        resourceId = ViewResourceId;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        JiZhang_ShouRu_ZhiZhu_listview_Item_Message lm = getItem(position);
        View view = LayoutInflater.from(getContext()).inflate(this.resourceId,parent,false);
        ImageView listviewImage = view.findViewById(R.id.listview_item_image);
        TextView listviewName = view.findViewById(R.id.listview_item_name);
        TextView listviewMoney = view.findViewById(R.id.listview_item_money);
        TextView listviewTime = view.findViewById(R.id.listview_item_time);

        if (lm != null) {
            listviewImage.setImageResource(lm.getImaged());
            listviewName.setText(lm.getName());
            listviewMoney.setText(lm.getMoney());
            listviewTime.setText((lm.getTime()));
        }
        return view;
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JDllaHhc-1647067869934)(C:\Users\26225\AppData\Roaming\Typora\typora-user-images\image-20200714133454754.png)]

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/budget_bg"
        android:alpha="0.4"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent"/>
    <TextView
        android:id="@+id/textview4"
        android:layout_width="match_parent"
        android:layout_height="118dp"
        android:layout_gravity="center"
        android:background="@color/color1"
        android:gravity="center"
        android:paddingTop="35dp"
        android:text="0.0"
        android:alpha="0.8"
        android:textColor="@color/black"
        android:textSize="57dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0"/>
    <TextView
        android:id="@+id/textview3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="本月余额 (元)"
        android:textColor="@color/black"
        android:textSize="10dp"
        android:gravity="center"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="@id/textview4"
        app:layout_constraintVertical_bias="0.15"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>
    <TextView
        android:id="@+id/textview5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/morning_bg"
        android:padding="8dp"
        android:alpha="0.8"
        android:text="收入"
        android:paddingLeft="30dp"
        android:textColor="@color/black"
        android:textSize="15dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/textview4"
        app:layout_constraintVertical_bias="0"/>
    <ListView
        android:id="@+id/list_view1"
        android:layout_width="match_parent"
        android:layout_height="160dp"
        android:textColor="@color/black"
        android:alpha="0.7"
        android:background="@color/white"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/textview5"
        app:layout_constraintVertical_bias="0" />
    <TextView
        android:id="@+id/textview6"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/morning_bg"
        android:padding="8dp"
        android:paddingLeft="30dp"
        android:text="支出"
        android:alpha="0.8"
        android:textColor="@color/black"
        android:textSize="15dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/list_view1"
        app:layout_constraintVertical_bias="0.0"/>

    <ListView
        android:id="@+id/list_view2"
        android:layout_width="match_parent"
        android:layout_height="320dp"
        android:textColor="@color/black"
        android:alpha="0.7"
        android:background="@color/white"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/textview6" />
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/add_record"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroundTint="@color/mainTextColor"
        android:src="@drawable/shandian"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.861"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.779" />
</androidx.constraintlayout.widget.ConstraintLayout>

E、日程管理

创建数据库

public class MainActivityDataBase extends SQLiteOpenHelper {
    
    public MainActivityDataBase(Context context) {
        super(context,"mainActivityDataBase",null,1);
    }
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        //创建日程表格
        String sql = "CREATE TABLE schedules (\n" +
                "    name VARCHAR(20),\n" +
                //日程名称
                "    type VARCHAR(20),\n" +
                //日程类型
                "    level VARCHAR(20),\n" +
                //重要性
                "    message VARCHAR(20),\n" +
                //留言
                "    datetime DATETIME,\n"+
                //日程时间
                "    alarmClock DATETIME,\n"+
                "    alarmClockOpen DATETIME,\n"+
                //闹钟时间
                "    location VARCHAR(20),\n"+
                "    locationOpen VARCHAR(20),\n"+
                //日程地点
                "    photo blob)";
                //图片
        sqLiteDatabase.execSQL(sql);
    }

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

    }
}

双击返回键退出

/**双击返回键退出*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        if (mIsExit) {
            this.finish();
        } else {
            Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mIsExit = true;
            new Handler().postDelayed(() -> mIsExit = false, 2000);
        }
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

重写主线程的函数

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    return resideMenu.dispatchTouchEvent(ev);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_CODE) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(this)) {
            }
        }
    }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.tool_bar,menu);//加载menu布局
    return true;
}
@Override
public boolean onMenuItemClick(MenuItem item) {
    switch (item.getItemId()){
        case  R.id.action_search:
            Toast.makeText(MainActivity.this,"action_search",Toast.LENGTH_SHORT).show();
            break;
    }
    return true;
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()){
        case R.id.beifen:
            MySQLDB.INSTANCE.upLoadData(MainActivity.this);
            Toast.makeText(MainActivity.this,"beifen",Toast.LENGTH_LONG).show();
            break;
        case R.id.recover:
            MySQLDB.INSTANCE.downLoadData(MainActivity.this);
            Toast.makeText(MainActivity.this,"已更新! 请重新选择日期",Toast.LENGTH_LONG).show();
            break;
        case R.id.download:
            Toast.makeText(MainActivity.this,"download",Toast.LENGTH_LONG).show();
            break;
        case R.id.close:
            drawerLayout.closeDrawer(GravityCompat.START);
            break;
        case R.id.setting:
            Intent intent = new Intent(MainActivity.this, SettingActivity.class);
            startActivity(intent);
            break;
    }
    drawerLayout.closeDrawers();
    return true;
}
@Override
public void onClick(View view) {
    switch(view.getId()){
        case R.id.add_schedule:
            initFloatingWindow();
            break;
        case R.id.floatActionButtonLogin:
            if(loginStatus){
                Toast.makeText(MainActivity.this,"已登录",Toast.LENGTH_LONG).show();
            }else{
                Intent mainIntent = new Intent(MainActivity.this,LoginActivity.class);
                startActivity(mainIntent);
                finish();
            }
            break;
        case R.id.date_select:
            Calendar c = Calendar.getInstance();
            new DatePickerDialog(MainActivity.this,
                    (view1, year, monthOfYear, dayOfMonth) -> {
                        date.setText((dataformat(monthOfYear+1)) + "月" + dataformat(dayOfMonth)+"日");
                        nowDateTime = year + "-" + (dataformat(monthOfYear+1)) + "-" + dataformat(dayOfMonth);
                        scheduleListMorning.clear();
                        scheduleListMorning.addAll(query(1));
                        morningScheduleAdapter.notifyDataSetChanged();
                        scheduleListNoon.clear();
                        scheduleListNoon.addAll(query(2));
                        noonScheduleAdapter.notifyDataSetChanged();
                        scheduleListAfternoon.clear();
                        scheduleListAfternoon.addAll(query(3));
                        afternoonScheduleAdapter.notifyDataSetChanged();
                        scheduleListNight.clear();
                        scheduleListNight.addAll(query(4));
                        nightScheduleAdapter.notifyDataSetChanged();
                    },c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)).show();
            break;
        case R.id.loginOut:
            QQLogin.INSTANCE.gotoQQLogout(MainActivity.this);
            break;
    }
}

绑定组件

private void bingView(){
    toolbar = findViewById(R.id.toolbar);
    navigationView = findViewById(R.id.navigationView);
    drawerLayout = findViewById(R.id.drawer_layout);
    addSchedule = findViewById(R.id.add_schedule);
    date_select = findViewById(R.id.date_select);
    date = findViewById(R.id.date);
    navigationViewLogin =  navigationView.getHeaderView(0).findViewById(R.id.floatActionButtonLogin);
    loginOut = navigationView.getHeaderView(0).findViewById(R.id.loginOut);
    loginState = navigationView.getHeaderView(0).findViewById(R.id.LoginStatue);
    textView1 = navigationView.getHeaderView(0).findViewById(R.id.textView1);
    //初始化未登录的登录情况
    preferences = getSharedPreferences("data",MODE_PRIVATE);
    loginStatus = preferences.getBoolean("loginStatus",false);
    navigationViewLogin.setImageBitmap(BitmapFactory.decodeFile("/storage/self/primary/Pictures/WeiXin/mmexport1593936099206.jpg"));
    if(loginStatus){
        loginState.setText(QQLogin.INSTANCE.getNickName());
        textView1.setText("");
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = getHttpBitmap("http://thirdqq.qlogo.cn/g?b=oidb&k=NSgvxXicLuHedhztS6gPhgA&s=100&t=1557060644");
                navigationViewLogin.setImageBitmap(bitmap);
            }
        }).start();
    }
    //设置头部的工具栏
    setSupportActionBar(toolbar);
    actionBar = getSupportActionBar();
    if(actionBar != null){
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
    //设置侧边栏
    navigationView.setCheckedItem(R.id.home);
    resource = getBaseContext().getResources();
    csl= resource.getColorStateList(R.color.navigation_menu_item_color);
    navigationView.setItemTextColor(csl);
    //日程表
    schedules_morning = findViewById(R.id.schedule_morning);
    schedules_noon = findViewById(R.id.schedule_noon);
    schedules_afternoon = findViewById(R.id.schedule_afternoon);
    schedules_night = findViewById(R.id.schedule_night);
    //获取数据库中的数据
    new initdatabase().execute();
}

对日程设置上午、中午、下午、晚上的分类

public List<ScheduleRecord> query(int id){
    String begin=nowDateTime,end=nowDateTime;
    begin += " ";
    end += " ";
    if(id==1){
        begin += "00:00:00";
        end += "11:59:59";
    }else if(id == 2){
        begin += "12:00:00";
        end += "13:59:59";
    }else if(id == 3){
        begin += "14:00:00";
        end += "19:59:59";
    }else if (id == 4){
        //2020-01-01
        begin += "19:00:00";
        end += "23:59:59";
    }else{
        throw new RuntimeException("id不正确");
    }
    List<ScheduleRecord> list = new ArrayList<>();
    ContentResolver resolver = getContentResolver();
    Uri uri = Uri.parse("content://com.example.time.contentProvider.scheduleProvider/schedules");

    @SuppressLint("Recycle") Cursor cursor = resolver.query(uri,null,"datetime between ? and ?",new String[]{begin,end},null);
    assert cursor != null;
    while(cursor.moveToNext()){
        String name = cursor.getString(0);
        String type = cursor.getString(1);
        Log.i("TEST", type);
        String level = cursor.getString(2);
        String message = cursor.getString(3);
        String datetime = cursor.getString(4);
        String alarmClock = cursor.getString(5);
        int alarmClockOpen = cursor.getInt(6);
        String location = cursor.getString(7);
        int locationOpen = cursor.getInt(8);
        byte[] photo = cursor.getBlob(9);
        ScheduleRecord t = new ScheduleRecord.scheduleRecordBuilder()
                .basicInfo(name,type)
                .level(level)
                .message(message)
                .datetime(datetime)
                .alarmClock(alarmClock)
                .alarmClockOpen(alarmClockOpen)
                .location(location)
                .locationOpen(locationOpen)
                .photo(photo)
                .build();
        list.add(t);
    }
    return list;
}

Residemenu类侧边栏

private void setRightCeBianLan(){
    resideMenu = new ResideMenu(this);
    resideMenu.setBackground(R.drawable.main_activity_bg);
    resideMenu.attachToActivity(this);
    resideMenu.setScaleValue(0.67f);
    resideMenu.setSwipeDirectionDisable(ResideMenu.DIRECTION_LEFT);
    resideMenu.setShadowVisible(false);
    // create menu items;
    String[] titles = {"Home", "calendar", "alarm", "budget"};
    int[] icon = {R.drawable.home, R.drawable.calendar, R.drawable.alarm_clock, R.drawable.budget};
    //home点击
    ResideMenuItem home = new ResideMenuItem(this, icon[0], titles[0]);
    ResideMenuItem calendar = new ResideMenuItem(this, icon[1], titles[1]);
    ResideMenuItem alarm_clock = new ResideMenuItem(this, icon[2], titles[2]);
    ResideMenuItem budget = new ResideMenuItem(this, icon[3], titles[3]);

    home.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(MainActivity.this,"已在日程界面",Toast.LENGTH_LONG).show();
        }
    });
    calendar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(MainActivity.this,"1",Toast.LENGTH_LONG).show();
            Intent intent1 = new Intent(MainActivity.this, CalendarActivity.class);
            startActivity(intent1);
            finish();
        }
    });
    alarm_clock.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(MainActivity.this,"2",Toast.LENGTH_LONG).show();
            Intent intent1 = new Intent(MainActivity.this, AlarmClockActivity.class);
            startActivity(intent1);
            finish();
        }
    });
    budget.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(MainActivity.this,"3",Toast.LENGTH_LONG).show();
            Intent intent1 = new Intent(MainActivity.this, Activity_JiZhang.class);
            startActivity(intent1);
            finish();
        }
    });
    resideMenu.addMenuItem(home,ResideMenu.DIRECTION_RIGHT);
    resideMenu.addMenuItem(calendar,ResideMenu.DIRECTION_RIGHT);
    resideMenu.addMenuItem(alarm_clock,ResideMenu.DIRECTION_RIGHT);
    resideMenu.addMenuItem(budget,ResideMenu.DIRECTION_RIGHT);
    resideMenu.setMenuListener(menuListener);
}
private ResideMenu.OnMenuListener menuListener = new ResideMenu.OnMenuListener() {
    @Override
    public void openMenu() {
        Toast.makeText(MainActivity.this, "Menu is opened!", Toast.LENGTH_SHORT).show();
    }
    @Override
    public void closeMenu() {
        Toast.makeText(MainActivity.this, "Menu is closed!", Toast.LENGTH_SHORT).show();
    }
};

日程展示界面的设计

适配器NewListAdapter

public class NewListAdapter extends ArrayAdapter<ScheduleRecord> {
    private int resourceId;
    private Context context;
    private SQLiteDatabase db;
    public NewListAdapter(Context context, int ViewResourceId, List<ScheduleRecord> objects, SQLiteDatabase db) {
        super(context,ViewResourceId,objects);
        resourceId = ViewResourceId;
        this.context = context;
        this.db = db;
    }

    @Nullable
    @Override
    public ScheduleRecord getItem(int position) {
        return super.getItem(position);
    }
    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        @SuppressLint("ViewHolder") final ScheduleRecord sr = getItem(position);
        View view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
        final TextView taskTime = view.findViewById(R.id.time);
        final TextView name = view.findViewById(R.id.text_data);
        TextView level = view.findViewById(R.id.level);
        TextView type = view.findViewById(R.id.type);
        TextView theMessage = view.findViewById(R.id.theMessage);
        CheckBox check = view.findViewById(R.id.check);
        ImageView xiuGai =view.findViewById(R.id.xiuGai);

        taskTime.setText(sr.getDatetime().substring(11));
        name.setText(sr.getName());
        level.setText(sr.getLevel());
        theMessage.setText(sr.getMessage());
        type.setText(sr.getType());
        check.setChecked(false);
        xiuGai.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, ModifySchedule.class);
                intent.putExtra("name",name.getText().toString());
                intent.putExtra("datetime",sr.getDatetime());
                context.startActivity(intent);
            }
        });
        return view;
    }
}

不同日程的触发事件

schedules_morning.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    ((SwipeLayout)(schedules_morning.getChildAt(position - schedules_morning.getFirstVisiblePosition()))).open(true);
    final TextView name = view.findViewById(R.id.text_data);
    view.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(MainActivity.this,"you click it !!!",Toast.LENGTH_LONG).show();
            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(MainActivity.this);
            builder.setMessage("Are You Sure to Move This Record ?");
            builder.setNegativeButton("YES", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    db.execSQL("delete from schedules where name = ?",new String[]{name.getText().toString()});
                    scheduleListMorning.clear();
                    scheduleListMorning.addAll(query(1));
                    morningScheduleAdapter.notifyDataSetChanged();
                }
            });
            builder.setPositiveButton("NO",null);
            builder.create().show();
        }
    });
    }
});
schedules_noon.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    ((SwipeLayout)(schedules_noon.getChildAt(position - schedules_noon.getFirstVisiblePosition()))).open(true);
    final TextView name = view.findViewById(R.id.text_data);
    view.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(MainActivity.this,"you click it !!!",Toast.LENGTH_LONG).show();
            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(MainActivity.this);
            builder.setMessage("Are You Sure to Move This Record ?");
            builder.setNegativeButton("YES", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    db.execSQL("delete from schedules where name = ?",new String[]{name.getText().toString()});
                    scheduleListNoon.clear();
                    scheduleListNoon.addAll(query(1));
                    noonScheduleAdapter.notifyDataSetChanged();
                }
            });
            builder.setPositiveButton("NO",null);
            builder.create().show();
        }
    });
    }
});
schedules_afternoon.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    ((SwipeLayout)(schedules_afternoon.getChildAt(position - schedules_afternoon.getFirstVisiblePosition()))).open(true);
    final TextView name = view.findViewById(R.id.text_data);
    view.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(MainActivity.this,"you click it !!!",Toast.LENGTH_LONG).show();
            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(MainActivity.this);
            builder.setMessage("Are You Sure to Move This Record ?");
            builder.setNegativeButton("YES", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    db.execSQL("delete from schedules where name = ?",new String[]{name.getText().toString()});
                    scheduleListAfternoon.clear();
                    scheduleListAfternoon.addAll(query(1));
                    afternoonScheduleAdapter.notifyDataSetChanged();
                }
            });
            builder.setPositiveButton("NO",null);
            builder.create().show();
        }
    });
    }
});
schedules_night.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    ((SwipeLayout)(schedules_night.getChildAt(position - schedules_night.getFirstVisiblePosition()))).open(true);
    final TextView name = view.findViewById(R.id.text_data);
    view.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(MainActivity.this,"you click it !!!",Toast.LENGTH_LONG).show();
            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(MainActivity.this);
            builder.setMessage("Are You Sure to Move This Record ?");
            builder.setNegativeButton("YES", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    db.execSQL("delete from schedules where name = ?",new String[]{name.getText().toString()});
                    scheduleListNight.clear();
                    scheduleListNight.addAll(query(1));
                    nightScheduleAdapter.notifyDataSetChanged();
                }
            });
            builder.setPositiveButton("NO",null);
            builder.create().show();
        }
    });
    }
});

新增日程的功能

WindowUtils类浮动界面

class WindowUtils {
    private  View mView = null;
    private  WindowManager mWindowManager = null;
    private  Context mContext = null;
    Boolean isShown = false;
    void showPopupWindow(Context context) {
        if (isShown) {
            return;
        }
        isShown = true;
        mContext = context;
        mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        mView = setUpView(context);
        final WindowManager.LayoutParams params = new WindowManager.LayoutParams();
        params.type = WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL;
        params.format = PixelFormat.TRANSLUCENT;
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = WindowManager.LayoutParams.MATCH_PARENT;
        params.gravity = Gravity.CENTER;
        mWindowManager.addView(mView, params);
    }
    void hidePopupWindow() {
        if (isShown && null != mView) {
            mWindowManager.removeView(mView);
            isShown = false;
        }
    }
    private  View setUpView(final Context context) {
        @SuppressLint("InflateParams") View view = LayoutInflater.from(context).inflate(R.layout.popupwindow, null);
        ImageView dateValueBtn = (ImageView) view.findViewById(R.id.content6);
        ImageView timeValueBtn = (ImageView) view.findViewById(R.id.content7);
        Button positiveBtn = (Button) view.findViewById(R.id.positiveBtn);
        Button negativeBtn = (Button) view.findViewById(R.id.negativeBtn);
        final TextView dateValue = (TextView)view.findViewById(R.id.dateValue);
        final TextView timeValue = (TextView)view.findViewById(R.id.timeValue);
        final EditText edit1 = (EditText) view.findViewById(R.id.edit1);
        final MyGridView icon_group = (MyGridView) view.findViewById(R.id.icon_group);
        final EditText edit3 = (EditText) view.findViewById(R.id.edit3);
        final MyGridView level_group = (MyGridView) view.findViewById(R.id.level_group);

        icon_group.setNumColumns(5);
        icon_group.setAdapter(new GridImageAdapter(MainActivity.this,listicon,listname));
        icon_group.setChoiceMode(GridView.CHOICE_MODE_SINGLE);
        icon_group.setItemChecked(0,true);
        icon_group.setSelection(0);
        position[0] = 0;
        icon_group.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position1, long id) {
                view.setSelected(true);
                position[0] = position1;
            }
        });

        level_group.setNumColumns(5);
        level_group.setAdapter(new GridImageAdapter(MainActivity.this,listicon2,list_English_name2));
        level_group.setChoiceMode(GridView.CHOICE_MODE_SINGLE);
        level_group.setItemChecked(0,true);
        level_group.setSelection(0);
        position2[0] = 0;
        level_group.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position1, long id) {
                view.setSelected(true);
                position2[0] = position1;
            }
        });

        dateValueBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar c = Calendar.getInstance();
                new DatePickerDialog(context,
                        new DatePickerDialog.OnDateSetListener() {
                            @SuppressLint("SetTextI18n")
                            @Override
                            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                                dateValue.setText(year + "-" + (dataformat(monthOfYear+1)) + "-" + dataformat(dayOfMonth));
                            }
                        },c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)).show();
            }
        });
        timeValueBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar c = Calendar.getInstance();
                new TimePickerDialog(context,
                        new TimePickerDialog.OnTimeSetListener() {
                            @SuppressLint("SetTextI18n")
                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                timeValue.setText(dataformat(hourOfDay) + ":" + dataformat(minute)+":00");
                            }
                        },c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true).show();
            }
        });
        positiveBtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
            String name = edit1.getText().toString();
            String type = list_English_name[position[0]];
            String message = edit3.getText().toString();
            String level = list_English_name2[position2[0]];
            String dateTime = dateValue.getText().toString()+" "+timeValue.getText().toString();
            SQLiteDatabase db = mainActivityDatabase.getWritableDatabase();
            ContentValues values = new ContentValues();
            byte[] t = new byte[1];
            values.put("name",name);
            values.put("type", type);
            values.put("level",level);
            values.put("message",message);
            values.put("datetime",dateTime);
            values.put("alarmClock","");
            values.put("alarmClockOpen",0);
            values.put("location","");
            values.put("locationOpen",0);
            values.put("photo",t);
            db.insert("schedules", null, values);

            scheduleListMorning.clear();
            scheduleListNoon.clear();
            scheduleListAfternoon.clear();
            scheduleListNight.clear();

            scheduleListMorning.addAll(query(1));
            scheduleListNoon.addAll(query(2));
            scheduleListAfternoon.addAll(query(3));
            scheduleListNight.addAll(query(4));

            morningScheduleAdapter.notifyDataSetChanged();
            noonScheduleAdapter.notifyDataSetChanged();
            afternoonScheduleAdapter.notifyDataSetChanged();
            nightScheduleAdapter.notifyDataSetChanged();
            windowUtils.hidePopupWindow();
            }
        });
        negativeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                windowUtils.hidePopupWindow();
            }
        });
        final View popupWindowView = view.findViewById(R.id.popup_window);// 非透明的内容区域
        view.setOnTouchListener(new View.OnTouchListener() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int x = (int) event.getX();
                int y = (int) event.getY();
                Rect rect = new Rect();
                popupWindowView.getGlobalVisibleRect(rect);
                if (!rect.contains(x, y)) {
                    windowUtils.hidePopupWindow();
                }
                return false;
            }
        });
        view.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    windowUtils.hidePopupWindow();
                    return true;
                }
                return false;
            }
        });
        return view;
    }
}

权限及主界面的调用

private void initFloatingWindow(){
    if (permission()) {
        windowUtils = new WindowUtils();
        windowUtils.showPopupWindow(MainActivity.this);
    } else {
        requestAlertWindowPermission();
    }
}
//申请权限,跳转到系统的权限申请界面
private void requestAlertWindowPermission() {
    Intent intent = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
    }
    assert intent != null;
    intent.setData(Uri.parse("package:" + getPackageName()));
    startActivityForResult(intent, REQUEST_CODE);
}
public boolean permission(){
    //判断权限
    Boolean result = true;
    if (Build.VERSION.SDK_INT >= 23) {
        try {
            Class<Settings> clazz = Settings.class;
            Method canDrawOverlays;
            canDrawOverlays = clazz.getDeclaredMethod("canDrawOverlays", Context.class);
            result = (Boolean) canDrawOverlays.invoke(null, MainActivity.this);
        } catch (Exception e) {
            Log.e("TAG", Log.getStackTraceString(e));
        }
    }
    return result;
}

F、闹钟提醒

工具类-调用系统的闹钟

public enum AlarmClock {
    INSTANCE;
    public void createAlarm(Context context, String message, int hour, int minutes, int resId) {
        ArrayList<Integer> testDays = new ArrayList<>();
//        testDays.add(Calendar.MONDAY);//周一
        String packageName = context.getPackageName();
        Uri ringtoneUri = Uri.parse("android.resource://" + packageName + "/" + resId);

        Intent intent = new Intent(android.provider.AlarmClock.ACTION_SET_ALARM)
                //闹钟的小时
                .putExtra(android.provider.AlarmClock.EXTRA_HOUR, hour)
                //闹钟的分钟
                .putExtra(android.provider.AlarmClock.EXTRA_MINUTES, minutes)
                //响铃时提示的信息
                .putExtra(android.provider.AlarmClock.EXTRA_MESSAGE, message)
                //用于指定该闹铃触发时是否振动
                .putExtra(android.provider.AlarmClock.EXTRA_VIBRATE, true)
                //一个 content: URI,用于指定闹铃使用的铃声,也可指定 VALUE_RINGTONE_SILENT 以不使用铃声。
                //如需使用默认铃声,则无需指定此 extra。
                .putExtra(android.provider.AlarmClock.EXTRA_RINGTONE, ringtoneUri)
                //对于一次性闹铃,无需指定此 extra
                .putExtra(android.provider.AlarmClock.EXTRA_DAYS, testDays)
                //如果为true,则调用startActivity()不会进入手机的闹钟设置界面
                .putExtra(android.provider.AlarmClock.EXTRA_SKIP_UI, true);
        if(intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        }
    }
}

G、修改日程

点击事件(添加图片、添加地址、保存数据)

@Override
public void onClick(View view) {
    switch (view.getId()){
        case R.id.photoButton:
            openPhoto();
            break;
        case R.id.b2:
            islocationOpen = islocationOpen==0?1:0;
            gotoBDLocationActivity();
            break;
        case  R.id.b1:
            isalarmClockOpen = isalarmClockOpen==0?1:0;
            break;
        case R.id.go:
            saveTodataBase();
            finish();
            break;
    }
}

百度地图调用

private void gotoBDLocationActivity(){
    if(location.isChecked()){
        startActivityForResult(new Intent(this, BDLocationActivity.class), BDLocation_CODE);
    }
}

百度地图工具类

public class BDLocationActivity extends AppCompatActivity implements View.OnClickListener{
    public static int BDLocation_CANCEL = 1;
    public static int BDLocation_FINISH = 4;
    public static String location;
    private TextView tvPostion;
    private MapView mMapView = null;
    private BaiduMap mBaiduMap;
    private LocationClient mLocationClient;
    private boolean  isFirstLocate = true;
    private TextView tvCancel;
    private TextView tvFinish;

    StringBuilder  currentPosition;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_bdlocation);
        mMapView = (MapView) findViewById(R.id.mMapView);
        tvPostion = (TextView) findViewById(R.id.tvPostion);
        tvCancel = (TextView) findViewById(R.id.tvCancel);
        tvFinish = (TextView) findViewById(R.id.tvFinish);
        tvCancel.setOnClickListener(this);
        tvFinish.setOnClickListener(this);

        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mBaiduMap.setMyLocationEnabled(true);
        initLocation();
        List<String> permissionList = new ArrayList<>();
        if(ContextCompat.checkSelfPermission(BDLocationActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if(ContextCompat.checkSelfPermission(this,Manifest.permission.READ_PHONE_STATE)!=PackageManager.PERMISSION_GRANTED){
            permissionList.add(Manifest.permission.READ_PHONE_STATE);
        }
        if(ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if(!permissionList.isEmpty()){
            String[] permissions= permissionList.toArray(new String[permissionList.size()]);
            ActivityCompat.requestPermissions(BDLocationActivity.this,permissions,1);
        }else{
            requestLocation();
        }
    }
    private void initLocation() {
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.requestLocation();
        mLocationClient.registerNotifyLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(final BDLocation bdLocation) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        currentPosition =  new StringBuilder();
                        currentPosition.append("当前位置为").append(bdLocation.getCountry()).append(bdLocation.getProvince()).append(bdLocation.getCity()).append(bdLocation.getDistrict()).append(bdLocation.getStreet());
                        if(bdLocation.getLocType() == BDLocation.TypeGpsLocation ||bdLocation.getLocType() == BDLocation.TypeNetWorkLocation ||bdLocation.getLocType() == BDLocation.INDOOR_LOCATION_SOURCE_WIFI){
                            if(isFirstLocate){
                                LatLng ll = new LatLng(bdLocation.getLatitude(),bdLocation.getLongitude());
                                MapStatus.Builder builder = new MapStatus.Builder();
                                builder.target(ll).zoom(18.0f);
                                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                                isFirstLocate = false;
                            }
                            MyLocationData.Builder  locationBuilder = new MyLocationData.Builder();
                            locationBuilder.latitude(bdLocation.getLatitude());
                            locationBuilder.longitude(bdLocation.getLongitude());
                            MyLocationData locationData = locationBuilder.build();
                            mBaiduMap.setMyLocationData(locationData);
                        }
                        tvPostion.setText(currentPosition);
                        location = String.valueOf(currentPosition);
                    }
                });
            }
        });
    }
    private void requestLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setScanSpan(1000);
        option.setIsNeedAddress(true);
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setOpenAutoNotifyMode();
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1) {
            if (grantResults.length > 0) {
                for (int result : grantResults) {
                    if (result != PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(this, "必须同意所有的权限才能使用本程序", Toast.LENGTH_SHORT).show();
                        finish();
                        return;
                    }
                }
                requestLocation();
            } else {
                Toast.makeText(this, "发生了错误", Toast.LENGTH_SHORT).show();
            }
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stop();
        mMapView.onDestroy();
        mBaiduMap.setMyLocationEnabled(false);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvCancel:
                setResult(BDLocation_CANCEL);
                finish();
                break;
            case R.id.tvFinish:
                setResult(BDLocation_FINISH);
                finish();
                break;
        }
    }

}

打开拍照系统和手机存储的照片

private void openPhoto(){
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(intent, 1);
}

设置回调函数

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {// 选取图片的返回值
        if (resultCode == RESULT_OK) {
            Uri uri = data.getData();
            Cursor cursor = getContentResolver().query(uri, null, null, null, null);
            cursor.moveToFirst();// 指向查询结果的第一个位置
            String imgPath = cursor.getString(1); // 图片文件路径
            String imgSize = cursor.getString(2); // 图片大小
            String imgName = cursor.getString(3); // 图片文件名
            BitmapFactory.Options options = new BitmapFactory.Options();
            // 此时把options.inJustDecodeBounds 设回true,即只读边不读内容
            options.inJustDecodeBounds = true;
            // 默认是Bitmap.Config.ARGB_8888
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            try {
                //此时不会把图片读入内存,只会获取图片宽高等信息
                Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
                //上面一句和下面的类似
                //Bitmap bitmap = BitmapFactory.decodeFile(imgPath,options);
                int heitht = options.outHeight;
                // 根据需要设置压缩比例
                int size = heitht / 800;
                if (size <= 0) {
                    size = 2;
                }
               /*inSampleSize表示缩略图大小为原始图片大小的几分之一,
                  即如果这个值为2,则取出的缩略图的宽和高都是原始图片的1/2,
                  图片大小就为原始大小的1/4*/
                options.inSampleSize = size;
                // 设置options.inJustDecodeBounds重新设置为false
                options.inPurgeable = true;// 同时设置才会有效
                options.inInputShareable = true;//。当系统内存不够时候图片自动被回收
                options.inJustDecodeBounds = false;
                //此时图片会按比例压缩后被载入内存中
                bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
                SaveSD.saveBitmap(imgName,bitmap);//saveBitmap这个是我定义保存到SDcard中的方法
                ivSchedulePhoto.setImageBitmap(bitmap);
                imgPath="/sdcard/"+imgName;
                //将图片从Bitmap变为二进制流,保存到数据库中
                newPhoto = BitmapToByte.saveBitmap(bitmap);
                getNewPhoto = true;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
    if(requestCode==BDLocation_CODE){
        if(resultCode== BDLocationActivity.BDLocation_FINISH){
            textView.setText(BDLocationActivity.location);
        }
    }
}

存储至数据库

private void saveTodataBase(){
    String newAlarmClock,newLocation;
    MainActivityDataBase myDatabase = new MainActivityDataBase(ModifySchedule.this);
    SQLiteDatabase db = myDatabase.getWritableDatabase();
    if (b1.isChecked()){
        int hour = Integer.parseInt(alarm_clock_time_1.getText().toString());
        int minute = Integer.parseInt(alarm_clock_time_2.getText().toString());
        int second = Integer.parseInt(alarm_clock_time_3.getText().toString());
        AlarmClock.INSTANCE.createAlarm(ModifySchedule.this,sname,hour,minute,second);
        newAlarmClock = getAlarmClock(hour, minute, second);
        db.execSQL("update schedules set alarmClock = ?" +
                        "where name = ? and datetime = ?",
                new Object[]{newAlarmClock,sname,sdatetime});
    }
    if(location.isChecked()){
        newLocation = BDLocationActivity.location;
        db.execSQL("update schedules set location = ?" +
                        "where name = ? and datetime = ?",
                new Object[]{newLocation,sname,sdatetime});
    }
    if(getNewPhoto){
        db.execSQL("update schedules set photo = ?" +
                        "where name = ? and datetime = ?",
                new Object[]{newPhoto,sname,sdatetime});
    }
    db.execSQL("update schedules set alarmClockOpen = ?, locationOpen = ?" +
                    "where name = ? and datetime = ?",
            new Object[]{isalarmClockOpen,islocationOpen,sname,sdatetime});
    db.close();
}
private String getAlarmClock(int hour,int minute,int second){
    String s1 = hour<10?"0"+hour:hour+"";
    String s2 = minute<10?"0"+minute:minute+"";
    String s3 = second<10?"0"+second:second+"";
    return s1+s2+s3;
}

H、收支平台

public class Activity_JiZhang extends AppCompatActivity implements View.OnClickListener, Toolbar.OnMenuItemClickListener, NavigationView.OnNavigationItemSelectedListener {
    private FloatingActionButton add_record;
    private Toolbar toolbar;
    private NavigationView navigationView;
    private DrawerLayout drawerLayout;
    private RoundImageView navigationViewLogin;
    private TextView loginOut;
    private TextView loginState;
    private TextView textView1;
    private SharedPreferences preferences;
    private boolean loginStatus;
    private ActionBar actionBar;
    private Resources resource;
    private ColorStateList csl;
    private DrawerLayout drawer;
    private ResideMenu resideMenu;
    private boolean mIsExit;
    private List<JiZhang_ShouRu_ZhiZhu_listview_Item_Message> ShouRuList = new ArrayList<>();
    private List<JiZhang_ShouRu_ZhiZhu_listview_Item_Message> ZhiChuList = new ArrayList<>();
    private JiZhang_ShouRu_ZhiZhu_listView_Item_Adapter adapter1,adapter2;
    private ListView listView1,listView2;
    private TextView textview4;
    private DecimalFormat df;
    public static double allMoney = 0.00;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_budget);
        //界面绑定
        bingView();
        initListViewItem();
        setRightCeBianLan();
        addListener();
//        报告与线程及虚拟机相关的策略违例
        StrictMode.ThreadPolicy policy= null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            StrictMode.setThreadPolicy(policy);
        }
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                }
            }
        }
        if(ContextCompat.checkSelfPermission(Activity_JiZhang.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(Activity_JiZhang.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
        listView1 = findViewById(R.id.list_view1);
        listView2 = findViewById(R.id.list_view2);
        adapter1 = new JiZhang_ShouRu_ZhiZhu_listView_Item_Adapter(Activity_JiZhang.this,R.layout.shouru_listview_message_item,ShouRuList);
        adapter2 = new JiZhang_ShouRu_ZhiZhu_listView_Item_Adapter(Activity_JiZhang.this,R.layout.zhichu_listview_message_item,ZhiChuList);
        listView1.setAdapter(adapter1);
        listView2.setAdapter(adapter2);
        //设置ListView1和ListView2每项点击触发事件
        AdapterView.OnItemClickListener mMessageClickedHandlerListView1 = (parent, v, position, id) -> {
            if (id == 0) {
                Intent intent1 = new Intent(Activity_JiZhang.this, GongZuoShouRu.class);
                startActivity(intent1);
            }
        };
        listView1.setOnItemClickListener(mMessageClickedHandlerListView1);
        AdapterView.OnItemClickListener mMessageClickedHandlerListView2 = (parent, v, position, id) -> {
            if (id == 0) {
                Intent intent1 = new Intent(Activity_JiZhang.this, GongZuoShouRu.class);
                startActivity(intent1);
            }
        };
        listView2.setOnItemClickListener(mMessageClickedHandlerListView2);

        df = new DecimalFormat("#.00");
        textview4 = findViewById(R.id.textview4);
        textview4.setText(df.format(allMoney));
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.add_record:
                Intent intent1 = new Intent(Activity_JiZhang.this, ActivityJiYiBi.class);
                startActivityForResult(intent1,1);
                break;
            case R.id.loginOut:
                QQLogin.INSTANCE.gotoQQLogout(Activity_JiZhang.this);
                break;
            case R.id.floatActionButtonLogin:
                if(loginStatus){
                    Toast.makeText(Activity_JiZhang.this,"已登录",Toast.LENGTH_LONG).show();
                }else{
                    Intent mainIntent = new Intent(Activity_JiZhang.this,LoginActivity.class);
                    startActivity(mainIntent);
                    finish();
                }
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1) {
            if (requestCode == 1) {
                if (data != null) {
                    String name = data.getStringExtra("name");//2
                    String type = data.getStringExtra("type");//3
                    data.getStringExtra("time");//6
                    int costicon = data.getIntExtra("costicon",0);//int
                    double cost = data.getDoubleExtra("cost",0);//double
                    String costdate = data.getStringExtra("costdate");//5
                    data.getStringExtra("place");//7
                    data.getStringExtra("note");//9
                    data.getIntExtra("image",0);//int
                    JiZhang_ShouRu_ZhiZhu_listview_Item_Message lm = new JiZhang_ShouRu_ZhiZhu_listview_Item_Message(name,costicon,cost>0?("+"+cost):("-"+cost),costdate);
                    for(int i=0;i<ShouRuList.size();i++){
                        if (ShouRuList.get(i).getName().equals(type)){
                            double t = calculateMoney(ShouRuList.get(i))+calculateMoney(lm);
                            String money = t>0?"+"+t:"-"+t;
                            ShouRuList.get(i).setMoney(money);
                        }
                    }
                    adapter1.notifyDataSetChanged();
                    allMoney+=calculateMoney(lm);
                    textview4.setText(df.format(allMoney));
                }
            }
        }
    }
    private void bingView(){
        toolbar = findViewById(R.id.toolbar);
        add_record = findViewById(R.id.add_record);
        navigationView = findViewById(R.id.navigationView);
        navigationViewLogin =  navigationView.getHeaderView(0).findViewById(R.id.floatActionButtonLogin);
        loginOut = navigationView.getHeaderView(0).findViewById(R.id.loginOut);
        loginState = navigationView.getHeaderView(0).findViewById(R.id.LoginStatue);
        textView1 = navigationView.getHeaderView(0).findViewById(R.id.textView1);
        //初始化未登录的登录情况
        preferences = getSharedPreferences("data",MODE_PRIVATE);
        loginStatus = preferences.getBoolean("loginStatus",false);
        navigationViewLogin.setImageBitmap(BitmapFactory.decodeFile("/storage/self/primary/Pictures/WeiXin/mmexport1593936099206.jpg"));
        if(loginStatus){
            loginState.setText(QQLogin.INSTANCE.getNickName());
            textView1.setText("");
            new Thread(() -> {
                Bitmap bitmap = getHttpBitmap("http://thirdqq.qlogo.cn/g?b=oidb&k=NSgvxXicLuHedhztS6gPhgA&s=100&t=1557060644");
                navigationViewLogin.setImageBitmap(bitmap);
            }).start();
        }
        //设置头部的工具栏
        setSupportActionBar(toolbar);
        actionBar = getSupportActionBar();
        if(actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        //设置侧边栏
        navigationView.setCheckedItem(R.id.home);
        resource = getBaseContext().getResources();
        csl= resource.getColorStateList(R.color.navigation_menu_item_color);
        navigationView.setItemTextColor(csl);
        //侧边栏的按钮事件
        drawer = findViewById(R.id.drawer_layout);
    }
    private void setRightCeBianLan(){
        resideMenu = new ResideMenu(this);
        resideMenu.setBackground(R.drawable.main_activity_bg);
        resideMenu.attachToActivity(this);
        resideMenu.setScaleValue(0.67f);
        resideMenu.setSwipeDirectionDisable(ResideMenu.DIRECTION_LEFT);
        resideMenu.setShadowVisible(false);
        // create menu items;
        String[] titles = {"Home", "calendar", "alarm", "budget"};
        int[] icon = {R.drawable.home, R.drawable.calendar, R.drawable.alarm_clock, R.drawable.budget};
        //home点击
        ResideMenuItem home = new ResideMenuItem(this, icon[0], titles[0]);
        ResideMenuItem calendar = new ResideMenuItem(this, icon[1], titles[1]);
        ResideMenuItem alarm_clock = new ResideMenuItem(this, icon[2], titles[2]);
        ResideMenuItem budget = new ResideMenuItem(this, icon[3], titles[3]);

        home.setOnClickListener(view -> {
            Toast.makeText(Activity_JiZhang.this,"刷新成功",Toast.LENGTH_LONG).show();
            Intent intent1 = new Intent(Activity_JiZhang.this, MainActivity.class);
            startActivity(intent1);
            finish();
        });
        calendar.setOnClickListener(view -> {
            Toast.makeText(Activity_JiZhang.this,"1",Toast.LENGTH_LONG).show();
            Intent intent1 = new Intent(Activity_JiZhang.this, CalendarActivity.class);
            startActivity(intent1);
            finish();
        });
        alarm_clock.setOnClickListener(view -> {
            Toast.makeText(Activity_JiZhang.this,"2",Toast.LENGTH_LONG).show();
            Intent intent1 = new Intent(Activity_JiZhang.this, AlarmClockActivity.class);
            startActivity(intent1);
            finish();
        });
        budget.setOnClickListener(view -> Toast.makeText(Activity_JiZhang.this,"已在收支页面",Toast.LENGTH_LONG).show());
        resideMenu.addMenuItem(home,ResideMenu.DIRECTION_RIGHT);
        resideMenu.addMenuItem(calendar,ResideMenu.DIRECTION_RIGHT);
        resideMenu.addMenuItem(alarm_clock,ResideMenu.DIRECTION_RIGHT);
        resideMenu.addMenuItem(budget,ResideMenu.DIRECTION_RIGHT);
        resideMenu.setMenuListener(menuListener);
    }
    private void addListener(){
        toolbar.setOnMenuItemClickListener(this);
        navigationView.setNavigationItemSelectedListener(this);
        navigationViewLogin.setOnClickListener(this);
        resideMenu.setOnClickListener(this);
        loginOut.setOnClickListener(this);
        add_record.setOnClickListener(this);
    }
    private ResideMenu.OnMenuListener menuListener = new ResideMenu.OnMenuListener() {
        @Override
        public void openMenu() {
            Toast.makeText(Activity_JiZhang.this, "Menu is opened!", Toast.LENGTH_SHORT).show();
        }
        @Override
        public void closeMenu() {
            Toast.makeText(Activity_JiZhang.this, "Menu is closed!", Toast.LENGTH_SHORT).show();
        }
    };
    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()){
            case  R.id.action_search:
                Toast.makeText(Activity_JiZhang.this,"action_search",Toast.LENGTH_SHORT).show();
                break;
        }
        return true;
    }
    /**双击返回键退出*/
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mIsExit) {
                this.finish();
            } else {
                Toast.makeText(Activity_JiZhang.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mIsExit = true;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mIsExit = false;
                    }
                }, 2000);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.beifen:
                Toast.makeText(Activity_JiZhang.this,"beifen",Toast.LENGTH_LONG).show();
                break;
            case R.id.recover:
                Toast.makeText(Activity_JiZhang.this,"recover",Toast.LENGTH_LONG).show();
                break;
            case R.id.download:
                Toast.makeText(Activity_JiZhang.this,"download",Toast.LENGTH_LONG).show();
                break;
            case R.id.close:
                drawerLayout.closeDrawer(GravityCompat.START);
                break;
        }
        drawerLayout.closeDrawers();
        return true;
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return resideMenu.dispatchTouchEvent(ev);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.tool_bar,menu);
        return true;
    }
    private void initListViewItem(){
        JiZhang_ShouRu_ZhiZhu_listview_Item_Message lm1 = new JiZhang_ShouRu_ZhiZhu_listview_Item_Message("工作收入",R.drawable.work,"+4800.00","2019.10.21");
        JiZhang_ShouRu_ZhiZhu_listview_Item_Message lm2 = new JiZhang_ShouRu_ZhiZhu_listview_Item_Message("存款利息",R.drawable.bank,"+317.56","2019.10.24");
        JiZhang_ShouRu_ZhiZhu_listview_Item_Message lm3 = new JiZhang_ShouRu_ZhiZhu_listview_Item_Message("业绩奖金",R.drawable.award,"+700.00","2019.10.28");
        JiZhang_ShouRu_ZhiZhu_listview_Item_Message lm4 = new JiZhang_ShouRu_ZhiZhu_listview_Item_Message("长辈给与",R.drawable.family,"+3000.00","2019.10.29");
        ShouRuList.add(lm1);
        ShouRuList.add(lm2);
        ShouRuList.add(lm3);
        ShouRuList.add(lm4);
        JiZhang_ShouRu_ZhiZhu_listview_Item_Message lm5 = new JiZhang_ShouRu_ZhiZhu_listview_Item_Message("餐饮食品",R.drawable.food,"-200.70","2019.10.21");
        JiZhang_ShouRu_ZhiZhu_listview_Item_Message lm6 = new JiZhang_ShouRu_ZhiZhu_listview_Item_Message("衣服饰品",R.drawable.clothes,"-1020.50","2019.10.22");
        JiZhang_ShouRu_ZhiZhu_listview_Item_Message lm7 = new JiZhang_ShouRu_ZhiZhu_listview_Item_Message("行车交通",R.drawable.subway,"-213.40","2019.10.22");
        JiZhang_ShouRu_ZhiZhu_listview_Item_Message lm8 = new JiZhang_ShouRu_ZhiZhu_listview_Item_Message("电子设备",R.drawable.electric,"-1230.10","2019.10.24");
        JiZhang_ShouRu_ZhiZhu_listview_Item_Message lm9 = new JiZhang_ShouRu_ZhiZhu_listview_Item_Message("女友消费",R.drawable.girlfriend,"-1230.00","2019.10.25");
        JiZhang_ShouRu_ZhiZhu_listview_Item_Message lm10 = new JiZhang_ShouRu_ZhiZhu_listview_Item_Message("住宅装修",R.drawable.building,"-1210.50","2019.10.26");
        JiZhang_ShouRu_ZhiZhu_listview_Item_Message lm11 = new JiZhang_ShouRu_ZhiZhu_listview_Item_Message("身体健康",R.drawable.hospital,"-310.90","2019.10.27");
        ZhiChuList.add(lm5);
        ZhiChuList.add(lm6);
        ZhiChuList.add(lm7);
        ZhiChuList.add(lm8);
        ZhiChuList.add(lm9);
        ZhiChuList.add(lm10);
        ZhiChuList.add(lm11);

        allMoney+=calculateMoney(lm1);
        allMoney+=calculateMoney(lm2);
        allMoney+=calculateMoney(lm3);
        allMoney+=calculateMoney(lm4);
        allMoney+=calculateMoney(lm5);
        allMoney+=calculateMoney(lm6);
        allMoney+=calculateMoney(lm7);
        allMoney+=calculateMoney(lm8);
        allMoney+=calculateMoney(lm9);
        allMoney+=calculateMoney(lm10);
        allMoney+=calculateMoney(lm11);
    }
    private double calculateMoney(JiZhang_ShouRu_ZhiZhu_listview_Item_Message lm){
        double t = 0;
        if(lm.getMoney().substring(0,1).equals("+")){
            t+=(Double.valueOf(lm.getMoney().substring(1)));
        }else{
            t-=(Double.valueOf(lm.getMoney().substring(1)));
        }
        return t;
    }
}

新增一条记录

public class ActivityJiYiBi extends AppCompatActivity {
    private static final int OPEN_CANMER = 1;
    private RecycleViewAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ji_yi_bi);
        //授予权限
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(ActivityJiYiBi.this, Manifest.permission.CAMERA);
            if(checkCallPhonePermission != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(ActivityJiYiBi.this,new String[]{Manifest.permission.CAMERA},OPEN_CANMER);
                return;
            }
        }
        //设置标题栏
        Toolbar toolbar = (Toolbar)findViewById(R.id.jiyibi_toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if(actionBar!=null){
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        //设置recycleview
        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        adapter = new RecycleViewAdapter(ActivityJiYiBi.this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        //新增加一条记录
        Button button = findViewById(R.id.button_baocun);
        button.setOnClickListener(view -> {
            MyDatabase myDatabase = new MyDatabase(ActivityJiYiBi.this,"yiji_db",null,1);
            SQLiteDatabase db = myDatabase.getWritableDatabase();
            ContentValues values = new ContentValues();
            DataBaseItem dataBaseItem = adapter.getBaseItem();
            values.put("name",dataBaseItem.getName());//2
            values.put("type",dataBaseItem.getType());//3
            values.put("time",dataBaseItem.getTime());//6
            values.put("costicon",dataBaseItem.getCosticon());//1
            values.put("cost",dataBaseItem.getCost());//4
            values.put("costdate",dataBaseItem.getCostdate());//5
            values.put("place",dataBaseItem.getPlace());//7
            values.put("note",dataBaseItem.getNote());//9
            values.put("image",dataBaseItem.getImage());//8
            db.insert("yiji", null, values);

            Intent intent = new Intent();
            intent.putExtra("name",dataBaseItem.getName());//2
            intent.putExtra("type",dataBaseItem.getType());//3
            intent.putExtra("time",dataBaseItem.getTime());//6
            intent.putExtra("costicon",dataBaseItem.getCosticon());//1
            intent.putExtra("cost",dataBaseItem.getCost());//4
            intent.putExtra("costdate",dataBaseItem.getCostdate());//5
            intent.putExtra("place",dataBaseItem.getPlace());//7
            intent.putExtra("note",dataBaseItem.getNote());//9
            intent.putExtra("image",dataBaseItem.getImage());//8
            setResult(1, intent);
            finish();
        });
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                finish();
                break;
        }
        return true;
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case OPEN_CANMER:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(ActivityJiYiBi.this, "授权成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(ActivityJiYiBi.this, "相机权限禁用了, 请务必开启相机权", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}

记账的适配器

public class JiZhang_ShouRu_ZhiZhu_listView_Item_Adapter extends ArrayAdapter<JiZhang_ShouRu_ZhiZhu_listview_Item_Message> {
    private int resourceId;
    public JiZhang_ShouRu_ZhiZhu_listView_Item_Adapter(Context context, int ViewResourceId, List<JiZhang_ShouRu_ZhiZhu_listview_Item_Message> objects){
        super(context,ViewResourceId,objects);
        resourceId = ViewResourceId;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        JiZhang_ShouRu_ZhiZhu_listview_Item_Message lm = getItem(position);
        View view = LayoutInflater.from(getContext()).inflate(this.resourceId,parent,false);
        ImageView listviewImage = view.findViewById(R.id.listview_item_image);
        TextView listviewName = view.findViewById(R.id.listview_item_name);
        TextView listviewMoney = view.findViewById(R.id.listview_item_money);
        TextView listviewTime = view.findViewById(R.id.listview_item_time);

        if (lm != null) {
            listviewImage.setImageResource(lm.getImaged());
            listviewName.setText(lm.getName());
            listviewMoney.setText(lm.getMoney());
            listviewTime.setText((lm.getTime()));
        }
        return view;
    }
}

收支记录的数据结构

public class JiZhang_ShouRu_ZhiZhu_listview_Item_Message {
    private String name;
    private int imaged;
    private String money;
    private String time;

    public JiZhang_ShouRu_ZhiZhu_listview_Item_Message(String name, int imaged, String money, String time) {
        this.name = name;
        this.imaged = imaged;
        this.money = money;
        this.time = time;
    }

    public String getName() {
        return name;
    }

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

    public int getImaged() {
        return imaged;
    }

    public void setImaged(int imaged) {
        this.imaged = imaged;
    }

    public String getMoney() {
        return money;
    }

    public void setMoney(String money) {
        this.money = money;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

修改界面的适配器

public class M_RecycleViewAdapter extends  RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private DataBaseItem dataBaseItem;
    private Context context;
    public M_RecycleViewAdapter(Context context, DataBaseItem dataBaseItem) {
        super();
        this.context = context;
        this.dataBaseItem = dataBaseItem;
    }
    private enum M_ITEM_TYPE{
        firstfloor,
        secondfloor,
        thirdfloor,
        fouthfloor,
        fifthfloor,
        sixthfloor,
        seventhfloor
    }
    @Override
    public int getItemViewType(int position) {
        return M_JudgeType(position);
    }
    private int M_JudgeType(int position) {
        if (position == 0) {
            return M_ITEM_TYPE.firstfloor.ordinal();
        } else if (position == 1) {
            return M_ITEM_TYPE.secondfloor.ordinal();
        } else if (position == 2) {
            return M_ITEM_TYPE.thirdfloor.ordinal();
        } else if (position == 3) {
            return M_ITEM_TYPE.fouthfloor.ordinal();
        } else if (position == 4) {
            return M_ITEM_TYPE.fifthfloor.ordinal();
        } else if (position == 5) {
            return M_ITEM_TYPE.sixthfloor.ordinal();
        } else{
            return M_ITEM_TYPE.seventhfloor.ordinal();
        }
    }
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if(viewType==M_ITEM_TYPE.firstfloor.ordinal()){
            return new M_firstfloorViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.jiyibi_recycleview_item1, parent, false));
        }else if(viewType==M_ITEM_TYPE.secondfloor.ordinal()){
            return new M_secondfloorViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.jiyibi_recycleview_item2, parent, false));
        }else if(viewType==M_ITEM_TYPE.thirdfloor.ordinal()){
            return new M_thirdfloorViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.jiyibi_recycleview_item3, parent, false));
        }else if(viewType==M_ITEM_TYPE.fouthfloor.ordinal()){
            return new M_fouthfloorViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.jiyibi_recycleview_item4, parent, false));
        } else if(viewType==M_ITEM_TYPE.fifthfloor.ordinal()){
            return new M_fifthfloorViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.jiyibi_recycleview_item5, parent, false));
        }else if(viewType==M_ITEM_TYPE.sixthfloor.ordinal()){
            return new M_sixthfloorViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.jiyibi_recycleview_item6, parent, false));
        }else if(viewType==M_ITEM_TYPE.seventhfloor.ordinal()){
            return new M_sevenfloorViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.jiyibi_recycleview_item7, parent, false));
        }else{
            return null;
        }
    }

    @Override
    public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof M_firstfloorViewHolder) {
            ((M_firstfloorViewHolder) holder).leibie.setText("类被");
            ((M_firstfloorViewHolder) holder).image.setImageResource(R.drawable.wenhao);
            ((M_firstfloorViewHolder) holder).name.setText(dataBaseItem.getName());
            ((M_firstfloorViewHolder) holder).number.setText(String.valueOf(dataBaseItem.getCost()));
            ((M_firstfloorViewHolder) holder).number.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }
                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }
                @Override
                public void afterTextChanged(Editable editable) {
                    dataBaseItem.setCost(Double.valueOf(((M_firstfloorViewHolder) holder).number.getText().toString()));
                }
            });
            ((M_firstfloorViewHolder) holder).name.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }
                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }
                @Override
                public void afterTextChanged(Editable editable) {
                    dataBaseItem.setName(((M_firstfloorViewHolder) holder).name.getText().toString());
                }
            });
        }else if(holder instanceof M_secondfloorViewHolder) {
            ((M_secondfloorViewHolder) holder).b1.setText("支出");
            ((M_secondfloorViewHolder) holder).b2.setText("收入");
        }else if(holder instanceof M_thirdfloorViewHolder) {
            final int[] listicon = {dataBaseItem.getCosticon()};
            final String[] listname = {dataBaseItem.getType()};
            ((M_thirdfloorViewHolder) holder).icon_group.setNumColumns(1);
            ((M_thirdfloorViewHolder) holder).icon_group.setAdapter(new GridImageAdapter(context,listicon,listname));
            ((M_thirdfloorViewHolder) holder).icon_group.setChoiceMode(GridView.CHOICE_MODE_SINGLE);
            ((M_thirdfloorViewHolder) holder).icon_group.setItemChecked(0,true);
            ((M_thirdfloorViewHolder) holder).icon_group.setSelection(0);
        }else if(holder instanceof M_fouthfloorViewHolder) {
            ((M_fouthfloorViewHolder) holder).datavalue.setText(dataBaseItem.getCostdate());
            ((M_fouthfloorViewHolder) holder).timevalue.setText(dataBaseItem.getTime());
            ((M_fouthfloorViewHolder) holder).dataicon.setImageResource(R.drawable.timeclock);

            ((M_fouthfloorViewHolder) holder).datavalue.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Calendar c = Calendar.getInstance();
                    new DatePickerDialog(context,
                            new DatePickerDialog.OnDateSetListener() {
                                @Override
                                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                                    ((M_fouthfloorViewHolder) holder).datavalue.setText(year + "." + dataformat(monthOfYear) + "." + dataformat(dayOfMonth) + ".");
                                    dataBaseItem.setCostdate(year + "." + dataformat(monthOfYear) + "." + dataformat(dayOfMonth));
                                }
                            },c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)).show();
                }
            });
            ((M_fouthfloorViewHolder) holder).timevalue.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Calendar c = Calendar.getInstance();
                    new TimePickerDialog(context,
                            new TimePickerDialog.OnTimeSetListener() {
                                @Override
                                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                    ((M_fouthfloorViewHolder) holder).timevalue.setText(hourOfDay + ":" + dataformat(minute));
                                    dataBaseItem.setTime(hourOfDay + ":" + minute);
                                }
                            },c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true).show();
                }
            });

        }else if(holder instanceof M_fifthfloorViewHolder) {
            ((M_fifthfloorViewHolder) holder).dingwei.setImageResource(R.drawable.dingwei);
            ((M_fifthfloorViewHolder) holder).place.setText(dataBaseItem.getPlace());
            ((M_fifthfloorViewHolder) holder).place.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }
                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }
                @Override
                public void afterTextChanged(Editable editable) {
                    dataBaseItem.setPlace(((M_fifthfloorViewHolder) holder).place.getText().toString());
                }
            });
        }else if(holder instanceof M_sixthfloorViewHolder) {
            ((M_sixthfloorViewHolder) holder).sisflooricon.setImageResource(R.drawable.beizhu);
            ((M_sixthfloorViewHolder) holder).beizhu.setText(dataBaseItem.getNote());
            ((M_sixthfloorViewHolder) holder).beizhu.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }
                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }
                @Override
                public void afterTextChanged(Editable editable) {
                    dataBaseItem.setNote(((M_sixthfloorViewHolder) holder).beizhu.getText().toString());
                }
            });
        }else{
            ((M_sevenfloorViewHolder) holder).sevenflooricon.setImageResource(R.drawable.camera);
            ((M_sevenfloorViewHolder) holder).shangchuntupian.setText(R.string.shangchuantupianhuopaishezhaopian);
            dataBaseItem.setImage(dataBaseItem.getImage());
        }
    }

    @Override
    public int getItemCount() {
        return 7;
    }
    public static class M_firstfloorViewHolder extends RecyclerView.ViewHolder {
        TextView leibie;
        RoundImageView image;
        EditText number;
        EditText name;
        M_firstfloorViewHolder(@NonNull View view) {
            super(view);
            name = view.findViewById(R.id.data_name);
            leibie = view.findViewById(R.id.leibie);
            image = view.findViewById(R.id.firstfloorlogo);
            number = view.findViewById(R.id.number);
        }
    }
    public static class M_secondfloorViewHolder extends RecyclerView.ViewHolder {
        Button b1;
        Button b2;
        M_secondfloorViewHolder(@NonNull View view) {
            super(view);
            b1 = view.findViewById(R.id.jiyibi_zhichu);
            b2 = view.findViewById(R.id.jiyibi_shouru);
        }
    }
    public static class M_thirdfloorViewHolder extends RecyclerView.ViewHolder {
        MyGridView icon_group;
        M_thirdfloorViewHolder(@NonNull View view) {
            super(view);
            icon_group = view.findViewById(R.id.icon_group);
        }
    }
    public static class M_fouthfloorViewHolder extends RecyclerView.ViewHolder {
        ImageView dataicon;
        TextView datavalue;
        TextView timevalue;
        M_fouthfloorViewHolder(@NonNull View view) {
            super(view);
            dataicon = view.findViewById(R.id.dataicon);
            datavalue = view.findViewById(R.id.datavalue);
            timevalue = view.findViewById(R.id.timevalue);
        }
    }

    public static class M_fifthfloorViewHolder extends RecyclerView.ViewHolder {
        ImageView dingwei;
        EditText place;
        M_fifthfloorViewHolder(@NonNull View view) {
            super(view);
            dingwei = view.findViewById(R.id.dingwei);
            place = view.findViewById(R.id.item_place);
        }
    }
    public static class M_sixthfloorViewHolder extends RecyclerView.ViewHolder {
        ImageView sisflooricon;
        EditText beizhu;
        M_sixthfloorViewHolder(@NonNull View view) {
            super(view);
            sisflooricon = view.findViewById(R.id.sisflooricon);
            beizhu = view.findViewById(R.id.beizhu);
        }
    }
    public static class M_sevenfloorViewHolder extends RecyclerView.ViewHolder {
        ImageView sevenflooricon;
        TextView shangchuntupian;
        M_sevenfloorViewHolder(@NonNull View view) {
            super(view);
            sevenflooricon =  view.findViewById(R.id.sevenflooricon);
            shangchuntupian = view.findViewById(R.id.shangchuntupian);
        }
    }
    public static String dataformat(int num){
        if(num<10){
            return "0"+num;
        }
        return num+"";
    }
}

记账的修改功能

public class ModifDataBaseItemActivity extends AppCompatActivity {
    M_RecycleViewAdapter adapter;
    DataBaseItem dataBaseItem_orign;
    DataBaseItem dataBaseItem_new;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ji_yi_bi);
        Toolbar toolbar = (Toolbar)findViewById(R.id.jiyibi_toolbar);
        //设置标题栏
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if(actionBar!=null){
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        Intent intent = getIntent();
        String name = intent.getStringExtra("name");
        String type = intent.getStringExtra("type");
        String beizhu = intent.getStringExtra("note");
        String date = intent.getStringExtra("date");
        String time = intent.getStringExtra("time");
        double cost = intent.getDoubleExtra("cost",0);
        String costdate = intent.getStringExtra("costdate");
        String place = intent.getStringExtra("place");
        String note = intent.getStringExtra("note");
        int image = intent.getIntExtra("image",0);
        int costicon = intent.getIntExtra("costicon",0);

        Log.i("WYJ","here");

        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        dataBaseItem_orign = new DataBaseItem(name,type,time,costicon,cost,costdate,place,note,image);
        dataBaseItem_new = new DataBaseItem(name,type,time,costicon,cost,costdate,place,note,image);
        adapter = new M_RecycleViewAdapter(ModifDataBaseItemActivity.this,dataBaseItem_new);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);

        Button button = findViewById(R.id.button_baocun);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MyDatabase myDatabase = new MyDatabase(ModifDataBaseItemActivity.this,"yiji_db",null,1);
                SQLiteDatabase db = myDatabase.getWritableDatabase();
                db.execSQL("update yiji set note = ?,time = ?,cost = ?,costdate = ?,place = ?,name = ?" +
                                "where name = ? and type = ? and time = ? and cost = ? and costdate = ?",
                        new Object[]{dataBaseItem_new.getNote(),dataBaseItem_new.getTime(),dataBaseItem_new.getCost(),dataBaseItem_new.getCostdate(),dataBaseItem_new.getPlace(),dataBaseItem_new.getName(),
                                dataBaseItem_orign.getName(),dataBaseItem_orign.getType(),dataBaseItem_orign.getTime(),dataBaseItem_orign.getCost(),dataBaseItem_orign.getCostdate()});
                db.close();
                finish();
            }
        });
    }
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }
}

收入支出界面的适配器

public class ShouRuListView_Item_Adapter extends ArrayAdapter<DataBaseItem> {
    private int resourceId;
    private Context context;
    private SQLiteDatabase db;

    @Nullable
    @Override
    public DataBaseItem getItem(int position) {
        return super.getItem(position);
    }

    public ShouRuListView_Item_Adapter(Context context, int ViewResourceId, List<DataBaseItem> objects, SQLiteDatabase db){
        super(context,ViewResourceId,objects);
        resourceId = ViewResourceId;
        this.context = context;
        this.db = db;
    }
    @NonNull
    @Override
    public View getView(int position, View convertView, @NonNull ViewGroup parent){
        final DataBaseItem lm = getItem(position);
        @SuppressLint("ViewHolder") View view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);

        ImageView image = view.findViewById(R.id.item_image);
        ImageView costicon =  view.findViewById(R.id.item_icon);
        TextView name =  view.findViewById(R.id.item_name);
        TextView time =  view.findViewById(R.id.item_time);
        TextView cost = view.findViewById(R.id.item_cost);
        TextView costdate = view.findViewById(R.id.item_costdate);
        TextView place = view.findViewById(R.id.item_place);
        TextView note = view.findViewById(R.id.item_note);
        Button button_delete = view.findViewById(R.id.button_DeleteDataBaseItem);

        button_delete.setOnClickListener(view1 -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setMessage("您确定要移除这条记录吗?");
            builder.setNegativeButton("是的", (dialogInterface, i) -> db.execSQL("delete from yiji where name = ?",new String[]{lm.getName()}));
            builder.setPositiveButton("打扰了",null);
            builder.create().show();
            ShouRuListView_Item_Adapter.this.notifyDataSetChanged();
        });
        Button button_modif = view.findViewById(R.id.button_ModifDataBaseItem);
        button_modif.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i("WYJ","here");
                Intent intent = new Intent(context, ModifDataBaseItemActivity.class);
                intent.putExtra("name",lm.getName());
                intent.putExtra("type",lm.getType());
                intent.putExtra("note",lm.getNote());
                intent.putExtra("date",lm.getCostdate());
                intent.putExtra("time",lm.getTime());
                intent.putExtra("cost",lm.getCost());
                intent.putExtra("costdate",lm.getCostdate());
                intent.putExtra("place",lm.getPlace());
                intent.putExtra("note",lm.getNote());
                intent.putExtra("image",lm.getImage());
                intent.putExtra("costicon",lm.getCosticon());
                context.startActivity(intent);
            }
        });
        image.setImageResource(lm.getImage());
        costicon.setImageResource(lm.getCosticon());
        name.setText(lm.getName());
        time.setText(lm.getTime());
        cost.setText(String.valueOf( lm.getCost()));
        costdate.setText(lm.getCostdate());
        place.setText(lm.getPlace());
        note.setText(lm.getNote());
        return view;
    }
}

I、云端数据库的链接

public enum MySQLDB {
    INSTANCE;
    public void upLoadData(Context context){
        new Thread(() -> {
            try {
                //建立云数据库链接
                Class.forName("com.mysql.jdbc.Driver");
                String url = "jdbc:mysql://rm-bp183f2u68r6s15y30o.mysql.rds.aliyuncs.com:3306/mysqldatabase";
                String username = "mysqlwyj";
                String password = "admin123456";
                Connection connection = DriverManager.getConnection(url,username,password);

                //删除云端数据库并重新建立一个空表
                String sql = "DROP TABLE IF EXISTS test;\n" +
                        "CREATE TABLE `test` (\n" +
                        "  `name` varchar(20) NOT NULL,\n" +
                        "  `type` varchar(20) DEFAULT NULL,\n" +
                        "  `note` varchar(20) DEFAULT NULL,\n" +
                        "  `level` varchar(20) DEFAULT NULL,\n" +
                        "  `datetime` datetime DEFAULT NULL,\n" +
                        "  `alarmClock` datetime DEFAULT NULL,\n" +
                        "  `alarmClockOpen` int(11) DEFAULT NULL,\n" +
                        "  `location` varchar(40) DEFAULT NULL,\n" +
                        "  `locationOpen` int(11) DEFAULT NULL,\n" +
                        "  `photo` blob,\n" +
                        "  PRIMARY KEY (`name`)\n" +
                        ") ENGINE=InnoDB DEFAULT CHARSET=utf8;\n" +
                        "SELECT * FROM mysqldatabase.test;";
                PreparedStatement preparedStatement = connection.prepareStatement(sql);
                preparedStatement.executeQuery();
                //查询本地的数据库
                ContentResolver resolver = context.getContentResolver();
                Uri uri = Uri.parse("content://com.example.time.contentProvider.scheduleProvider/schedules");
                @SuppressLint("Recycle") Cursor cursor = resolver.query(uri,null,null,null,null);
                assert cursor != null;
                PreparedStatement preparedStatement2;
                String sql2 = "insert into `test` (name,type,note,level,datetime,alarmClock,alarmClockOpen,location,locationOpen,photo) values(?,?,?,?,?,?,?,?,?,?)";
                preparedStatement2 = connection.prepareStatement(sql2);
                while(cursor.moveToNext()){
                    String name = cursor.getString(0);
                    String type = cursor.getString(1);
                    String level = cursor.getString(2);
                    String message = cursor.getString(3);
                    String datetime = cursor.getString(4);
                    String alarmClock = cursor.getString(5);
                    int alarmClockOpen = cursor.getInt(6);
                    String location = cursor.getString(7);
                    int locationOpen = cursor.getInt(8);
                    byte[] photo = cursor.getBlob(9);
                    preparedStatement2.setString(1,name);
                    preparedStatement2.setString(2,type);
                    preparedStatement2.setString(3,message);
                    preparedStatement2.setString(4,level);
                    preparedStatement2.setString(5,datetime);
                    preparedStatement2.setString(6,alarmClock);
                    preparedStatement2.setInt(7,alarmClockOpen);
                    preparedStatement2.setString(8,location);
                    preparedStatement2.setInt(9,locationOpen);
                    //照片转换
                    Bitmap bmpout = BitmapFactory.decodeByteArray(photo, 0, photo.length);
                    byte[] bytesPhoto = BitmapToByte.saveBitmap(bmpout);
                    preparedStatement2.setBytes(10,bytesPhoto);
                    preparedStatement2.executeQuery();
                }
                preparedStatement2.close();
                preparedStatement.close();
                connection.close();
            } catch (SQLException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }).start();
    }
    public void downLoadData(Context context){
        new Thread(() -> {
            try {
                //建立数据库链接
                Class.forName("com.mysql.jdbc.Driver");
                String url = "jdbc:mysql://rm-bp183f2u68r6s15y30o.mysql.rds.aliyuncs.com:3306/mysqldatabase";
                String username = "mysqlwyj";
                String password = "admin123456";
                Connection connection = DriverManager.getConnection(url,username,password);

                String sql = "SELECT \n" +
                        "    name,\n" +
                        "    type,\n" +
                        "    note,\n" +
                        "    level,\n" +
                        "    datetime,\n" +
                        "    alarmClock,\n" +
                        "    alarmClockOpen,\n" +
                        "    location,\n" +
                        "    locationOpen,\n" +
                        "    photo\n" +
                        "FROM\n" +
                        "    mysqldatabase.test\n" +
                        "ORDER BY datetime";
                PreparedStatement preparedStatement = connection.prepareStatement(sql);
                ResultSet resultSet = preparedStatement.executeQuery();
                MainActivityDataBase mainActivityDatabase;
                mainActivityDatabase = new MainActivityDataBase(context);
                SQLiteDatabase db = mainActivityDatabase.getWritableDatabase();
                db.execSQL("DROP TABLE IF EXISTS `schedules`;");
                db.execSQL("CREATE TABLE schedules (\n" +
                        "    name VARCHAR(20),\n" +
                        "    type VARCHAR(20),\n" +
                        "    level VARCHAR(20),\n" +
                        "    message VARCHAR(20),\n" +
                        "    datetime DATETIME,\n"+
                        "    alarmClock DATETIME,\n"+
                        "    alarmClockOpen DATETIME,\n"+
                        "    location VARCHAR(20),\n"+
                        "    locationOpen VARCHAR(20),\n"+
                        "    photo blob)");
                while (resultSet.next()){
                    String name = resultSet.getString("name");
                    String type = resultSet.getString("type");
                    String message = resultSet.getString("note");
                    String level = resultSet.getString("level");
                    String datetime = resultSet.getString("datetime").substring(0,19);
                    String alarmClock = resultSet.getString("alarmClock");
                    int alarmClockOpen = resultSet.getInt("alarmClockOpen");
                    String location = resultSet.getString("location");
                    int locationOpen = resultSet.getInt("locationOpen");
                    Blob photo = resultSet.getBlob("photo");
                    db.execSQL("INSERT INTO `schedules` (`name`, `type`, `message`, `level`, `datetime`, `alarmClock`,`alarmClockOpen`,`location`,`locationOpen`,`photo`) " +
                            "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);",new Object[]{name,type,message,level,datetime,alarmClock,alarmClockOpen,location,locationOpen,photo});
                    Log.i("TESTDATABASE",name);
                    Log.i("TESTDATABASE",type);
                    Log.i("TESTDATABASE",message);
                    Log.i("TESTDATABASE",level);
                    Log.i("TESTDATABASE",datetime);
                    Log.i("TESTDATABASE",alarmClock);
                    Log.i("TESTDATABASE",alarmClockOpen+"");
                    Log.i("TESTDATABASE",location);
                    Log.i("TESTDATABASE",locationOpen+"");
                    Log.i("TESTDATABASE",String.valueOf(photo));
                }
                preparedStatement.close();
                connection.close();
            } catch (SQLException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sheng_er_sheng

打赏是什么?好吃么

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值