连接到SQLite数据库

时间:2016-12-25 01:30:00

标签: java android sqlite android-sqlite

我已经在一个新项目中为我的BMI应用程序创建了一个SQLite数据库 现在的问题是我不知道如何连接到数据库。

是否将private string file = "mydata";更改为其他内容或是否正确?

CalculatorActivity。的java

public class CalculatorActivity extends AppCompatActivity {
    private EditText etWeight, etHeight;
    private TextView tvDisplayResult, tvResultStatus;
    Button bSave, bRead;
    TextView tvStored;
    String data;
    private String file = "mydata";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calculator);
        etWeight = (EditText) findViewById(R.id.weight);
        etHeight = (EditText) findViewById(R.id.height);
        tvDisplayResult = (TextView) findViewById(R.id.display_result);
        tvResultStatus = (TextView) findViewById(R.id.result_status);
        tvResultStatus = (TextView) findViewById(R.id.result_status);
        bSave = (Button) findViewById(R.id.savebutton);
        bRead = (Button) findViewById(R.id.readbutton);
        tvStored = (TextView) findViewById(R.id.displaysaveditem);
        bSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                data = tvDisplayResult.getText().toString() + "\n";

                try {
                    FileOutputStream fOut = openFileOutput(file, Context.MODE_APPEND);
                    fOut.write(data.getBytes());
                    fOut.close();
                    Toast.makeText(getBaseContext(), "file saved", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });

        //Read
        bRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(CalculatorActivity.this, RecordActivity.class));
                finish();

            }
        });


    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_calculate:
                Log.d("check", "Button Clicked!");
                calculate();
                break;
            case R.id.button_reset:
                reset();
                break;
        }
    }

    private void calculate() {
        String weight = etWeight.getText().toString();
        String height = etHeight.getText().toString();

        double bmiResult = Double.parseDouble(weight) / (Double.parseDouble(height) * Double.parseDouble(height));

        tvDisplayResult.setText(String.valueOf(bmiResult));


        if (bmiResult < 18.5) {
            tvResultStatus.setText(R.string.under);
            tvResultStatus.setBackgroundColor(Color.parseColor("#F1C40F"));
            tvResultStatus.setTextColor(Color.parseColor("#FFFFFF"));
        } else if (bmiResult >= 18.5 && bmiResult <= 24.9) {
            tvResultStatus.setText(R.string.normal);
            tvResultStatus.setBackgroundColor(Color.parseColor("#2ECC71"));
            tvResultStatus.setTextColor(Color.parseColor("#FFFFFF"));
        } else if (bmiResult >= 24.9 && bmiResult <= 29.9) {
            tvResultStatus.setText(R.string.over);
            tvResultStatus.setBackgroundColor(Color.parseColor("#E57E22"));
            tvResultStatus.setTextColor(Color.parseColor("#FFFFFF"));
        } else if (bmiResult >= 30) {
            tvResultStatus.setText(R.string.obes);
            tvResultStatus.setBackgroundColor(Color.parseColor("#C0392B"));
            tvResultStatus.setTextColor(Color.parseColor("#FFFFFF"));
        }


    }

    private void reset() {
        etWeight.setText("");
        etHeight.setText("");
        tvDisplayResult.setText(R.string.default_result);
        tvResultStatus.setText(R.string.na);
        tvResultStatus.setBackgroundColor(0);
        tvResultStatus.setTextColor(0);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_options, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.menu_home:
                startActivity(new Intent(CalculatorActivity.this, CalculatorActivity.class));
                finish();
                break;
            case R.id.menu_info:
                startActivity(new Intent(CalculatorActivity.this, InformationActivity.class));
                finish();
                break;

        }
        return true;
    }

}

DBHandler。的java

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

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



public class DBHandler extends SQLiteOpenHelper {

    // Database Version
    public static final int DATABASE_VERSION = 1;
    // Database Name
    public static final String DATABASE_NAME = "RecordDB";
    // Record table name
    public static final String TABLE_RECORD = "recordtable";
    // Record Table Columns names
    public static final String KEY_ID = "id";
    public static final String KEY_BMI = "bmi";


    public DBHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_RECORD_TABLE = "CREATE TABLE " + TABLE_RECORD + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_BMI + " TEXT " + ")";
        db.execSQL(CREATE_RECORD_TABLE);
    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_RECORD);
        // Creating tables again
        onCreate(db);

    }


    public void addBmi(Record record) {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_BMI, record.getBmi()); // BMI value

        // Inserting Row
        db.insert(TABLE_RECORD, null, values);
        db.close(); // Closing database connection
    }

    public List<Record> getAllRecords() {
        List<Record> recordList = new ArrayList<Record>();
        // Select All Query
        String selectQuery = "SELECT * FROM " + TABLE_RECORD;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Record record = new Record();
                record.setId(Integer.parseInt(cursor.getString(0)));
                record.setBmi(cursor.getString(1));
                // Adding record to list
                recordList.add(record);
            } while (cursor.moveToNext());
        }

        // return record list
        return recordList;
    }
}

1 个答案:

答案 0 :(得分:0)

  

我不知道如何在我的BMI应用程序中连接数据库

好吧,你需要声明并初始化它。

public class CalculatorActivity extends AppCompatActivity {

    private DBHandler dbHandler;

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

        dbHandler = new DBHandler(this);

        // Use it...
  

private string file = "mydata";是否需要更改为其他内容或其正确?

您可以保留它,并且它是正确的,但它与数据库无关。