У меня есть окно хранения, но данные не сохраняются.Как сохранить значение логического значения в базе данных? - PullRequest
0 голосов
/ 29 мая 2018

Привет всем.Я пытаюсь сделать приложение, которое работает с базой данных.У меня есть окно хранения, но данные не сохраняются.Как сохранить значение логического значения из флажка в базе данных?

Как решить эту проблему?

Это код базы данных

public class DataBase extends SQLiteOpenHelper{
    public static final String DATABASE_NAME = "DataOfSchedule.db";
    public static final String TABLE_NAME = "DataOfSchedule_table";
    public static final String COL_1 = "ID";
    public static final String COL_2 = "NAME";
    public static final String COL_3 = "AGE";
    public static final String COL_4 = "SEX_MALE";
    public static final String COL_7 = "SEX_FEMALE";
    public static final String COL_5 = "WEIGHT";
    public static final String COL_6 = "HEIGHT";
    public static final String COL_8 = "TRAUMA";
    public DataBase(Context context){
        super(context, DATABASE_NAME, null,1);
    }
    @Override
    public void onCreate(SQLiteDatabase db){
        db.execSQL("CREATE TABLE" + TABLE_NAME + "(ID INTEGER PRIMARY KEY," +
                " NAME TEXT," +
                " AGE INTEGER NOT NULL DEFAULT 0 , " +
                "SEX_MALE  TEXT NOT NULL \n" +
                "        CHECK( typeof(\"boolean\") = \"text\" AND\n" +
                "               \"boolean\" IN (\"TRUE\",\"FALSE\") ," +
                "SEX_FEMALE  TEXT NOT NULL \n" +
                "        CHECK( typeof(\"boolean\") = \"text\" AND\n" +
                "               \"boolean\" IN (\"TRUE\",\"FALSE\")," +
                "TRAUMA NOT NULL  TEXT NOT NULL \n" +
                "        CHECK( typeof(\"boolean\") = \"text\" AND\n" +
                "               \"boolean\" IN (\"TRUE\",\"FALSE\")," +
                "WEIGHT INTEGER NOT NULL DEFAULT 0," +
                "HEIGHT INTEGER NOT NULL DEFAULT 0)");
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
        db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
    }
    public boolean insertData(String name, Integer age, String sex_male, String sex_female, Integer weight, Integer height, String trauma){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_2,name);
        contentValues.put(COL_3,age);
        contentValues.put(COL_4,sex_male);
        contentValues.put(COL_5,weight);
        contentValues.put(COL_6,height);
        contentValues.put(COL_7,sex_female);
        contentValues.put(COL_8,trauma);
        long result = db.insert(TABLE_NAME,null,contentValues);
        db.close();
        //To Check Whether Data is Inserted in DataBase
        if(result==-1){
            return false;
        }else{
            return true;
        }
    }
    public Cursor getALLData(){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res = db.rawQuery("Select * from "+ TABLE_NAME,null);
        return res;
    }
}

Этоэто код Activity, который вставляет данные

public class InsertData extends AppCompatActivity {
    DataBase myDb;
    EditText txtName, txtAge , txtWeight, txtHeight;
    CheckBox boxSex_male,boxSex_female,boxTrauma;
    Button btnClick;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_insert_data);
        myDb = new DataBase(this);
        txtName = (EditText) findViewById(R.id.name);
        txtAge = (EditText) findViewById(R.id.age);
        boxSex_male = (CheckBox) findViewById(R.id.sex_m);
        boxTrauma = (CheckBox) findViewById(R.id.trauma);
        boxSex_female = (CheckBox) findViewById(R.id.sex_f);
        txtWeight = (EditText) findViewById(R.id.weight);
        txtHeight = (EditText) findViewById(R.id.height);
        btnClick = (Button) findViewById(R.id.InsertBtn);
        btnClick.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                ClickMe();
            }
        });
        if(boxTrauma.isChecked()){
            boxTrauma.setChecked(true);
        }else {
            boxTrauma.setChecked(false);
        }
        if(boxSex_female.isChecked()){
            boxSex_female.setChecked(true);
        }else {
            boxSex_female.setChecked(false);
        }
        if(boxSex_male.isChecked()){
            boxSex_male.setChecked(true);
        }else {
            boxSex_male.setChecked(false);
        }
    }
    private void ClickMe(){
        String name = txtName.getText().toString();
        String age = txtAge.getText().toString();
        String sex_male = boxSex_male.getText().toString();
        String trauma = boxTrauma.getText().toString();
        String sex_female = boxSex_female.getText().toString();
        String weight = txtName.getText().toString();
        String height = txtName.getText().toString();
        int weight_int = Integer.parseInt(weight);
        int age_int = Integer.parseInt(age);
        int height_int = Integer.parseInt(height);
        Boolean result = myDb.insertData(name,age_int,sex_male,sex_female,weight_int,height_int,trauma);
        if (result == true){
            Toast.makeText(this, "Data Inserted Successfully",Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(this, "Data Inserted Failed",Toast.LENGTH_SHORT).show();
        }
        Intent i = new Intent(this,ResultData.class);
        startActivity(i);
    }


}

