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);
Related
I'm new in this programming in Android Studio.I have a problem with this code that I write from a tutorial.
public void onClick(View v){
if (editusername.getText().toString().trim().length() == 0 || editpassword.getText().toString().trim().length() ==0) {
Toast.makeText(getApplicationContext(), "Semua Kolom harus Diisi", Toast.LENGTH_SHORT).show();}
else try{ String username = editusername.getText().toString().trim();
String password = editpassword.getText().toString().trim();
String query = "Select * From User where username = '"+username+"'";
if(DbManager.fetch().getCount()>0){
Toast.makeText(getApplicationContext(), "Already Exist!", Toast.LENGTH_SHORT).show();
}else{
DbManager.insert(username, password);
Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();
}
}catch (Exception e) {
e.printStackTrace();
}
In the 'fetch' and 'insert' Method there was an error of 'cannot be referenced as static method'.
This is the code in the corresponding class DbManager
public void insert(String usn, String pwd) {
ContentValues contentValue = new ContentValues();
contentValue.put(SQLiteHelper.USERNAME, usn);
contentValue.put(SQLiteHelper.PASSWORD, pwd);
this.database.insert(SQLiteHelper.TABLE_NAME_USER, null, contentValue);
}
public Cursor fetch() {
Cursor cursor = this.database.query(SQLiteHelper.TABLE_NAME_USER, new String[]{SQLiteHelper._ID, SQLiteHelper.USERNAME, SQLiteHelper.PASSWORD}, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
You never created an instance of the DbManager class.
Adding an DbManager manager = new DbManager(); and then using manager.fetch() and manager.insert(params...) should solve your problem.
Doing Class.Method() is only possible if Method() was declares as public static void Method(). If it wasn't, you need to first create an object, then call the method on that object like I showed you above.
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.
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();
I want my Onclick method that is used used to insert data into a database to first check if data exist. If there is data, a toast message appears. how can I accomplish this. My OnClick is below. I just it to verify there is a username and password. If there is, the user receives a toast.
#Override
public void onClick (View v) {
rUsername = rName.getText().toString();
rPasscode = rCode.getText().toString();
RegDetails regDetails = new RegDetails();
regDetails.setrName(bundleRegName);
regDetails.setpCode(bundleRegCode);
if(v.getId()==R.id.rtn_button){
finish();
}else if(v.getId()==R.id.reg_button){
insertCredentials(regDetails);
}
}
private void insertCredentials(RegDetails regDetails){
LoginDB androidOpenDBHelper = new LoginDB(this);
SQLiteDatabase sqliteDB = androidOpenDBHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(LoginDB.COLUMN_NAME_USERNAME, rUsername);
contentValues.put(LoginDB.COLUMN_NAME_PASSWORD, rPasscode);
long affectedColumnid = sqliteDB.insert(LoginDB.TABLE_NAME_CREDENTIALS, null, contentValues);
Toast.makeText(getApplicationContext(), "Credentials Saved! Please login" + affectedColumnid, Toast.LENGTH_SHORT).show();
sqliteDB.close();
finish();
}
}
The sqliteDB.insert return long value on success and -1 on error. The long value indicates the row number for newly inserted row in db. You can check this return value and display toast accordingly.
Please look at the detailed explanation here, http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#insert(java.lang.String, java.lang.String, android.content.ContentValues)
In short, modify your code to be like this,
private void insertCredentials(RegDetails regDetails){
LoginDB androidOpenDBHelper = new LoginDB(this);
SQLiteDatabase sqliteDB = androidOpenDBHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(LoginDB.COLUMN_NAME_USERNAME, rUsername);
contentValues.put(LoginDB.COLUMN_NAME_PASSWORD, rPasscode);
long affectedColumnid = sqliteDB.insert(LoginDB.TABLE_NAME_CREDENTIALS, null, contentValues);
if(affectedColumnid != -1){
Toast.makeText(getApplicationContext(), "Credentials Saved! Please login" + affectedColumnid, Toast.LENGTH_SHORT).show();
}else{
// Display error dialog or smthg
}
sqliteDB.close();
finish();
}
Read your database . If cursor.getCount() >0 thats mean data exists.
Cursor cursor = getDbEntries();
if( cursor.getCount() > 0 ){
// data exists
}
else{
// data doesnt exist
}
I am trying to develop a quiz app for physics, but I keep getting the error
02-23 16:02:06.006: E/Database(9348): on sqlite3_open_v2("data/data/com.mcq.srm/databases/q.db", &handle, 1, NULL) failed
Code Snippet below
public class QuestionPane extends Activity {
int counter =00;
RadioButton radioButton;
TextView Question;
TextView tvScore;
Button Next;
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.questionpane);
int resdb=0;
try {
SQLiteDatabase checkDB = null;
String DB_FULL_PATH = "data/data/com.mcq.srm/databases/q.db";
checkDB = SQLiteDatabase.openDatabase(DB_FULL_PATH, null,
SQLiteDatabase.OPEN_READONLY);
checkDB.close();
//Toast.makeText(this,"db "+checkDB, Toast.LENGTH_LONG).show();
resdb=0;
Log.v("msg","Database created");
} catch (Exception e){
resdb=1;
}
Log.v("msg", "check res-->"+resdb);
try{
db = openOrCreateDatabase("q.db" , SQLiteDatabase.CREATE_IF_NECESSARY , null );
if(resdb==1)
{
Log.v("msg","creating tables");
CreateTable();
InsertData();
displayres();
}
}
catch(Exception e){
}
}
public void CreateTable(){
String Createtab;
Createtab =" CREATE TABLE tbl_Question ("+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, Questions TEXT, option_1 TEXT,option_2 TEXT, option_3 Text, option_4 TEXT, correct_answer TEXT);";
try{
db.execSQL(Createtab);
}
catch(Exception e){
}
}
public void InsertData(){
ContentValues values = new ContentValues();
values.put("question", "Two beams of red and violet colours are made to pass separately through a prism of A = 60°. In the minimum deviation position, the angle of refraction inside the prism will be");
//... value.put statements removed
db.insert("tbl_Question", null, values);
//.. values.put statements removed
values.put("correct_answer","35 grams");
db.insert("tbl_Question", null, values);
}
public void displayres() {
int qno=1;
String sql1="select * from question;";
Cursor c1=db.rawQuery(sql1,null);
Log.v("answer","asd");
String que,opt1,opt2,opt3,opt4;
startManagingCursor(c1);
c1.moveToFirst();
que=c1.getString(c1.getColumnIndex("Question1"));
Log.v("answer",que);
}
}
There are lot of mistakes in your I'll suggest you go through this example, it's best to start with that example in android.You need to create separate class for Database generally know as Database Adapter and one more that is Database Helper by Android Devs. So to get complete idea go through that example.