如何将单选按钮转换为字符串并将其存储到数据库中?

时间:2018-09-25 11:02:44

标签: java android xml database radio-button

编辑:此帖子现在已解决。但是,存在新的错误。.当我选择“女性”时,当我转到ViewRecord页面时,它表明我选择了“男性”。

Adding Records (gender)

Viewing Records (gender)

我正在尝试使用Android Studio制作一个应用程序,该应用程序可以接收学生的信息并将其存储在数据库中。这些信息的一部分是学生的性别。

当学生选择单选按钮(男性或女性)时,该选择将添加到数据库中。

我尝试对其进行编码,但是每次打开它时我的应用都会崩溃...

这是布局代码(xml)。

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="40dp"
android:background="#F0F8FF"
>

<TableLayout
    android:id="@+id/add_table"
    android:layout_width="match_parent"
    android:layout_height="606dp"
    android:paddingTop="40dp">

    <TableRow>

        <TextView
            android:layout_marginLeft="25dp"
            android:padding="3dip"
            android:text="Student ID:" />

        <EditText
            android:id="@+id/sid"
            android:layout_width="190dp"
            android:layout_height="wrap_content" />
    </TableRow>

    <TableRow>

        <TextView
            android:layout_marginLeft="25dp"
            android:padding="3dip"
            android:text="First Name:" />

        <EditText
            android:id="@+id/fn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minWidth="150dip" />
    </TableRow>

    <TableRow>

        <TextView
            android:layout_marginLeft="25dp"
            android:padding="3dip"
            android:text="Last Name:" />

        <EditText
            android:id="@+id/ln"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minWidth="150dip" />
    </TableRow>

    <TableRow>

        <TextView
            android:layout_marginLeft="25dp"
            android:padding="3dip"
            android:layout_marginTop="5dp"
            android:text="Gender:" />

        <RadioGroup
            android:id="@+id/ge"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:orientation="horizontal">

            <RadioButton
                android:id="@+id/male"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:scaleX="0.9"
                android:scaleY="0.9"
                android:checked="true"
                android:text="Male" />

            <RadioButton
                android:id="@+id/female"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:scaleX="0.9"
                android:scaleY="0.9"
                android:text="Female" />

        </RadioGroup>

    </TableRow>

    <TableRow>

        <TextView
            android:layout_marginLeft="25dp"
            android:padding="3dip"
            android:text="Course Study:" />

        <EditText
            android:id="@+id/cs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minWidth="150dip" />
    </TableRow>

    <TableRow>

        <TextView
            android:layout_marginLeft="25dp"
            android:digits="0123456789"
            android:inputType="number"
            android:padding="3dip"
            android:text="Age:" />

        <EditText
            android:id="@+id/ag"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minWidth="150dip" />
    </TableRow>

    <TableRow>

        <TextView
            android:layout_marginLeft="25dp"
            android:padding="3dip"
            android:text="Address:" />

        <EditText
            android:id="@+id/ad"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minWidth="150dip" />


    </TableRow>

    <Button
        android:id="@+id/add_button"
        android:layout_width="207dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="118dp"
        android:layout_marginRight="52dp"
        android:layout_marginTop="14dp"
        android:padding="6dip"
        android:text="Add Student" />

    <ImageView
        android:id="@+id/imageView4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        app:srcCompat="@mipmap/man" />

</TableLayout>

 </LinearLayout>

这是主要活动(java代码)

public class Addrecord extends AppCompatActivity {

DatabaseManager myDb;
EditText sid, fn, ln, cs, ag, ad;
RadioGroup radioGenderGroup;
RadioButton radioGenderButton;

Button btnAddStudent;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle(null);
    myDb = new DatabaseManager(this);

    sid = (EditText)findViewById(R.id.sid);
    fn = (EditText)findViewById(R.id.fn);
    ln = (EditText)findViewById(R.id.ln);

    radioGenderGroup = (RadioGroup) findViewById(R.id.ge);
    int selectedid = radioGenderGroup.getCheckedRadioButtonId();
    radioGenderButton = (RadioButton) findViewById(selectedid);


