0

我从表中检索 ID 时遇到问题。

在项目中,我有 SQLite 数据库,其中包含两个表:学生和部门。

部门表由我完成。我通过 Spinner 从该表中读取数据。如何从表中获取部门的 ID 并将其保存到学生表中?

我不想将数据保存到部门表中,因为它已经完成了。

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

1 回答 1

0

在“getDepartments()”函数中,您可以在检索“wydzial”值时检索部门 ID,如下所示:

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

如何存储以供使用取决于您。我会建议一个 HashMap,其中索引是 ID,值是 depName。

于 2015-11-03T22:30:40.627 回答