Android之简单记账功能Demo-----数据存储在本地

该Demo涉及到的知识点:SQLiteOpenHelper, ListView, AlertDialog,SharedPreferences等的使用,代码比较简单直接贴上:

1)主界面的两个Button 入口

package com.example.qz;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    public Intent intent;
    private Button btn1;
    private Button btn2;

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

    public void init() {
        btn1 = findViewById(R.id.button);
        btn2 = findViewById(R.id.button2);
        intent = new Intent();

    }

    //todo:记账点击事件
    public void btn1(View view) {
        intent.setClass(this,Qz.class);
        startActivity(intent);
    }

    //todo:流水点击事件
    public void btn2(View view) {
        intent.setClass(this,De.class);
        startActivity(intent);
    }

}

对应的xml布局文件为:





    

2)记账功能的Java代码为:

package com.example.qz;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

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

public class Qz extends AppCompatActivity {

    private Button clearbtn;
    private AlertDialog alertDialog;
    //类别
    private EditText editText;
    //金额
    private EditText editText1;
    //日期
    private EditText editText2;
    //说明
    private EditText editText3;

    private SqlLiteHelper sqlLiteHelper;

    private SharedPreferences sharedPreferences;
    private SharedPreferences commitSharePreference;
    private Context mContext;
    private final String items[] = {"食物", "衣服", "娱乐", "租金", "交通", "医疗", "其他"};
    private String qc_info = "qc_info";

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

    public void init() {
        clearbtn = findViewById(R.id.clearbtn);
        editText = findViewById(R.id.edit_text);
        sharedPreferences = getSharedPreferences("qz_value", MODE_PRIVATE);
        commitSharePreference = getSharedPreferences("commit", MODE_PRIVATE);
        editText.setText(sharedPreferences.getString("items", ""));
        editText.setFocusable(false);
        //金额,监听用户输入完成
        editText1 = findViewById(R.id.edit_text2);
        editText1.setInputType(EditorInfo.TYPE_CLASS_PHONE);
        //日期
        editText2 = findViewById(R.id.edit_text3);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        Date date = new Date(System.currentTimeMillis());
        editText2.setText(simpleDateFormat.format(date));
        editText2.setFocusable(false);
        editText2.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Toast.makeText(Qz.this, "默认日期,无需修改!", Toast.LENGTH_SHORT).show();
                return false;
            }
        });
        //说明
        editText3 = findViewById(R.id.edit_text4);
        //创建数据库的对象
        sqlLiteHelper = new SqlLiteHelper(Qz.this, "qz.db3", null, 1);
    }

    //单选框按钮
    public void clearbtn(View v) {

        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(Qz.this);
        alertBuilder.setTitle("类别");

        //点击选择之后把值存储在SP中
        alertBuilder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                editText.setText(items[which]);
                SharedPreferences.Editor edit = sharedPreferences.edit();
                edit.putString("items", items[which]);
                edit.commit();
            }
        });

        //设置点击事件
        alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                alertDialog.dismiss();
            }
        });
        alertDialog = alertBuilder.create();
        alertDialog.show();
    }

    //提交按钮点击事件
    public void commitbtn(View v) {
        String variety = editText.getText().toString();
        String total = editText1.getText().toString();
        String date = editText2.getText().toString();
        String description = editText3.getText().toString();

        //todo:金额如果超过即截取,否则默认输入的
        if (total != null && total.length() > 10) {
            Toast.makeText(Qz.this, "提交失败!数额过大,不允许超过10位!", Toast.LENGTH_LONG).show();
            editText1.setText("".trim());
        } else {
            ContentValues contentValues = new ContentValues();
            contentValues.put("variety", variety);
            contentValues.put("total", total);
            contentValues.put("date", date);
            contentValues.put("description", description);
            sqlLiteHelper.getReadableDatabase().insert(qc_info, null, contentValues);
            Toast.makeText(Qz.this, "提交成功", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (sqlLiteHelper != null) {
            sqlLiteHelper.close();
        }
    }
}

对应的xml布局为:




    
        
        

        

        


        
    

    

        

        
    



    

        

        
    



    
        

        
    

    


3)查看"流水"功能的Java代码为.:

package com.example.qz;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
public class De extends AppCompatActivity {
    private ListView listView;
    private LinearLayout l1;
    private SqlLiteHelper sqlLiteHelper;
    private String variety, total, date, description;
    private String qc_info = "qc_info";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_de);
        init();

    }
    private void init() {
        listView = findViewById(R.id.listview);
       // l1 = findViewById(R.id.linearLayout);
        listView.setAdapter(new MyAdapter(De.this));
        //todo:解决Scroview嵌套ListView只显示一行数据的问题
        //setListViewHeightBasedOnChildren(listView);
    }

