簡體   English   中英

安卓。 SQLite 數據庫

[英]Android. SQLite Database

我在從 DEPARTMENT_TABLE 中的 ID_COLUMN 獲取 ID 時遇到問題。 我想獲取這個 id 並將其插入第二個表 - STUDENT_TABLE。

我有兩個表的數據庫。 一張表供學生使用,是空的 - 用戶將數據插入表中。 第二個是部門,這里有2個部門。

如果用戶選擇了 ID=2 的部門,這個 ID 必須插入到學生表的 DEPARTMENT_ID 列中。

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"));
                //String depId = cursor.getString(cursor.getColumnIndex("id"));
                list.add(depname);
                //list.add(depId);
            }
        }
        db.setTransactionSuccessful();
    }catch(SQLiteException e){
        e.printStackTrace();
    }
    finally{
        db.endTransaction();
        db.close();
    }
    return list;
}

public Cursor getAllData(){
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_STUDENTS, null);
    return cursor;
}

}

AddActivity.class

public class AddActivity extends AppCompatActivity implements OnClickListener {

private DatabaseHandler dbCreate;
EditText etImie, etNazwisko, etIndeks, etEmail, 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);
    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 telefon) {
    SQLiteDatabase db = dbCreate.getWritableDatabase();

   // ContentValues data_2 = new ContentValues();

    //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 telefon =    etTelefon.getText().toString();

            if(imie.length() == 0 || nazwisko.length() == 0 || sIndex.length() == 0 || email.length() == 0 || telefon.length() == 0){
                Toast.makeText(getApplicationContext(),"Fill data.", Toast.LENGTH_SHORT).show();
            }else{
                insertInStudentTable(imie, nazwisko, indeks, email, 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();
        }
    }

}

}

android 中的查詢按從左到右(0 到 N)的順序檢索帶有信息的游標。 運行查詢並驗證要使用的列的位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM