2016-06-11 114 views
-1

我想使用Fragment在SQLite數據庫中添加數據,但它不是在數據庫中添加並且在運行應用程序時沒有錯誤。 我在AddRoom片段代碼:在Android中使用Fragment在SQLite數據庫中添加數據

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

我想你在onCreateView(..)錯過

bt_addRoom.setOnClickListener(this); 

。您應該首先註冊OnClickListener

+0

它不工作:( –

1

什麼MD說...但你可能還需要mydb.getWriteableDatabase();而不是getReadableDatabase()以及