Это мой HTML

<ScrollView 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context="daniel_nikulshyn_and_andrew_rybka.myway.InsertData">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true">
    <TextView
        android:id="@+id/heading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/insert_heading"
        android:layout_gravity="center"
        android:textSize="16dp"
        android:textColor="#021aee"/>

    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/insert_name"/>
    <EditText
        android:id="@+id/age"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/insert_age"
        android:numeric="integer"/>
    <EditText
        android:id="@+id/weight"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/insert_weight"
        android:numeric="integer"/>
    <EditText
        android:id="@+id/height"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/insert_height"
        android:numeric="integer"/>

    <TextView
        android:padding="10dp"
        android:text="@string/insert_sex"
        android:layout_gravity="left"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <CheckBox
        android:id="@+id/sex_m"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/male"/>
    <CheckBox
        android:id="@+id/sex_f"
        android:text="@string/female"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:padding="10dp"
        android:text="@string/insert_trauma"
        android:layout_gravity="left"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <CheckBox
        android:id="@+id/trauma"
        android:text="@string/insert_trauma_subtitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"/>

    <Button
        android:id="@+id/InsertBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:text="@string/insert_button"
        android:textColor="#f2fde4"
        android:layout_gravity="center"/>
</LinearLayout>

</ScrollView>

1 Ответ

0 голосов
/ 29 мая 2018

Давайте разберем эту проблему на пару постов.Сначала мы можем разобраться с частью SQLite кода, затем вы можете опубликовать новый вопрос о вставке значений - достаточно много кода, чтобы охватить и сделать это понятным.

Измените свой код в своем DataBase класс (Кстати: ненадлежащее имя!)

Дайте именам переменных для столбцов понятное имя.Кто может вспомнить, что такое COL_6?Также учтите, что это, вероятно, не обязательно должно быть public.

public static final String COL_ID = "ID";
public static final String COL_NAME = "NAME";
public static final String COL_AGE = "AGE";
public static final String COL_GENDER = "GENDER";
public static final String COL_WEIGHT = "WEIGHT";
public static final String COL_HEIGHT = "HEIGHT";
public static final String COL_TRAUMA = "TRAUMA";

Возможно, вы не захотите проверять, существует ли таблица, но я все равно добавил проверку.Я также сделал ID столбец AUTOINCREMENT.

@Override
public void onCreate(SQLiteDatabase db){
    db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
            COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COL_NAME + " TEXT," +
            COL_AGE + " INTEGER NOT NULL DEFAULT 0, " +
            COL_GENDER + " INTEGER NOT NULL DEFAULT 0, " +
            COL_TRAUMA + " INTEGER NOT NULL DEFAULT 0, " +
            COL_WEIGHT + " INTEGER NOT NULL DEFAULT 0, " +
            COL_HEIGHT + " INTEGER NOT NULL DEFAULT 0);");
}

Измените метод insertData, чтобы учесть изменения статических конечных переменных для столбцов и изменения типов параметров:

public boolean insertData(String name, Integer age, Integer sex_male, Integer weight, Integer height, Integer trauma){
    boolean success = false;
    try{
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_NAME, name);
        contentValues.put(COL_AGE, age);
        contentValues.put(COL_GENDER, sex_male);
        contentValues.put(COL_WEIGHT, weight);
        contentValues.put(COL_HEIGHT, height);
        contentValues.put(COL_TRAUMA, trauma);
        long result = db.insert(TABLE_NAME,null,contentValues);
        db.close();

        if(result != -1) success = true;
    }
    catch(Exception ex){
        Log.e(TAG, ex.getMessage());
    }

    return success;
}

Также обратите внимание, нет необходимости получать Writeable базу данных в вашем getALLData() методе:

   public Cursor getALLData(){
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res = db.rawQuery("Select * from "+ TABLE_NAME, null);
        return res;
    }

Теперь опубликуйте новый вопрос о том, как заполнить базу данных из вашегоActivity и мы можем идти оттуда ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...