-1

I have a problem saving and displaying an image using SQLite ,then display the data with a RecyclerView. My intention is to get the information of the user, within it its genre through RadioButton, to finally show the data and an image distinguishing between man and woman. All was OK trying to do it without image, just text, but when I added the necessary to the image, the app failed.

I pointed with "/ * ??HERE * /" where I suppose there is a problem.

I really hope you can help me. Thanks.

public class MainActivity extends AppCompatActivity {

    EditText edtNames, edtLastNames, edtId;
    Button btnRegister, btnShow;
    RadioButton rdbtnMale, rdbtnFemale;
    int imgStudent;

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

        edtNames= (EditText) findViewById(R.id.edtNames);
        edtLastNames= (EditText) findViewById(R.id.edtLastNames);
        //...etc, etc ->linkinkgs

        final SQLiteDb sqLiteDb =new SQLiteDb(getApplicationContext());

        // ??HERE
        if(rdbtnMale.isChecked()){
            imgStudent = R.drawable.boy;
        }else if(rdbtnFemale.isChecked()){
            imgStudent = R.drawable.girl;
        }

        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sqLiteDb.AddStudents(edtNames.getText().toString(),
    edtLastNames.getText().toString(), edtId.getText().toString(),imgStudent /* ??HERE*/);
                Toast.makeText(getApplicationContext(),"Was added correctly",
     Toast.LENGTH_SHORT).show();
            }
        });

        btnShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent showStudents = new Intent(getApplicationContext(),StudentsActivity.class);
                startActivity(showStudents);
            }
        });
    }
}

The Student class

public class Student {

    private String Names, LastNames, Id;
    private int Image;

    public Student(String names, String lastnames, String id, int imageStudent) {
        //...parameters
    }
    // + Getters and Setters
}

The Database Helper class

public class SQLiteDb extends SQLiteOpenHelper {

        private static final String TABLE_STUDENTS = "CREATE TABLE STUDENTS(NAMES TEXT, 
    LASTNAMES TEXT,ID TEXT, IMAGEN INT)";

    public SQLiteDb(Context context) {
        super(context, "db_students", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(TABLE_STUDENTS);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS TABLE_STUDENTS");
        onCreate(sqLiteDatabase);
    }

    public void AddStudents(String names, String lastnames, String id,/*??HERE*/ int img) {
        SQLiteDatabase bd = getWritableDatabase();
        if (bd != null) {
            bd.execSQL("INSERT INTO STUDENTS VALUES('" + names + "','"
    + lastnames + "','" + id + "','" + img + "')");
            bd.close();
        }
    }

    public List<Student> ShowStudents() {
        SQLiteDatabase bd = getReadableDatabase();
        Cursor cursor = bd.rawQuery("SELECT * FROM STUDENTS", null);
        List<Student> students = new ArrayList<>();

        if (cursor.moveToFirst()) {
            do {
                students.add(new Student(cursor.getString(0), cursor.getString(1)
    , cursor.getString(2),/*??HERE*/ cursor.getInt(3)));
            } while (cursor.moveToNext());
        }
        return students;
    }
}

And the adapter :-

public class AdapterStudentList extends RecyclerView.Adapter<AdapterStudentList.ViewHolder> {

    public static  class  ViewHolder extends RecyclerView.ViewHolder{

        private TextView CompleteName;
        ImageView ImageStudent;

        public ViewHolder(View itemView) {
            super(itemView);
            CompleteName =(TextView)itemView.findViewById(R.id.tvCompleteName);
            ImageStudent = (ImageView)itemView.findViewById(R.id.imgStudent);
        }
    }

    public List<Student> studentsList;
    public AdapterStudentList(List<Student>studentsList){
        this.studentsList = studentsList;
    }

    //@NonNull
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_student,parent,false);
        ViewHolder  viewHolder= new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.CompleteName.setText(studentsList.get(position).getNames()+" "+ studentsList.get(position).getLastNames());
        holder.ImageStudent.setImageResource(studentsList.get(position).getImagen());
    }

    @Override
MikeT
  • 51,415
  • 16
  • 49
  • 68
