I have fragment class in that i am calling the database handler method which takes model class as a argument which is Manager and that class takes two variable one is int and another one is String, but i am getting an error:
The method addManager(Manager) in the type DatabaseConnection is not
applicable for the arguments (int, String)
Here is the code of the addManager() and where it's called
Fragment Class Manager
public void onClick(View v) {
DatabaseConnection db = new DatabaseConnection(getActivity());
db.**addManager**(Integer.parseInt(text1.getText().toString()),
text2.getText().toString());
Database Handler
void addManager(Manager manager1) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(M_ID, manager1.getMid());
values.put(M_NAME, manager1.getMname()); // Name
// Inserting Row
db.insert(TABLE_NAME, null, values);
db.close(); // Closing database connection
}
There are two ways to make it work.
Option 1: Change addManager() to this
void addManager(int managerId, string managerName) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(M_ID, managerId);
values.put(M_NAME, managerName); // Name
// Inserting Row
db.insert(TABLE_NAME, null, values);
db.close(); // Closing database connection
}
Option 2: Change the call parameter to this
public void onClick(View v) {
DatabaseConnection db = new DatabaseConnection(getActivity());
Manager aManager = new Manager();
aManager.setMid(Integer.parseInt(text1.getText().toString()));
aManager.setMname(text2.getText().toString());
db.addManager(aManager);
}
Related
Hi I'm new to Android Java and SQLite, I'm trying to make an onClick listener change the value in the column from 1 to 2 but I'm confused about what I need to do. I tried doing some research on it but seem to get the basic way of updating your entries you added. Can anyone help me with this?
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (database.updateReserved() == 1) {
database.updateReserved(reserved);
}
}
});
public void updateReserved(Integer reserved){
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("reserved",reserved);
String tableName="cars"; //Table Name
db.update(tableName , contentValues, "=" + reserved,null) ;
}
If you want to make sure that only rows with reserved = 1 will be updated, change updateReserved() so that both the current value and the new value of reserved are passed as arguments.
So, in the 3d argument of update(), which is the WHERE clause, pass the current value:
public void updateReserved(int oldReserved, int newReserved) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("reserved", newRreserved);
String tableName = "cars";
db.update(tableName, contentValues, "reserved = ?", new String[] {String.valueOf(oldReserved)}) ;
}
Now you can simplify the click listener like this:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
database.updateReserved(1, reserved);
}
});
I have a method in my activity class which should print a random role to the player (stores in an SQLite database). I am getting a success message but it is not being carried out. I only have 1 record in my SQLite database so far and will be adding a while loop after to populate each row.
This is my my activity class:
public class StartGame extends AppCompatActivity implements View.OnClickListener {
DatabaseHelper myDb;
Button btnRoles;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_startgame);
myDb = new DatabaseHelper(this);
btnRoles = (Button) findViewById(R.id.btnAssignRoles);
assignRoles();
}
public String RandomNumber() {
List < String > roles = Arrays.asList("Mafia", "Mafia", "Angel", "Detective", "Civilian", "Civilian", "Civilian");
Collections.shuffle(roles);
return roles.get(0);
}
public void assignRoles() {
btnRoles.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
{
boolean isUpdated = myDb.updateRole(RandomNumber().toString());
if (isUpdated == true)
Toast.makeText(StartGame.this, "Roles assigned, keep them secret!", Toast.LENGTH_LONG).show();
else
Toast.makeText(StartGame.this, "UNSUCCESSFUL!", Toast.LENGTH_LONG).show();
}
}
}
);
}
And this is the method in my Database Helper class:
public boolean updateRole(String role){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_ROLE, role);
db.update(TABLE_NAME, contentValues, "Role =?", new String[] {role});
return true;
}
What am I doing wrong?
You got an error in this line:
db.update(TABLE_NAME, contentValues, "Role =?", new String[] {role});
You are updating all the rows in the table where Role = {role} to have the column Role the value {role}. So obviously this will have no effect.
You need to have some thing like id and use that in your where statement, some thing like this:
db.update(TABLE_NAME, contentValues, "id =?", new String[] {id});
I have a custom List which holds information stored from a online mysql database. I now want to put this List into a sqlite internal database. The table has already been created in the database. I also have a databasehelper class which is working fine.
All the list information is stored in FoodInfoModel class which is made of get and set properties.
Do I create a method in the databasehelper class to insert the whole list at once? not sure how to go about it.
Current Method in databasehelper
public void addDiet(FoodInfoModel foodinfomodel) {
SQLiteDatabase db = getReadableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_DIET_ID, foodinfomodel.getDietID());
values.put(KEY_DAY, foodinfomodel.getDay());
values.put(KEY_QTY, foodinfomodel.getQty());
values.put(KEY_TIME_FOOD, foodinfomodel.getTime());
values.put(KEY_ITEM_FOOD, foodinfomodel.getItem());
values.put(KEY_MEASURE, foodinfomodel.getMeasure());
// Inserting Row
db.insert("my_diet", null, values);
db.close(); //
}
Function to set List and Adapter
public void onFetchComplete(List<FoodInfoModel> data) {
this.data = data;
System.out.println("data is " + data);
if(dialog != null) dialog.dismiss();
// create new adapter
adapter = new DietAdapterNew(this, data);
// set the adapter to list
setListViewHeightBasedOnChildren(listview);
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
How do i add that data list to the internal sqlite db?
Thanks!
You basically need one more method.
public void addDiet(List<FoodInfoModel> foodinfomodels) {
SQLiteDatabase db = getReadableDatabase();
for( FoodInfoModel foodinfomodel : foodinfomodels ){
ContentValues values = new ContentValues();
values.put(KEY_DIET_ID, foodinfomodel.getDietID());
values.put(KEY_DAY, foodinfomodel.getDay());
values.put(KEY_QTY, foodinfomodel.getQty());
values.put(KEY_TIME_FOOD, foodinfomodel.getTime());
values.put(KEY_ITEM_FOOD, foodinfomodel.getItem());
values.put(KEY_MEASURE, foodinfomodel.getMeasure());
// Inserting Row
db.insert("my_diet", null, values);
}
db.close(); //
}
Yes, you have to create this kind of methods in DatabaseHelper class
public class DatabaseHandler extends SQLiteOpenHelper {
public void insertFoodInfo(ChatBase chat) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_DIET_ID, foodinfomodel.getDietID());
values.put(KEY_DAY, foodinfomodel.getDay());
values.put(KEY_QTY, foodinfomodel.getQty());
values.put(KEY_TIME_FOOD, foodinfomodel.getTime());
values.put(KEY_ITEM_FOOD, foodinfomodel.getItem());
values.put(KEY_MEASURE, foodinfomodel.getMeasure());
db.insert("my_diet", null, values);
db.close();
}
public void updateFoodInfo(FoodInfoModel model) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_DIET_ID, foodinfomodel.getDietID());
values.put(KEY_DAY, foodinfomodel.getDay());
values.put(KEY_QTY, foodinfomodel.getQty());
values.put(KEY_TIME_FOOD, foodinfomodel.getTime());
values.put(KEY_ITEM_FOOD, foodinfomodel.getItem());
values.put(KEY_MEASURE, foodinfomodel.getMeasure());
db.update("my_diet", values, KEY_DIET_ID + "=" + model.getId(),null);
db.close();
}
}
and then update or insert each FoodInfoModel inside the loop
And for bulk insert can use this code
db.beginTransaction();
try {
...
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
What you should create is a separate class with public static functions that process the CRUD (Create, Read, Update and Delete) functions associated with the SQL transactions.
Example (SQLcrud.java):
public static boolean insertObject(SQLdatabase localDB, Object insertObject)
{
// Test if things are not null and that the DB is open and writable.
// Insert the object
// If insert successful, return TRUE.
// If anything wrong or insert not successful return FALSE (or int indicating what went wrong.
}
Actual Example:
public static boolean insertLocalAdr(SQLiteDatabase db, PersonAddress adr, boolean deleteCurrent, boolean transaction)
throws SQLFunctionFailed {
if(db != null && adr != null)
{
try
{
// If the connection is open and writable.
SQLiteGeneral.openAndWritable(db);
if(deleteCurrent)
{
deleteLocalAdr(db, transaction);
}
String sqlStmt = GeneralSQLfunctions.getUserAdrInsert(
adr,
PersonAddress.ADR_TABLE_NAME,
GeneralSQLfunctions.databaseType.SQLITE);
return StmtExecution(db, sqlStmt, transaction);
}
catch (SQLException e)
{
e.printStackTrace();
throw new SQLFunctionFailed(e.getMessage());
}
}
else
{
throw new SQLFunctionFailed("Given DB or Adr was NULL! FATAL ERROR!");
}
}
Note: GeneralSQLfunctions.getUserAdrInsert just gets a simple formatted INSERT statement and StmtExecution simply executes the statement on the SQL DB. They are there for simplification. SQLiteGeneral.openAndWritable(db) throws a (custom) SQLFunctionFailed exception so the function fails and does not proceed.
While iterating over each list items, you can start a new AsyncTask or Thread to to make it faster.
This question already exists:
how to insert data into sq-lite database at run-time [closed]
Closed 9 years ago.
I built an application that uses sq-lite database and within the application at run-time i made a button that when pressed added a new Edit-Text i'm wondering how can i save the values in the new Edit-Text into my database? please help me
Use this method :
public long saveData(Context context, String editTextValue) {
long x = -1;
appDb = new AppDatabase(context);
sqliteDb = appDb.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("monthOfBirth", editTextValue);
try {
if (sqliteDb.isOpen()) {
x = sqliteDb.insert("password", null, values);
if (x >= 0)
{
Toast.makeText(context, "Password Save", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception exc) {
exc.printStackTrace();
}
return x;
}
Call this method in your button's onClickListener()
button.setOnCLickListener(new View.OnClickListener())
{
#override
public void onClick(View v)
{
if(editText.getText().toString.equals(""))
{
Toast.makeText(context, "Fill Value first.", Toast.LENGTH_SHORT).show();
return;
}
saveData(YourActivity.this, editText.getText().toString());
}
}
Have you created the class extending SQLiteOpenHelper? If you have it, then use the constructor and get an object of this class:
dbHelper = new SQLiteHelper(context, getString(R.string.db_name_dev), null, DB_VERSION);
And then for example:
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("term", term);
db.insert("Search", null, cv);
Simply make a String which contains insert query of SQL. Then call the method
db.execSQL(sql);
on your datebase refence variable.
String sql =
"INSERT INTO <TABLE_NAME> VALUES('this is','03/04/2005','5000','tran','y')" ;
db.execSQL(sql);
I am developing an android app, and i want to display the primary key in the textview so that every-time I edit a textfield, I will be using the primary key to update.can anyone help me with this? below is the inserting of data in the sqlite. My problem is how to get the primary key...
public class UsedataActivity extends Activity {
DatabaseHandler db = new DatabaseHandler(this);
ImageButton evsave;
EditText evname;
EditText evtime;
EditText evdate;
EditText evcode;
TextView evadmin;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_onetoone);
evsave = (ImageButton)findViewById(R.id.event_save);
evname = (EditText)findViewById(R.id.eventname);
evtime = (EditText)findViewById(R.id.time1);
evdate = (EditText)findViewById(R.id.eventdate);
evcode = (EditText)findViewById(R.id.eventcode);
evadmin = (TextView)findViewById(R.id.adminname_1to1);
evsave.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Events addev =
new Events(evname.getText().toString(),evcode.getText().toString(),evdate.getText().toString(),Integer.parseInt(evtime.getText().toString()),evadmin.getText().toString());
db.addEvents(addev);
Toast.makeText(getApplicationContext(), "Event: "+ evname.getText()+" successfully save",
Toast.LENGTH_SHORT).show();
}
});
}
database handler class:
public void addEvents(Events event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_EV_NAME, event.get_name());
values.put(KEY_EV_PASS, event.get_pass());
values.put(KEY_EV_DATE, event.get_date());
values.put(KEY_EV_TIME, event.get_time());
values.put(KEY_EV_ADMIN, event.get_admin());
// Inserting Row
db.insert(TABLE_EVENTS, null, values);
db.close();
}
As it can be observed from the docs for the SQLiteDatabase, db.insert will return the id of the newly created object. Just make addEvents return it (instead of being `void).
PS: Please paste code in edits of the question, not in comments. In comments they really look awful!
EDIT
public long addEvents(Events event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_EV_NAME, event.get_name());
values.put(KEY_EV_PASS, event.get_pass());
values.put(KEY_EV_DATE, event.get_date());
values.put(KEY_EV_TIME, event.get_time());
values.put(KEY_EV_ADMIN, event.get_admin());
// Inserting Row
long id = db.insert(TABLE_EVENTS, null, values);
db.close();
return id;
}
And then:
long id = db.addEvents(addev);
Toast.makeText(getApplicationContext(),
"Event with id: "+ id + " successfully saved",
Toast.LENGTH_SHORT).show();