将新值添加到文本文件中

时间:2018-03-31 12:20:16

标签: java android android-sqlite read-write

所以基本上我正在创建一个Android应用程序,其中一个功能是模拟生命体征。有4个变量:温度,舒张压,收缩压和心率。这4个变量是随机生成的,并与设定值进行比较,并确定用户是否有风险。所有这些都发生在CalculationRisk类中。

结果显示在文本视图中,如下所示:

Simulation Results
Temperature: 39
Diastolic Blood Pressure: 107
Systolic Blood Pressure: 224
Heart Rate: 151

Risk Results
Temperature: HIGH RISK
Diastolic Blood Pressure: NORMAL
Systolic Blood Pressure: HIGH RISK
Heart Rate: LOW RISK

每个测量都存储在VitalsDB类中名为MEASUREMENTS_TABLE的表中。我想要做的是点击一个按钮,我希望这些值保存到名为“text”的文本文件中。

文字档案:

    Height:   175
    Weight:   80

    Diastolic Blood Pressure:   100
    Systolic Blood Pressure:   100
    Heart Rate:   170
    Body Temperature:   100

此文本文件存储在assets文件夹中,并在SummaryCareRecord类中读取。但问题是我想添加到文本文件中,所以无论什么已经存在,应该在文本视图中显示值。

CalculationRisk:

package com.example.testapp;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

import static java.text.DateFormat.getTimeInstance;

public class CalculateRisk extends AppCompatActivity {

    TextView tv_text2;
    String name = "";
    String address = "";
    String date_of_birth = "";
    String medication1 = "";
    String medication2 = "";
    String medication3 = "";
    String allergies = "";
    String bad_reactions = "";

    int height = 0;
    int weight = 0;

    int DBP = 0;
    int SBP = 0;
    int pulse_rate = 0;
    int blood_glucose = 0;
    int respiration_rate = 0;
    int body_temperature = 0;

    Button btn_pm;

    VitalsDB db;
    int highRiskCount = 0;

    String verdictTemp = null;
    String verdictHR = null;
    String verdictDBP = null;
    String verdictSBP = null;


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

        db = new VitalsDB(getBaseContext());

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(CalculateRisk.this);
        int h = 0;
        int userPosition = preferences.getInt("positionCount", h);


        tv_text2 = (TextView) findViewById(R.id.textView2);
        tv_text2.setText("");
        tv_text2.setMovementMethod(new ScrollingMovementMethod());

        btn_pm = (Button) findViewById(R.id.btn_pm);

