使用Android中的Fragment在SQLite数据库中添加数据

时间:2016-06-11 13:53:52

标签: android sqlite android-fragments

我正在尝试使用Fragment在SQLite数据库中添加数据,但它不是在数据库中添加,并且在运行应用程序时没有错误。 我在AddRoom片段中的代码:

public class AddRoom extends Fragment implements View.OnClickListener {

DatabaseHotel myHotel;
Button bt_addRoom;
EditText ed_roomtype, ed_roomPrice, ed_noOfRoom;
View view;
Context context;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    myHotel = new DatabaseHotel(getActivity());
    view = inflater.inflate(R.layout.addroom, container, false);

    bt_addRoom = (Button)view.findViewById(R.id.bt_addroom);

    ed_roomtype = (EditText)view.findViewById(R.id.ed_roomtype);
    ed_roomPrice = (EditText)view.findViewById(R.id.ed_roomprice);
    ed_noOfRoom = (EditText)view.findViewById(R.id.ed_noofrooms);

    return view;
}

@Override
public void onClick(View v) {
    bt_addRoom.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            addRoom();
        }
    });
}


private  void addRoom(){
    String roomType = ed_roomtype.getText().toString();
    int roomPrice = Integer.parseInt(ed_roomPrice.getText().toString());
    int noOfRoom = Integer.parseInt(ed_noOfRoom.getText().toString());

    boolean inserted = myHotel.addRoom(roomType, roomPrice, noOfRoom);
    if (inserted){
        Message.message(context, "Room Added Succeccfully");
    }else {
        Message.message(context, "Room Not Added!!");
    }
}
}

在我的数据库类中:addRoom()方法代码:

  public boolean addRoom(String roomType, int roomPrice, int numberOfRoom){
        SQLiteDatabase db = mydb.getReadableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(Database.ROOM_TYPE, roomType);
        cv.put(Database.ROOM_PRICE, roomPrice);
        cv.put(Database.NUMBER_OF_ROOMS, numberOfRoom);
        try {
            long result = db.insert(Database.ROOM_TABLE,null, cv);
            if (result == -1){
                return false;
            }else {
                return true;
            }
         }catch (SQLException e){
            Message.message(context, e+"");
        }
        return true;
    }

2 个答案:

答案 0 :(得分:2)

我想你错过了

bt_addRoom.setOnClickListener(this);
onCreateView(..)中的

。您应该首先注册OnClickListener

答案 1 :(得分:1)

MD说...但你可能也想要mydb.getWriteableDatabase();而不是getReadableDatabase()