在android studio中:如何创建带有引用的两个表?

时间:2019-06-03 18:49:25

标签: java android sqlite

我在android Studio中有一个有关酒店的项目,它有两个表(Room,Customer)的数据库。 我尝试使用外键(Room_ID)创建客户表,但是出现错误。 我如何创建它? 另一个问题,当我添加一个新房间并转到“显示房间”活动时,我添加的第一个房间没有显示,这是什么问题?

这是Database类扩展SqliteOpenHelper

  public DatabaseHelper(Context context) {
    super(context, "Hotel", null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
        db .execSQL(room.Create_table);
        db .execSQL(customer.Create_table);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("drop table " + room.Table_Name);
    db.execSQL("drop table " + customer.Table_Name);
    onCreate(db);
}
public  boolean insert_room (String name , String type , String price){
SQLiteDatabase db = getWritableDatabase() ;
    ContentValues data = new ContentValues();
    data.put(room.Col_Name,name);
    data.put(room.Col_Type,type);
    data.put(room.Col_Price,price);
    return db.insert(room.Table_Name,null ,data) >0 ;
 }
 public  boolean insert_customer (String name , String mobile , String 
 passport,int days,int room_id){
     SQLiteDatabase db = getWritableDatabase() ;

     ContentValues data = new ContentValues();
     data.put(customer.Col_Name,name);
     data.put(customer.Col_Passport,passport);
     data.put(customer.Col_Mobile,mobile);
     data.put(customer.Col_Days,days);
     data.put(customer.Col_Room_ID,room_id);

    return db.insert(customer.Table_Name,null ,data) >0 ;
}
public ArrayList<room> getAll_rooms(){
    SQLiteDatabase db = getWritableDatabase() ;

    ArrayList<room> rooms=new ArrayList<>();
    Cursor cursor = db.rawQuery("select * from " +room.Table_Name  ,null);
    if (cursor.moveToFirst()){
        while (cursor.moveToNext()){
            int id=cursor.getInt(cursor.getColumnIndex(room.Col_Id));
            String name =cursor.getString(cursor.getColumnIndex(room.Col_Name));
            String type =cursor.getString(cursor.getColumnIndex(room.Col_Type));
            String price =cursor.getString(cursor.getColumnIndex(room.Col_Price));
            room r =new room(id,name,type,price);
            rooms.add(r);
        }
    }
    cursor.close();
    return rooms;
}

public ArrayList<customer> getAll_customers(){
    SQLiteDatabase db = getWritableDatabase() ;

    ArrayList<customer> customers=new ArrayList<>();
    Cursor cursor = db.rawQuery("select * from " +customer.Table_Name ,null);
    if (cursor.moveToFirst()){
        while (cursor.moveToNext()){
            int id=cursor.getInt(cursor.getColumnIndex(customer.Col_Id));
            String name =cursor.getString(cursor.getColumnIndex(customer.Col_Name));
          int days =cursor.getInt(cursor.getColumnIndex(customer.Col_Days));
            String mobile =cursor.getString(cursor.getColumnIndex(customer.Col_Mobile));
            String passport =cursor.getString(cursor.getColumnIndex(customer.Col_Passport));
            int room_id =cursor.getInt(cursor.getColumnIndex(customer.Col_Room_ID));
            customer c =new customer(id,name,passport,mobile,days,room_id);
            customers.add(c);
        }
    }
    cursor.close();
    return customers;
}


 }

这是客户类别


      public class customer {
    int id ;
    String name ;
    String passport_num;
    String mobile;
    int num_ofDays;
    int room_id ;

    public  static  final String Col_Id = "id";
    public  static  final String Col_Name = "name";
    public  static  final String Col_Passport= "passport_num";
    public  static  final String Col_Days= "num_ofDays";
    public  static  final String Col_Mobile= "mobile";
    public  static  final String Col_Room_ID= "room_id";
    public  static  final String Table_Name= "Customer";
    public  static  final String Create_table = " create table Customer(id integer primary key autoincrement ," +
            " name text , passport_num text , mobile text , num_ofDays integer " +
            " room_id integer , FOREIGN KEY(room_id) references Room (id))";

    public customer() {
    }

    public customer(int id, String name, String passport_num, String mobile, int num_ofDays, int room_id) {
        this.id = id;
        this.name = name;
        this.passport_num = passport_num;
        this.mobile = mobile;
        this.num_ofDays = num_ofDays;
        this.room_id = room_id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassport_num() {
        return passport_num;
    }

    public void setPassport_num(String passport_num) {
        this.passport_num = passport_num;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public int getNum_ofDays() {
        return num_ofDays;
    }

    public void setNum_ofDays(int num_ofDays) {
        this.num_ofDays = num_ofDays;
    }

    public int getRoom_id() {
        return room_id;
    }

    public void setRoom_id(int room_id) {
        this.room_id = room_id;
    }
}

这是“添加客户信息”


    public class AddCustomer extends AppCompatActivity {

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

        final DatabaseHelper db=new DatabaseHelper(this);
        final Spinner type = findViewById(R.id.room_type_add);
        final EditText name = findViewById(R.id.customer_name_add);
        final EditText mobile = findViewById(R.id.mobile_num_add);
        final EditText passport = findViewById(R.id.passport_num_add);
        final EditText days = findViewById(R.id.num_days_add);
        final Button add =findViewById(R.id.addCustomer);
        final ArrayList<room> spData=db.getAll_rooms();

        room_adapter_spinner adapter=new room_adapter_spinner(this,spData);
        type.setAdapter(adapter);
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String Name = name.getText().toString();
                String Mobile = mobile.getText().toString();
                String Passport = passport.getText().toString();
                String Days = days.getText().toString() ;
                int Days_i = Integer.parseInt(Days);
                int TYpe=(int) type.getSelectedItemId();
                if (db.insert_customer(Name,Mobile,Passport,Days_i ,TYpe)) {
                    Intent i = new Intent(AddCustomer.this,ShowCustomers.class);
                    startActivity(i);
                }
                else Toast.makeText(AddCustomer.this, "error", Toast.LENGTH_SHORT).show();
            }
        });


    }

}