        btn_pm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(CalculateRisk.this, PastMeasurements.class));
            }
        });

        final TextView HRMeasureText = (TextView) findViewById(R.id.result_label);

        ImageButton results = (ImageButton) findViewById(R.id.button_calculate);
        results.setOnClickListener(new View.OnClickListener() {
                                       public void onClick(View v) {
                                           Random random = new Random();

                                           int SBP = random.nextInt(180) + 70;
                                           int DBP = random.nextInt(110) + 70;
                                           int pulse_rate = random.nextInt(180)+ 60;
                                           int body_temperature = random.nextInt(32)+ 10;


                        if (body_temperature > 38) {
                            verdictTemp = "HIGH RISK";
                            highRiskCount += 1;
                        } else if (body_temperature <= 38 && body_temperature > 37) {
                            verdictTemp = "LOW RISK";
                        } else if (body_temperature <= 37) {
                            verdictTemp = "NORMAL";
                        }

                        if (DBP >= 180) {
                            verdictDBP = "HIGH RISK";
                            highRiskCount += 1;
                        } else if (DBP < 180 && DBP > 120) {
                            verdictDBP = "LOW RISK";
                        } else if (DBP <= 120) {
                            verdictDBP = "NORMAL";
                        }

                        if (SBP >= 110) {
                            verdictSBP = "HIGH RISK";
                            highRiskCount += 1;
                        } else if (SBP < 110 && SBP > 80) {
                            verdictSBP = "LOW RISK";
                        } else if (SBP <= 80) {
                            verdictSBP = "NORMAL";
                        }

                        if (pulse_rate > 160) {
                            verdictHR = "HIGH RISK";
                            highRiskCount += 1;
                        } else if (pulse_rate <= 160 && pulse_rate > 72) {
                            verdictHR = "LOW RISK";
                        } else if (pulse_rate <= 72) {
                            verdictHR = "NORMAL";
                        }


                    HRMeasureText.setVisibility(View.VISIBLE);
                    TextView output = (TextView) findViewById(R.id.output_riskyness);
                    output.setText(String.valueOf(highRiskCount));

                    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(CalculateRisk.this);

                    int h = 0;
                    int userPosition = preferences.getInt("positionCount", h);

                    /***************************** INSERT NEW CALCULATION RECORD *********************/
                    Calculation calc = new Calculation();


                    //temperature data
                    calc.setTemperatureReading(body_temperature);
                    calc.setVerdictTemp(verdictTemp);

                    //Heart Rate data
                    calc.setHeartRateReading(pulse_rate);
                    calc.setVerdictHR(verdictHR);

                    //diastolic blood pressure data
                     calc.setDBPReading(DBP);
                     calc.setVerdictDBP(verdictDBP);

                    //diastolic blood pressure data
                    calc.setSBPReading(SBP);
                    calc.setVerdictSBP(verdictSBP);

                    //Date Data
                    Calendar calendar = Calendar.getInstance();
                    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
                    String strDate = sdf.format(calendar.getTime());

                    calc.setDate(strDate);

                    //Time Data
                    long millis = new Date().getTime();
                    String time = getTimeInstance(SimpleDateFormat.MEDIUM, Locale.UK).format(millis);

                    String strTime = time + " GMT";
                    calc.setTime(strTime);

                    db.open();
                    db.insertCalculation(calc);
                    db.close();

//                    final AlertDialog.Builder highRiskAlert  = new AlertDialog.Builder(CalculateRisk.this);
//                    highRiskAlert.setMessage("An SMS has been sent to alert your GP of your measurements, and an appointment will be booked. \n" +
//                            "\nPlease keep an eye on your inbox for your GP's confirmation of the appointment.");
//                    highRiskAlert.setTitle("HIGH RISK!");
//
//                    highRiskAlert.setCancelable(false);


                    AlertDialog.Builder resultAlert  = new AlertDialog.Builder(CalculateRisk.this);



                                           tv_text2.setText("\nSimulation Results: " + "\n\n" +
                            "Temperature: " + body_temperature +  "       Diastolic Blood Pressure: " + DBP + "\n\n" +

                            "Systolic Blood Pressure: " + SBP  + "        Heart Rate: " +  pulse_rate + "\n\n" + "\n\n"+

                                                   "Risk Results:" + "\n\n"+
                                                   "Temperature:" + verdictTemp + "        DBP:" + verdictDBP + "\n\n"+
                                           "SBP:" + verdictSBP + "              Heart Rate:" + verdictHR);

//                    resultAlert.setMessage("Results:" + "\n\n" +
//                            "Temperature Risk: " + verdictTemp + "\n\n" +
//                            "DBP Risk:" + verdictDBP + "\n\n" +
//                            "SBP Risk:" + verdictSBP + "\n\n" +
//                            "Heart Rate Risk:" + verdictHR
//                    );

                    if (verdictTemp == "HIGH RISK"){
                        resultAlert.setMessage("WARNING Temperature too high");
                    }
                    if(verdictDBP == "HIGH RISK"){
                        resultAlert.setMessage("WARNING DBP too high");
                    }
                    if(verdictSBP == "HIGH RISK"){
                        resultAlert.setMessage("WARNING SBP too high");
                    }
                    if(verdictHR == "HIGH RISK"){
                        resultAlert.setMessage("WARNING Heart Rate too high");
                    }


                    if(verdictTemp == "HIGH RISK" & verdictDBP == "HIGH RISK"){
                        resultAlert.setMessage("WARNING Temperature and DBP too high ");
                    }
                    if(verdictTemp == "HIGH RISK" & verdictSBP == "HIGH RISK"){
                        resultAlert.setMessage("WARNING Temperature and SBP too high");
                    }
                    if(verdictTemp == "HIGH RISK" & verdictHR == "HIGH RISK"){
                        resultAlert.setMessage("WARNING Temperature and Heart Rate too high");
                    }

                    if(verdictDBP == "HIGH RISK" & verdictSBP == "HIGH RISK"){
                        resultAlert.setMessage("WARNING DBP and SBP too high");
                    }
                    if(verdictDBP == "HIGH RISK" & verdictHR == "HIGH RISK"){
                        resultAlert.setMessage("WARNING DBP and Heart Rate too high");
                    }

                    if(verdictSBP == "HIGH RISK" & verdictHR == "HIGH RISK"){
                        resultAlert.setMessage("WARNING SBP and Heart Rate too high");
                    }


                    if(verdictTemp == "HIGH RISK" & verdictDBP == "HIGH RISK" & verdictSBP == "HIGH RISK"){
                        resultAlert.setMessage("WARNING Temperature, DBP and SBP too high PLEASE SEEK ATTENTION");
                    }
                    if(verdictTemp == "HIGH RISK" & verdictDBP == "HIGH RISK" & verdictHR == "HIGH RISK"){
                        resultAlert.setMessage("WARNING Temperature, DBP and Heart Rate too high PLEASE SEEK ATTENTION");
                    }
                    if(verdictTemp == "HIGH RISK" & verdictSBP == "HIGH RISK" & verdictHR == "HIGH RISK"){
                        resultAlert.setMessage("WARNING Temperature,SBP and Heart Rate too high PLEASE SEEK ATTENTION");
                    }

                    if(verdictDBP == "HIGH RISK" & verdictSBP == "HIGH RISK" & verdictHR == "HIGH RISK"){
                        resultAlert.setMessage("WARNING DBP, SBP and Heart Rate too high PLEASE SEEK ATTENTION");
                    }


                    if(verdictTemp == "HIGH RISK" & verdictDBP == "HIGH RISK" & verdictSBP == "HIGH RISK" & verdictHR == "HIGH RISK"){
                        resultAlert.setMessage("WARNING Temperature,DBP, SBP and Heart Rate too high" + "\n\n" +
                        "PLEASE SEEK IMMEDIATE ATTENTION");
                    }





                    resultAlert.setTitle("Results");
                    resultAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {

                            highRiskCount = 0;

                        }
                    });
                    resultAlert.setCancelable(false);
                    resultAlert.create().show();

                }

        });
        tv_text2.setText("Results");
    }
}

