-1

EDIT: This post is now solved. However, there are new errors..when I select "Female", it shows me "Male" is selected when I go to the ViewRecord page.

Adding Records (gender)

Viewing Records (gender)

I am trying to make an app with Android Studio which takes student's information and stores them in the database. Part of that information is the student's gender.

When the student selects a radio button (either male or female), that selection gets added to the database.

I have attempted the coding for it but my app crashes whenever I open it...

This is the layout code (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>

This is the main activity (java code)

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);
}
 }

This is the database (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});
}

  }

This is the error log

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.
s98
  • 45
  • 8
  • 1
    "turn radio button into string" ... explain? – Stultuske Sep 25 '18 at 11:03
  • Basically, when the user selects a gender through the radio buttons, their gender gets stored into the database. In order to store radio buttons, we convert it into string (that's what I found out). If you have any other way to store radio button results into the database, please tell me :) – s98 Sep 25 '18 at 11:04
  • Can you share the crashlog maybe? Also I suspect you might want to move your int selectedid = radioGenderGroup.getCheckedRadioButtonId(); directly in your onclicklistener, otherwise it will always reference the button selected at the moment of the view creation. – Macmist Sep 25 '18 at 11:09
  • If there's a crash, then there's a crash log and [Unfortunately MyApp has stopped. How can I solve this?](https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this) has some instructions for acquiring and interpreting it. – Markus Kauppinen Sep 25 '18 at 11:11
  • 1
    Are you unable to get the data from RadioButton? or Are you not able to insert it in DB? – Ümañg ßürmån Sep 25 '18 at 11:11
  • 1
    paste your error log. Check which line causing the error. – bluetoothfx Sep 25 '18 at 11:18
  • @UmangBurman The main app crashes when I open it because there are errors with storing the radio buttons into the database – s98 Sep 25 '18 at 11:33
  • s98, There was some issues I found, Check my answer, Follow the steps, It will Work. – Ümañg ßürmån Sep 25 '18 at 11:58

3 Answers3

0

If you are looking for how you can catch the input from radio group. Here is a little hint for you. You also need to get RadioButton id and implement a listener. That's all.

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
                }
        }
    });
bluetoothfx
  • 643
  • 9
  • 23
0

In onCreate method

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

Then override onCheckedChanged method

@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;

    }
}
Radinika
  • 31
  • 1
  • 1
  • 3
0

Solution:

Firstly, set any one of the RadioButton as:

android:checked="true" 

So it should look like:

<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" />

This will give you by default as Male text in String gender.

Secondly, remove this line: String gender = String.valueOf(radioGenderButton.getText()); from this part.

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

then,

Write this:

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

Inside onClick() as shown:

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();
            }
        }
);

With the above steps, you will get whatever gender you select and then pass it to database for inserting.

Hope it helps.

Ümañg ßürmån
  • 9,695
  • 4
  • 24
  • 41
  • THANK YOU sooo much! it worked. But when I viewed the records, it gave me "male" as the selected gender when I selected "female"... I will edit this post and show what is happening through an image. – s98 Sep 25 '18 at 12:36
  • Cool.. I've updated my Answer, @s98 check it out. Accept it if it works please :) – Ümañg ßürmån Sep 25 '18 at 12:43
  • THANK YOU SO MUCH! worked perfectly! I gave a thumbs up to your answer...it didn't get accepted since I don't have enough reps.. But thank you so much! – s98 Sep 25 '18 at 12:55