Как превратить переключатель в строку и сохранить ее в базе данных? - PullRequest
0 голосов
/ 25 сентября 2018

РЕДАКТИРОВАТЬ: Этот пост теперь решен.Однако появляются новые ошибки .. Когда я выбираю "Женский", он показывает, что "Мужской" выбран, когда я перехожу на страницу ViewRecord.

Добавление записей (пол)

Просмотр записей (пол)

Я пытаюсь создать приложение с 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 голосов
/ 25 сентября 2018

В методе 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;

    }
}
0 голосов
/ 25 сентября 2018

Решение:

Во-первых, установите любой из 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();
            }
        }
);

С помощью описанных выше шагов вы получите все, что выберете gender, и затем передадитеэто в базу данных для вставки.

Надеюсь, это поможет.

0 голосов
/ 25 сентября 2018

Если вы ищете, как вы можете поймать вход от радиогруппы.Вот маленький совет для вас.Вы также должны получить идентификатор RadioButton и реализовать слушателя.Вот и все.

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
                }
        }
    });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...