user129270
  • 11
  • 5
  • Please add your adapter class and why don't you save gender rather than R.drawable.boy/R.drawable.girl in your database and use it for displaying correct image? – hosseinAmini May 30 '19 at 02:53
  • What failed you? Any errors? – John Joe May 30 '19 at 02:56
  • hosseinAmini I already passed the Adapter class ... Emm I have not done it that way because I know how to do it, I'm starting to learn all this jeje :s – user129270 May 30 '19 at 03:07
  • John Joe that ran when I only used the texts and hadn't tried to do it with the images, now it executes but dies when I press any button. – user129270 May 30 '19 at 03:10
  • @user129270 post the dies message. – John Joe May 30 '19 at 03:14
  • the app closes and message just is "the application has stopped" – user129270 May 30 '19 at 03:20
  • check your logcat tab. Sure have error message there. – John Joe May 30 '19 at 03:22
  • Ooh you're right, I'm gonna do it just give a second for that. – user129270 May 30 '19 at 03:34
  • 1
    Yeah you were right. The message is: "E/SQLiteLog: (1) table STUDENTS has 3 columns but 4 values were supplied". it is not assumed that the table had 4 columns in the part: private final static String TABLE_ALUMNOS = "CREATE TABLE STUDENTS (NAMES TEXT, LAST NAME TEXT, ID TEXT, IMAGE TEXT)"; ?? – user129270 May 30 '19 at 04:14
  • You already asked this question: https://stackoverflow.com/questions/56371711/how-to-create-a-table-with-4-columns-using-sqlite?noredirect=1 – Phantômaxx May 30 '19 at 06:37
  • Fantômas Yeah that was after seeing my error here, but I found the answer, would be better delete that? – user129270 May 30 '19 at 06:54

1 Answers1

1

Considering the comment :-

Yeah you were right. The message is: "E/SQLiteLog: (1) table STUDENTS has 3 columns but 4 values were supplied". it is not assumed that the table had 4 columns in the part: private final static String TABLE_ALUMNOS = "CREATE TABLE STUDENTS (NAMES TEXT, LAST NAME TEXT, ID TEXT, IMAGE TEXT)"; ??

The most likely cause is that although you have changed the schema (added the IMAGE column at a guess) the onCreate only runs when the database is created. The database persists (only gets created once and the data is stored as part of the App).

When developing an App and if the data is expendable then the quickest fix is to either delete the App's data or to uninstall the App (both delete the database) and then rerun the App.

As the onUpgrade methed drops the table and calls the onCreate, you have the additional option of increasing the database version number e.g. change super(context, "db_students", null, 1); to super(context, "db_students", null, 2); (the 4th parameter is the database version)

With regard to the radio button selection then you could use something like :-

public class MainActivity extends AppCompatActivity {

    RadioButton rdbtnMale, rdbtnFemale;
    RadioGroup rgrpGender; //<<<<<<<<<<< ADDED
    Button btnRegister;
    int imgStudent; //<<<<<<<<<< Not needed

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rdbtnMale = this.findViewById(R.id.rdbtnMale);
        rdbtnFemale = this.findViewById(R.id.rdbtnFemale);
        btnRegister = this.findViewById(R.id.btnRegister);
        rgrpGender = this.findViewById(R.id.rgrpGender); //<<<<<<<<<< ADDED

        // ??HERE - NOTHING COMMENTED OUT
        /**
        if(rdbtnMale.isChecked()){
            imgStudent = R.drawable.boy;
        }else if(rdbtnFemale.isChecked()){
            imgStudent = R.drawable.girl;
        }
        **/
        //............ other code

        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int studentGender;
                switch(rgrpGender.getCheckedRadioButtonId()) {
                    case R.id.rdbtnMale:
                        studentGender = 0;
                        break;
                    case R.id.rdbtnFemale:
                        studentGender = 1;
                        break;
                    default:
                        studentGender = -1;
                        break;
                }
                Log.d("SAVING","Student is gender " + String.valueOf(studentGender) + "\t(1 = Male 0= Female)"); //TODO Remove before publishing
                //<<<<<<<<<< COMMENTED OUT FOR DEMO >>>>>>>>>>
                //sqLiteDb.AddStudents(edtNames.getText().toString(),edtLastNames.getText().toString(), edtId.getText().toString(),studentGender);
            }
        });
    }
}
  • The above allows additional RadioButtons for other genders just add the appropriate case(s)

  • The above can be run on it's own with an appropriate layout.

In essence you aren't saving the image but an indicator of the gender.

MikeT
  • 51,415
  • 16
  • 49
  • 68
  • Mike Thanks again! In fact that was the problem, the app runs but I now I don't know why the image don't change when I select the gender with the radio button :( ,Do you have some idea why? – user129270 May 30 '19 at 05:32
  • You don't ever appear to change the value of imgStudent. You need to change it's value when the Radio button is clicked. I also believe that saving R.drawable.?? isn't what you really want. I believe that the value could change as they are numbers generated based upon the code. – MikeT May 30 '19 at 05:44
  • Umm yeah it sounds razonable...Although that's the only example I've found. I'll research how to do it, any way thank you again for your help. – user129270 May 30 '19 at 06:01
  • @user129270 I may have a look but I have things to do at the moment. – MikeT May 30 '19 at 06:02
  • MikeT Don't worry, you've helped me a lot with the above, at least I'm not stuck with the same thing anymore xD. – user129270 May 30 '19 at 06:06