/*    //todo:解决ScrollView嵌套ListView 之后只显示一行数据的BUG
    private void setListViewHeightBasedOnChildren(ListView listView) {

        ListAdapter adapter = listView.getAdapter();

        if(adapter == null){
            return;
        }

        int totalHeight = 0;

        for(int i = 0,len = adapter.getCount();i

适配ListView的Adapter类:

package com.example.qz;

import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MyAdapter extends BaseAdapter {

    private Context mContext;
    private LayoutInflater layoutInflater;
    private SqlLiteHelper sqlLiteHelper;
    private String qc_info = "qc_info";
    private static ArrayList list = null;
    Map map;
    static Cursor cursor;

    static List beanList;

    public MyAdapter(Context context) {
        super();
        mContext = context;
        layoutInflater = LayoutInflater.from(context);
        beanList = new ArrayList<>();
        sqlLiteHelper = new SqlLiteHelper(mContext, "qz.db3", null, 1);
        cursor = sqlLiteHelper.getReadableDatabase().query(qc_info, new String[]{"variety", "total", "date", "description"},
                null, null, null, null, null);
        query();
    }

    @Override
    public int getCount() {
        return beanList.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public int getItemViewType(int position) {
        return super.getItemViewType(position);
    }

    //todo:重点重写方法:getView()
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        final ViewHolder viewHolder;
        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.list_item, null);
            viewHolder = new ViewHolder();
            viewHolder.t1 = convertView.findViewById(R.id.t1);
            viewHolder.t2 = convertView.findViewById(R.id.t2);
            viewHolder.t3 = convertView.findViewById(R.id.t3);
            viewHolder.t4 = convertView.findViewById(R.id.t4);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        String total = null;
        String variety = null;
        String date = null;
        String description = null;
        while (cursor.moveToNext()) {
            variety = cursor.getString(cursor.getColumnIndex("variety"));
            total = cursor.getString(cursor.getColumnIndex("total"));
            date = cursor.getString(cursor.getColumnIndex("date"));
            description = cursor.getString(cursor.getColumnIndex("description"));
            MyBean bean = new MyBean(variety, total, date, description);
            beanList.add(bean);
        }
        cursor.close();

        MyBean myBean = beanList.get(position);
        //todo :判断如果字段为空的话,将"null"替补!
        viewHolder.t1.setText(myBean.getVariety().toString().length() != 0 ? myBean.getVariety() : "null");
        viewHolder.t2.setText(myBean.getTotal().toString().length()!=0 ? "¥:"+myBean.getTotal() : "null");
        viewHolder.t3.setText(myBean.getDate().toString().length()!=0 ? myBean.getDate() : "null");
        viewHolder.t4.setText(myBean.getDescription().toString().length()!=0 ? "备注: "+myBean.getDescription() : "备注:null");
        return convertView;
    }

    private final class ViewHolder {
        private TextView t1;
        private TextView t2;
        private TextView t3;
        private TextView t4;

    }

    //获取数据库数据
    private static ArrayList query() {
        String total = null;
        String variety = null;
        String date = null;
        String description = null;
        while (cursor.moveToNext()) {
            variety = cursor.getString(cursor.getColumnIndex("variety"));
            total = cursor.getString(cursor.getColumnIndex("total"));
            date = cursor.getString(cursor.getColumnIndex("date"));
            description = cursor.getString(cursor.getColumnIndex("description"));
            MyBean bean = new MyBean(variety, total, date, description);
            beanList.add(bean);
        }
        cursor.close();
        return list;
    }


}

 

对应的xml布局为:




    
        
        
        
    

        
        

适配的List Item布局为:




    
        
        
        
        
        
        
    

    
    

4)数据库类:

package com.example.qz;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class SqlLiteHelper extends SQLiteOpenHelper {

    //创建数据库表.
    private static final String SQL_CREATE_ENTRIES =(
            "create table qc_info(variety varchar(50),"
            +"total varchar(255),"
            +"date varchar(50),"
            +"description varchar(255))"
    );

    public SqlLiteHelper(@Nullable Context context, @Nullable String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name,factory,version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        System.out.println("创建数据库");
        db.execSQL(SQL_CREATE_ENTRIES);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

}

5)工具类(Bean):

package com.example.qz;

public class MyBean {

    private String variety;
    private String total ;
    private String date;
    private String description;

    public String getVariety() {
        return variety;
    }

    public void setVariety(String variety) {
        this.variety = variety;
    }

    public String getTotal() {
        return total;
    }

    public void setTotal(String total) {
        this.total = total;
    }

    public String getDate() {
        return date;
    }

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

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public MyBean(String variety, String total, String date, String description) {
        this.variety = variety;
        this.total = total;
        this.date = date;
        this.description = description;
    }

    public String toString(){
        return variety+","+total+","+date+","+description;
    }
}

 

你可能感兴趣的:(工作总结输出,android)