0

I have problem with retrieving ID from table.

In the project I have SQLite database which contains two tables: students and departments.

Departments table is completed by me. I read data from this table by Spinner. how can I get the id of the department from table and save it into student table ?

I don't want to save data into department table, because it's completed.

AddActivity.class:

public class AddActivity extends AppCompatActivity implements OnClickListener {

private DatabaseHandler dbCreate;
EditText etImie, etNazwisko, etIndeks, etEmail, etWydzial, etKierunek, etTelefon, etShow;
Button btnSave, btnDisplay;
Spinner spSpinner;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    etImie = (EditText)     findViewById(R.id.etImie);
    etNazwisko = (EditText) findViewById(R.id.etNazwisko);
    etIndeks = (EditText)   findViewById(R.id.etIndeks);
    etEmail = (EditText)    findViewById(R.id.etEmail);
   // etWydzial = (EditText)  findViewById(R.id.etWydzial);
    etKierunek = (EditText) findViewById(R.id.etKierunek);
    etTelefon = (EditText)  findViewById(R.id.etTelefon);
    etShow = (EditText)     findViewById(R.id.etShow);
    spSpinner = (Spinner)   findViewById(R.id.spSpinner);

    btnSave = (Button)      findViewById(R.id.btnSave);
    btnSave.setOnClickListener(this);
    btnDisplay = (Button)   findViewById(R.id.btnDisplay);
    btnDisplay.setOnClickListener(this);

    dbCreate = new DatabaseHandler(this.getApplicationContext());

    ArrayList<String> list = dbCreate.getAllDepartments();
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item,list);
    spSpinner.setAdapter(adapter);
}

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_baza_stud, menu);
    return true;
}

private void insertInStudentTable(String imie, String nazwisko, int indeks, String email, String wydzial, String kierunek, String telefon) {
    SQLiteDatabase db = dbCreate.getWritableDatabase();

    ContentValues data_2 = new ContentValues();

    data_2.put("wydzial",     wydzial);
    data_2.put("kierunek", kierunek);

    long idOfDepart = db.insertOrThrow("departments", null, data_2);

    ContentValues data = new ContentValues();

    data.put("imie",        imie);
    data.put("nazwisko",    nazwisko);
    data.put("indeks", indeks);
    data.put("email", email);
    data.put("numer", telefon);
    data.put("dept_id", idOfDepart);

    db.insertOrThrow("students", null, data);
}



public void onClick(View v) {
    if(v.getId() == R.id.btnSave) {
        try {
            String imie =       etImie.getText().toString();
            String nazwisko =   etNazwisko.getText().toString();
            String sIndex =     etIndeks.getText().toString();
            int indeks =        Integer.parseInt(sIndex);
            String email =      etEmail.getText().toString();
            String wydzial =    etWydzial.getText().toString();
            String kierunek =   etKierunek.getText().toString();
            String telefon =    etTelefon.getText().toString();

            if(imie.length() == 0 || nazwisko.length() == 0 || sIndex.length() == 0 || email.length() == 0 || wydzial.length() == 0 || kierunek.length() == 0 || telefon.length() == 0){
                Toast.makeText(getApplicationContext(),"Fill data.", Toast.LENGTH_SHORT).show();
            }else{
                insertInStudentTable(imie, nazwisko, indeks, email, wydzial, kierunek, telefon);
                Toast.makeText(getApplicationContext(), "Student has been created: " + imie + " " + nazwisko + " .", Toast.LENGTH_SHORT).show();
            }
        } catch (SQLiteException e) {
            System.err.println(e.toString());
        } finally {
            dbCreate.close();
        }
    }

}// end of onClick method}

DatabaseHandler.class:

 public class DatabaseHandler extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 2;
    private static final String TAG = "DatabaseHandler";
    private static final String DATABASE_NAME = "studencibazadb.db";

    private static final String ID_COLUMN = "id";

    // pola tabeli "wydzial"
    public static final String TABLE_DEPARTMENTS = "departments",
            KEY_DEPARTMENT =        "wydzial",
            KEY_SPECIALIZATION =    "kierunek";
    // pola tabeli "students"
    public static final String TABLE_STUDENTS = "students",
            KEY_FIRSTNAME =         "imie",
            KEY_SURNAME =           "nazwisko",
            KEY_INDEKS =            "indeks",
            KEY_EMAIL =             "email",
            KEY_NUMER =             "numer",
            STUDENT_DEPARTMENT_ID = "dept_id";

    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE " + TABLE_DEPARTMENTS + "(" + ID_COLUMN + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_DEPARTMENT + " TEXT NOT NULL," + KEY_SPECIALIZATION + " TEXT NOT NULL)");
        db.execSQL("CREATE TABLE " + TABLE_STUDENTS + "(" + ID_COLUMN + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_FIRSTNAME + " TEXT NOT NULL," + KEY_SURNAME + " TEXT NOT NULL," + KEY_INDEKS + " INTEGER NOT NULL," + KEY_EMAIL + " TEXT NOT NULL," + KEY_NUMER + " TEXT NOT NULL," + STUDENT_DEPARTMENT_ID + " INT)");
    }

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

    public ArrayList<String> getAllDepartments() {
        ArrayList<String> list = new ArrayList<String>();
        SQLiteDatabase db = this.getReadableDatabase();
        db.beginTransaction();
        try{
            String selectQuery = "SELECT * FROM " + TABLE_DEPARTMENTS;
            Cursor cursor = db.rawQuery(selectQuery, null);

            if(cursor.getCount() > 0){
                while(cursor.moveToNext()){
                    String depname = cursor.getString(cursor.getColumnIndex("wydzial"));
                    list.add(depname);
                }
            }
            db.setTransactionSuccessful();
        }catch(SQLiteException e){
            e.printStackTrace();
        }
        finally{
            db.endTransaction();
            db.close();
        }
        return list;
    }
}
ArtKorchagin
  • 4,801
  • 13
  • 42
  • 58
pank_94
  • 13
  • 7

1 Answers1

0

In your "getDepartments()" function, you can retrieve the department ID while you're retrieving the "wydzial" value, like so:

Integer depId = cursor.getString(cursor.getColumnIndex("id"));

How you store it for use is up to you. I would suggest a HashMap where the index is the ID, and the value is depName.

MHardwick
  • 659
  • 3
  • 9
  • And how can I add this ID into "insertInStudentTable()" function? – pank_94 Nov 03 '15 at 22:34
  • Are you getting an error from the insertInStudentTable function? If so, can you paste it? – MHardwick Nov 03 '15 at 22:40
  • Without more information, my best guess as to what's going wrong is that you have the etWydzial initialization commented out, and that's causing either an error or causing the insertInStudentTable function not to run at all. – MHardwick Nov 03 '15 at 23:15
  • I need to delete some code, but I don't want to insert data to TABLE_DEPARTMENT - in this table data is exists and I want to retrieve ID of departments from it and paste in TABLE_STUDENT: in which the department what student - do you know what I mean? – pank_94 Nov 04 '15 at 10:48
  • `String depname = cursor.getString(cursor.getColumnIndex("wydzial"));` `String depId = cursor.getString(cursor.getColumnIndex("id"));` `list.add(depname);` `list.add(depId);` it's like this, but I want to insert the ID into student table. – pank_94 Nov 04 '15 at 11:11
  • In Spinner I'm retrieving name of department - it's cool. What I mean is when I'm choosing department like "Psychology" I want to get the ID of this department and paste it into table student. – pank_94 Nov 04 '15 at 11:53