VitalsDB:

package com.example.testapp;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


public class VitalsDB {

    //variables for all columns in database
    private static final String TAG = "DBHelper";

    private static final String DATABASE_NAME = "VitalsDB2";



    private static final String MEASUREMENTS_TABLE = "measurements";
    public static final String COLUMN_MEASUREMENTID = "measureid";
    public static final String COLUMN_DATE = "date";
    public static final String COLUMN_TIME = "time";
    public static final String COLUMN_TEMPERATURE = "temperature";
    public static final String COLUMN_TEMPERATURE_VERDICT = "temperature_verdict";
    public static final String COLUMN_SBP = "sbp";
    public static final String COLUMN_SBP_VERDICT = "sbp_verdict";
    public static final String COLUMN_DBP = "dbp";
    public static final String COLUMN_DBP_VERDICT = "dbp_verdict";
    public static final String COLUMN_HEARTRATE = "heartrate";
    public static final String COLUMN_HEARTRATE_VERDICT = "heartrate_verdict";

    private static final int DATABASE_VERSION = 2;


//    public VitalsDB(Context context) {
//        super(context, DATABASE_NAME, null, DATABASE_VERSION);
//    }
//
//
//    //creating tables
//    public void onCreate(SQLiteDatabase db){
//        String CREATE_MEASUREMENTS_TABLE1 = "CREATE TABLE" + MEASUREMENT_TABLE1 + "( MEASUREMENTID INTEGER PRIMARY KEY, Date TEXT, Time TEXT, Temperature INTEGER, Temperature_Verdict TEXT, Lbp INTEGER, Lbp_Verdict TEXT, Hbp INTEGER, Hbp_Verdict TEXT, Heartrate INTEGER, Heartrate_verdict TEXT) ";
//        db.execSQL(CREATE_MEASUREMENTS_TABLE1);
//        Log.d("DatabaseHandler","Database Created");
//    }
//
//
//    // Upgrading database
//    @Override
//    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//        // Drop older table if existed
//        db.execSQL("DROP TABLE IF EXISTS " + MEASUREMENTS_TABLE1);
//        // Create tables again
//        onCreate(db);
//    }







    //string query to hold database table name and order of columns
    private static final String CREATE_MEASUREMENTS_TABLE = "create table "+ MEASUREMENTS_TABLE + "("
            + COLUMN_MEASUREMENTID + " integer primary key autoincrement, "
            + COLUMN_DATE + " text, "
            + COLUMN_TIME + " text, "
            + COLUMN_TEMPERATURE + " text not null, "
            + COLUMN_TEMPERATURE_VERDICT + " text not null, "
            + COLUMN_SBP + " text not null, "
            + COLUMN_SBP_VERDICT + " text not null, "
            + COLUMN_DBP + " text not null, "
            + COLUMN_DBP_VERDICT + " text not null, "
            + COLUMN_HEARTRATE + " text not null, "
            + COLUMN_HEARTRATE_VERDICT + " text not null )";




    //variables for holding database context, helper and SQLite instances
    private final Context context;
    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;

    //method to create instance of database helper
    public VitalsDB(Context ctx)
    {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }

    private static class DatabaseHelper extends SQLiteOpenHelper {
        //generate instance of database helper with defined database name and version
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        //first method ran on load of class
        @Override
        public void onCreate(SQLiteDatabase db){

            db.execSQL(CREATE_MEASUREMENTS_TABLE);
        }

        //if the database is updated, wipe it to prevent conflicts
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + MEASUREMENTS_TABLE);
            onCreate(db);
        }
    }

    //open database
    public VitalsDB open() throws SQLException {
        db = DBHelper.getWritableDatabase();
        //sqlDB = DBHelper.getWritableDatabase();
        return this;
    }

    //close the database
    public void close() {
        DBHelper.close();
    }

    //add new row and calc to database
    public void insertCalculation(Calculation calc) {

        //populate rows with measurements
        ContentValues newCalc = new ContentValues();

        newCalc.put(COLUMN_TEMPERATURE, calc.getTemperatureReading());
        newCalc.put(COLUMN_SBP, calc.getSBPReading());
        newCalc.put(COLUMN_DBP, calc.getDBPReading());
        newCalc.put(COLUMN_HEARTRATE, calc.getHeartRateReading());
        newCalc.put(COLUMN_DATE, calc.getDate());
        newCalc.put(COLUMN_TIME, calc.getTime());
        newCalc.put(COLUMN_TEMPERATURE_VERDICT, calc.getVerdictTemp());
        newCalc.put(COLUMN_SBP_VERDICT, calc.getVerdictSBP());
        newCalc.put(COLUMN_DBP_VERDICT, calc.getVerdictDBP());
        newCalc.put(COLUMN_HEARTRATE_VERDICT, calc.getVerdictHR());

        db.insert(MEASUREMENTS_TABLE, null, newCalc);
    }

    public Cursor getCalculation() {
        //query database for current row for data


        Cursor mCursor = db.rawQuery("select * from " + MEASUREMENTS_TABLE, null);

        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        //return the cursor
        return mCursor;
    }
}

摘要护理记录:

package com.example.testapp;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class SummaryCareRecord extends Activity {

    Button b_read;
    TextView tv_text;
    String name = "";
    String address = "";
    String date_of_birth = "";
    String medication1 = "";
    String medication2 = "";
    String medication3 = "";
    String allergies = "";
    String bad_reactions = "";

    int height = 0;
    int weight = 0;

    int blood_pressure = 0;
    int pulse_rate = 0;
    int blood_glucose = 0;
    int respiration_rate = 0;
    int body_temperature = 0;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scr);

        tv_text = (TextView) findViewById(R.id.tv_text);
     Read(tv_text);
    }


        public void Read(View view) {
            String text = "";
            try {
                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(getAssets().open("test.txt")));
                String line;
                while((line = bufferedReader.readLine()) != null){
                    text = text.concat(line + "\n");
//                    String[] lineVals = line.split(":");
//                    if(lineVals[0].equalsIgnoreCase("name")){
//                        name = lineVals[1].trim();
//                    } else if(lineVals[0].equalsIgnoreCase("height")){
//                        height = Integer.parseInt(lineVals[1].trim());
//                    }
//                    else if(lineVals[0].equalsIgnoreCase("weight")){
//                        weight = Integer.parseInt(lineVals[1].trim());
//                    }
//                    else if(lineVals[0].equalsIgnoreCase("blood pressure")){
//                        blood_pressure = Integer.parseInt(lineVals[1].trim());
//                    } else if(lineVals[0].equalsIgnoreCase("pulse rate")){
//                        pulse_rate = Integer.parseInt(lineVals[1].trim());
//                    }
//                    else if(lineVals[0].equalsIgnoreCase("blood glucose")){
//                        blood_glucose = Integer.parseInt(lineVals[1].trim());
//                    }
//                    else if(lineVals[0].equalsIgnoreCase("respiration rate")){
//                        respiration_rate = Integer.parseInt(lineVals[1].trim());
//                    }
//                    else if(lineVals[0].equalsIgnoreCase("body temperature")){
//                        body_temperature = Integer.parseInt(lineVals[1].trim());
//                    }
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            tv_text.setText(text);

        }
    }

Pastmeasurements

1 个答案:

答案 0 :(得分:0)

我相信assets文件夹是受保护的,只能被读取,因为它是用于安装App的软件包的一部分,因此您将无法将资产文件夹中的文件(任何文件)保存在应用

当然,您已经拥有了一种非常高效且易于使用的方法,可以将数据写入文件,从而保留数据,即使用SQLite数据库。

从表面上看,最好的方法是在数据库中添加一个新表,其中包含名称,高度,重量,bp,bgl,rr和bt的列。