这是添加房间课程


public class AddRoom extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_room);
        final  DatabaseHelper db = new DatabaseHelper(this);
        final EditText name = findViewById(R.id.room_name_add);
        final Spinner type = findViewById(R.id.room_type_add);
        final EditText price = findViewById(R.id.room_price_add);
        final Button add =findViewById(R.id.addRoom);
       add.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               String name_ = name.getText().toString();
              String type_s= type.getSelectedItem().toString();
               String price_ = price.getText().toString();
               if (db.insert_room(name_,type_s,price_)) {
                   Intent i = new Intent(AddRoom.this,ShowRooms.class);
                   startActivity(i);
               }
           }
       });

    }
}

这是(显示房间)课程

public class ShowRooms extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_rooms);

        final ListView list = findViewById(R.id.list_rooms);
        DatabaseHelper db = new DatabaseHelper(this) ;
        ArrayList<room> data = db.getAll_rooms();
        room_adapter adapter = new room_adapter(this,data);
        list.setAdapter(adapter);

    }
}

当我运行项目时,我有这个错误

 Caused by: android.database.sqlite.SQLiteException: unknown column "room_id" in foreign key definition (code 1): , while compiling: create table Customer(id integer primary key autoincrement , name text , passport_num text , mobile text , num_ofDays integer  room_id integer , FOREIGN KEY(room_id) references Room (id))
        at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
        at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
        at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
        at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
        at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
        at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
        at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1663)
        at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1594)
        at com.example.the_hotel_project.DatabaseHelper.onCreate(DatabaseHelper.java:23)
        at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
        at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
        at com.example.the_hotel_project.DatabaseHelper.getAll_rooms(DatabaseHelper.java:54)
        at com.example.the_hotel_project.AddCustomer.onCreate(AddCustomer.java:32)
        at android.app.Activity.performCreate(Activity.java:5104)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 
        at android.app.ActivityThread.access$600(ActivityThread.java:141) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 
        at android.os.Handler.dispatchMessage(Handler.java:99) 
        at android.os.Looper.loop(Looper.java:137) 
        at android.app.ActivityThread.main(ActivityThread.java:5041) 
        at java.lang.reflect.Method.invokeNative(Native Method) 
        at java.lang.reflect.Method.invoke(Method.java:511) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 
        at dalvik.system.NativeStart.main(Native Method) 

2 个答案:

答案 0 :(得分:3)

Customer类的String Create_table中缺少“,”(逗号)。在num_ofDays之后。

应该是:

cleanStartTime = moment();
cleanEndTime = moment().add(100, 'days');
theDuration = moment.duration(cleanStartTime.diff(cleanEndTime)).humanize()
console.log(theDuration)

答案 1 :(得分:2)

对于第二个问题(请再次回答两个不同的问题),请依次呼叫moveToFirst()while(moveToNext())。 调用moveToFirst()时,光标位于第一个值;调用moveToNext()时,光标位于第二个位置。这就是为什么您的列表从第二个值开始的原因。

您可以做的是调用moveToFirst()并反转while循环:

if (cursor.moveToFirst()) {
    do {
        int id = cursor.getInt(cursor.getColumnIndex(room.Col_Id));
        String name = cursor.getString(cursor.getColumnIndex(room.Col_Name));
        String type = cursor.getString(cursor.getColumnIndex(room.Col_Type));
        String price = cursor.getString(cursor.getColumnIndex(room.Col_Price));
        room r = new room(id, name, type, price);
        rooms.add(r);
    } while (cursor.moveToNext());
}

或检查计数并仅致电moveToNext()

if(cursor.getCount() != 0) {
    while(cursor.moveToNext()){
        int id = cursor.getInt(cursor.getColumnIndex(room.Col_Id));
        String name = cursor.getString(cursor.getColumnIndex(room.Col_Name));
        String type = cursor.getString(cursor.getColumnIndex(room.Col_Type));
        String price = cursor.getString(cursor.getColumnIndex(room.Col_Price));
        room r = new room(id, name, type, price);
        rooms.add(r);
    }
}

getAll_customers()

使用相同的逻辑