    cs = (EditText)findViewById(R.id.cs);
    ag = (EditText)findViewById(R.id.ag);
    ad = (EditText)findViewById(R.id.ad);
    btnAddStudent = (Button)findViewById(R.id.add_button);

    AddStudentRecord();


}



public  void AddStudentRecord() {
    btnAddStudent.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean isInserted = myDb.insertDataStudent(
                            Integer.parseInt(sid.getText().toString()),
                            fn.getText().toString(),
                            ln.getText().toString(),
                            radioGenderButton.getText().toString(),
                            cs.getText().toString(),
                            Integer.parseInt(ag.getText().toString()),
                            ad.getText().toString()

                    );

                    if(isInserted == true)
                        Toast.makeText(Addrecord.this,"Data Inserted",Toast.LENGTH_LONG).show();
                    else
                        Toast.makeText(Addrecord.this,"Data not Inserted",Toast.LENGTH_LONG).show();
                }
            }
    );
}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.screen2_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement

    if (id == R.id.home2) {
        Intent intent = new Intent(Addrecord.this, Home.class);
        startActivity(intent);
        return true;

    }
    return super.onOptionsItemSelected(item);
}
 }

这是数据库(java)

public class DatabaseManager extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "student";
public static final String TABLE_NAME1 = "studentinfo";
public static final String TABLE_NAME2 = "taskinfo";
public static final String TABLE_NAME3 = "examinfo";

//student information
public static final String COL_0student = "IDstudent";
public static final String COL_1student = "studentId";
public static final String COL_2student = "firstname";
public static final String COL_3student = "lastname";
public static final String COL_4student = "gender";
public static final String COL_5student = "coursestudy";
public static final String COL_6student = "age";
public static final String COL_7student = "address";


//task information

public static final String COL_0task = "IDtask";
public static final String COL_1task = "taskname";
public static final String COL_2task = "location";
//public static final String COL_3task = "status";

//exam information (no need for Id since no selection happening)

public static final String COL_1exam = "unitname";
public static final String COL_2exam = "date";
public static final String COL_3exam = "time";
public static final String COL_4exam = "location3";


public DatabaseManager(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table if not exists " + TABLE_NAME1 + " (IDstudent INTEGER PRIMARY KEY AUTOINCREMENT,studentId INTEGER,firstname TEXT,lastname TEXT, gender TEXT, coursestudy TEXT, age INTEGER, address TEXT)");
    db.execSQL("create table if not exists " + TABLE_NAME2 + " (IDtask INTEGER PRIMARY KEY AUTOINCREMENT, taskname TEXT,location TEXT,status TEXT)");
    db.execSQL("create table if not exists " + TABLE_NAME3 + " (unitname TEXT,date TEXT,time TEXT, location TEXT)");
}


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME1);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME2);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME3);
    onCreate(db);
}


//INSERT, UPDATE, SELECT, DELETE student record


public boolean insertDataStudent(Integer studentId, String firstname, String lastname, String gender, String coursestudy, Integer age, String address) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues newStudent = new ContentValues();
    newStudent.put(COL_1student, studentId);
    newStudent.put(COL_2student, firstname);
    newStudent.put(COL_3student, lastname);
    newStudent.put(COL_4student, gender);
    newStudent.put(COL_5student, coursestudy);
    newStudent.put(COL_6student, age);
    newStudent.put(COL_7student, address);

    long result = db.insert(TABLE_NAME1, null, newStudent);
    if (result == -1)
        return false;
    else
        return true;
}

public Cursor getAllDataStudent() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from " + TABLE_NAME1, null);
    return res;
}


public boolean updateDataStudent(String idstudent, String studentId, String firstname, String lastname, String gender, String coursestudy, String age, String address) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues newStudent = new ContentValues();
    newStudent.put(COL_0student, idstudent);
    newStudent.put(COL_1student, studentId);
    newStudent.put(COL_2student, firstname);
    newStudent.put(COL_3student, lastname);
    newStudent.put(COL_4student, gender);
    newStudent.put(COL_5student, coursestudy);
    newStudent.put(COL_6student, age);
    newStudent.put(COL_7student, address);

    db.update(TABLE_NAME1, newStudent, "IDstudent = ?", new String[]{idstudent});
    return true;
}

public Integer deleteDataStudent(String idstudent) {
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete(TABLE_NAME1, "IDstudent = ?", new String[]{idstudent});
}

  }

这是错误日志

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.supriya.project3, PID: 5517
              java.lang.RuntimeException: Unable to start activity   ComponentInfo{com.supriya.project3/com.supriya.project3.Addrecord}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
                  at android.app.ActivityThread.-wrap11(Unknown Source:0)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
                  at android.os.Handler.dispatchMessage(Handler.java:106)
                  at android.os.Looper.loop(Looper.java:164)
                  at android.app.ActivityThread.main(ActivityThread.java:6494)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference
                  at com.supriya.project3.Addrecord.onCreate(Addrecord.java:42)
                  at android.app.Activity.performCreate(Activity.java:7009)
                  at android.app.Activity.performCreate(Activity.java:7000)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
                  at android.app.ActivityThread.-wrap11(Unknown Source:0) 
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
                  at android.os.Handler.dispatchMessage(Handler.java:106) 
                  at android.os.Looper.loop(Looper.java:164) 
                  at android.app.ActivityThread.main(ActivityThread.java:6494) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
                  at     com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 
    I/zygote: Do full code cache collection, code=98KB, data=54KB
      After code cache collection, code=93KB, data=45KB
    Application terminated.

3 个答案:

答案 0 :(得分:0)

如果您正在寻找如何从广播组捕获输入。这是给您的一些提示。您还需要获取RadioButton id并实现一个侦听器。就是这样。

radioGenderGroup = (RadioGroup) findViewById(R.id.ge);
//Get also male and Female (RadioButton) id from the layout.

radioGenderGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
                // checkedId is the RadioButton selected
                if (rdoMale.getId() == checkedId) {                   
                    //Get the value for male R.Button.rdoMale

                } else if (rdoFemale.getId() == checkedId) {              
                  //Get the value for Female R.Button.rdoFemale
                }
        }
    });

答案 1 :(得分:0)

在onCreate方法中

radioGenderGroup = (RadioGroup) findViewById(R.id.ge);
radioGenderGroup .setOnCheckedChangeListener(this);

然后重写onCheckedChanged方法

@Override
public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
    switch (group.getId()) {
        case R.id.male:
            gender = "Male";
            break;

        case R.id.female:
            gender = "Female";
            break;

    }
}

答案 2 :(得分:0)

解决方案:

首先,将right: 5px;中的任何一个设置为:

RadioButton

因此它应该看起来像:

android:checked="true" 

默认情况下,这将为您提供<RadioButton android:id="@+id/male" android:layout_width="wrap_content" android:layout_height="wrap_content" android:scaleX="0.9" android:scaleY="0.9" android:text="Male" android:checked="true" /> 中的Male文本。

第二,从此部分删除此行:String gender

String gender = String.valueOf(radioGenderButton.getText());

然后

写下:

radioGenderGroup = (RadioGroup) findViewById(R.id.ge);
int selectedid = radioGenderGroup.getCheckedRadioButtonId();
radioGenderButton = (RadioButton) findViewById(selectedid);
String gender = String.valueOf(radioGenderButton.getText()); // REVOME THIS

radioGenderGroup = (RadioGroup) findViewById(R.id.ge); int selectedid = radioGenderGroup.getCheckedRadioButtonId(); radioGenderButton = (RadioButton) findViewById(selectedid); 内部,如图所示:

onClick()

通过上述步骤,您将获得选择的btnAddStudent.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { .... (Write those 3 lines here) boolean isInserted = myDb.insertDataStudent( Integer.parseInt(sid.getText().toString()), fn.getText().toString(), ln.getText().toString(), radioGenderButton.getText().toString(), cs.getText().toString(), Integer.parseInt(ag.getText().toString()), ad.getText().toString() ); if(isInserted == true) Toast.makeText(Addrecord.this,"Data Inserted",Toast.LENGTH_LONG).show(); else Toast.makeText(Addrecord.this,"Data not Inserted",Toast.LENGTH_LONG).show(); } } ); ,然后将其传递给数据库以进行插入。

希望有帮助。