I am new in android app developement. I tried to insert values to SQLite database through the below code;
public class cashbook extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SQLiteDatabase db;
db = openOrCreateDatabase(
"cashbookdata.db"
, SQLiteDatabase.CREATE_IF_NECESSARY
, null
);
final String Create_CashBook =
"CREATE TABLE CashData ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "Description TEXT,"
+ "Amount REAL,"
+ "Trans INTEGER,"
+ "EntryDate TEXT);";
db.execSQL(Create_CashBook);
final String Insert_Data="INSERT INTO CashData VALUES(2,'Electricity',500,1,'04/06/2011')";
db.execSQL(Insert_Data);
It shows error on emulator - The application CashBook has stopped unexpectedly.
The database and table created , but the value insertion is not working.
Please help me to resolve this issue.
Thanks.
Seems odd to be inserting a value into an automatically incrementing field.
Also, have you tried the insert() method instead of execSQL?
ContentValues insertValues = new ContentValues();
insertValues.put("Description", "Electricity");
insertValues.put("Amount", 500);
insertValues.put("Trans", 1);
insertValues.put("EntryDate", "04/06/2011");
db.insert("CashData", null, insertValues);
okk this is fully working code edit it as per your requirement
public class TestProjectActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SQLiteDatabase db;
db = openOrCreateDatabase( "Temp.db" , SQLiteDatabase.CREATE_IF_NECESSARY , null );
try {
final String CREATE_TABLE_CONTAIN = "CREATE TABLE IF NOT EXISTS tbl_Contain ("
+ "ID INTEGER primary key AUTOINCREMENT,"
+ "DESCRIPTION TEXT,"
+ "expirydate DATETIME,"
+ "AMOUNT TEXT,"
+ "TRNS TEXT," + "isdefault TEXT);";
db.execSQL(CREATE_TABLE_CONTAIN);
Toast.makeText(TestProjectActivity.this, "table created ", Toast.LENGTH_LONG).show();
String sql =
"INSERT or replace INTO tbl_Contain (DESCRIPTION, expirydate, AMOUNT, TRNS,isdefault) VALUES('this is','03/04/2005','5000','tran','y')" ;
db.execSQL(sql);
}
catch (Exception e) {
Toast.makeText(TestProjectActivity.this, "ERROR "+e.toString(), Toast.LENGTH_LONG).show();
}}}
Hope this is useful for you..
do not use TEXT for date field may be that was casing problem still getting problem let me know :)Pragna
You'll find debugging errors like this a lot easier if you catch any errors thrown from the execSQL call. eg:
try
{
db.execSQL(Create_CashBook);
}
catch (Exception e)
{
Log.e("ERROR", e.toString());
}
I recommend to create a method just for inserting and than use ContentValues.
For further info https://www.tutorialspoint.com/android/android_sqlite_database.htm
public boolean insertToTable(String DESCRIPTION, String AMOUNT, String TRNS){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("this is",DESCRIPTION);
contentValues.put("5000",AMOUNT);
contentValues.put("TRAN",TRNS);
db.insert("Your table name",null,contentValues);
return true;
}
public class TestingData extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SQLiteDatabase db;
db = openOrCreateDatabase(
"TestingData.db"
, SQLiteDatabase.CREATE_IF_NECESSARY
, null
);
}
}
then see this link link
okkk you have take id INTEGER PRIMARY KEY AUTOINCREMENT and still u r passing value...
that is the problem :)
for more detail
see this
still getting problem then post code and logcat
Since you are new to Android development you may not know about Content Providers, which are database abstractions. They may not be the right thing for your project, but you should check them out: http://developer.android.com/guide/topics/providers/content-providers.html
I see it is an old thread but I had the same error.
I found the explanation here:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
void execSQL(String sql)
Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.
void execSQL(String sql, Object[] bindArgs)
Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE.
Related
I have an app that gets JSON data from a server. I then put the parsed data into the android SQLite database and use the data as needed. This all works great, however, I am unable to find a method to update the whole table.
The scenario would be that this Json Data feed gets updated every week on the server. I have two Questions:
What am I missing or what is the method for updating the SQLite table? (currently this just duplicates the data)
public void updateTable(Product product){
SQLiteDatabase db = this.getWritableDatabase();
try{
ContentValues values = new ContentValues();
values.put(KEY_TYPE_NAME, product.getmProductTypeName());
// more columns here...
db.update(TABLE_NAME, values, null,null);
db.close();
}catch(Exception e){
Log.e("error:",e + "in updateData method")
}
What is an ideal system for updating the data? Would it be silly and bad practice to just call the method when connected to internet?
Related Code in "Main Activity":
handler = new DBHandler(this);
NetworkUtils utils = new NetworkUtils(MainActivity.this);
if (handler.getProductCount() == 0 && utils.isConnectingToInternet()) {
new JsonDataParse().execute();
}`
Related Code "DBhandler" Activity:
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE);
onCreate(db);
}
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_TYPE_NAME + " TEXT" + ")"
That is basically my CREATE TABLE String format. I just condensed to because it has 16 columns.
This is the code I added to only delete the stored data only if there was data:
if(handler.getProductCount() == 0) {
}else{
handler.deleteData();
}
Then I just just added the delete the method as suggested:
public void deleteData() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, "1", null);
}
I'm not sure what you mean by "update the whole table". It sounds to me like you just need to delete the data in the table and then use your current method to add the new data. To delete the contents you can use:
db.delete(TABLE_NAME, "1", null);
Then call your existing method to re-populate the table from the server.
What is an ideal system for updating the data? Would it be silly and bad practice to just call the method when connected to internet?
No it wouldn't be bad practice. That makes sense, as you'll only be able to reach the server if you're connected to the internet anyway.
this is my error in console :
11-29 19:06:50.295: E/AndroidRuntime(333): android.database.sqlite.SQLiteException: table usuarios has no column named email: , while compiling: INSERT INTO usuarios(username, organizacion, email) VALUES(?, ?, ?);
This is the mainActivity, with a button that goes to an Activity for create a 'Perfil' (User)[btCrearPerfil] ... and one to see the listView with them [btEditarPerfil]...
public class MainActivity extends Activity implements OnClickListener {
public static ArrayList<Perfil> lstPerfiles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstPerfiles = new ArrayList<Perfil>();
Button btCrearPerfil = (Button) findViewById(R.id.btCrearPerfil);
btCrearPerfil.setOnClickListener(this);
Button btEditarPerfil = (Button) findViewById(R.id.btEditarPerfil);
btEditarPerfil.setOnClickListener(this);
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View v) {
Intent i;
switch(v.getId()) {
case R.id.btCrearPerfil:
i = new Intent(MainActivity.this, CrearPerfil.class);
startActivity(i);
break;
case R.id.btEditarPerfil:
i = new Intent(MainActivity.this, ListaPerfiles.class);
startActivity(i);
break;
default: break;
}
}
}
This is the creator of Perfil , entered by btCrearPerfil :
public class CrearPerfil extends Activity implements OnClickListener {
private Database datos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crear_perfil);
datos = new Database(this);
Button btGuardarPerfil = (Button) findViewById(R.id.btGuardarPerfil);
btGuardarPerfil.setOnClickListener(this);
Button btCancelar = (Button) findViewById(R.id.btCancelarPerfil);
btCancelar.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.crear_perfil, menu);
return true;
}
#Override
public void onClick(View v) {
Intent i;
switch (v.getId()){
case R.id.btGuardarPerfil:
EditText eNombre = (EditText) findViewById(R.id.txtUsername);
EditText eOrganizacion = (EditText) findViewById(R.id.txtOrganizacion);
EditText eCorreo = (EditText) findViewById(R.id.txtCorreo);
CheckBox eFavorito = (CheckBox) findViewById(R.id.cbFavorito);
if ((eNombre.equals("")) || (eOrganizacion.equals("")) || (eCorreo.equals(""))){
Toast.makeText(getApplicationContext(), "Rellena los campos", Toast.LENGTH_SHORT).show();
} else {
datos.nuevoPerfil(eNombre.getText().toString(),
eOrganizacion.getText().toString(), eCorreo.getText().toString());
Perfil p = new Perfil();
p.setUsername(eNombre.getText().toString());
p.setOrganizacion(eOrganizacion.getText().toString());
p.setCorreo(eCorreo.getText().toString());
p.setFavorito(eFavorito.isChecked());
MainActivity.lstPerfiles.add(p);
eNombre.setText("");
eOrganizacion.setText("");
eCorreo.setText("");
Toast.makeText(getApplicationContext(), "Perfil guardado", Toast.LENGTH_SHORT).show();
i = new Intent(CrearPerfil.this, MainActivity.class);
startActivity(i);
}
break;
case R.id.btCancelarPerfil:
i = new Intent(CrearPerfil.this, MainActivity.class);
startActivity(i);
break;
default: break;
}
}
}
And this one, the database for SQLite creator ...
public class Database extends SQLiteOpenHelper {
private static final String BBDD_NOMBRE = "baseDatos.db";
private static String[] FROM_CURSOR = {_ID, NOMBRE_USUARIO, NOMBRE_ORGANIZACION, NOMBRE_CORREO };
private static String ORDER_BY = NOMBRE_USUARIO + " DESC";
public Database(Context contexto) {
super(contexto, BBDD_NOMBRE, null, 1 );
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLA_USUARIOS + "("
+ _ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NOMBRE_USUARIO + " TEXT NOT NULL, "
+ NOMBRE_ORGANIZACION + " TEXT NOT NULL, "
+ NOMBRE_CORREO + "TEXT NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int a, int b) {
db.execSQL("DROP TABLE IF EXISTS " + TABLA_USUARIOS);
onCreate(db);
}
public void nuevoPerfil(String n, String o, String c){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues value = new ContentValues();
value.put(NOMBRE_USUARIO, n);
value.put(NOMBRE_ORGANIZACION, o);
value.put(NOMBRE_CORREO, c);
db.insertOrThrow(TABLA_USUARIOS, null, value);
}
public Cursor getPerfiles() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.query(TABLA_USUARIOS, FROM_CURSOR, null, null, null, null, ORDER_BY);
return c;
}
}
NEED HELP PLEASE .. THANKS...
You are missing a space in your CREATE TABLE statement:
NOMBRE_CORREO + "TEXT NOT NULL);");
should be
NOMBRE_CORREO + " TEXT NOT NULL);");
This problem is mainly caused by syntax. for example, previously my code was correct. here it is:
String CREATE_PRODUCTS_TABLE = "CREATE TABLE " + TABLE_PRODUCTS + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_MESSAGEADDRESS
+ " TEXT," + COLUMN_MESSAGEBODY + " TEXT " + ")";
The above code was running correct but i added another column and it started causing the mentioned error. below is the erroneous code:
String CREATE_PRODUCTS_TABLE = "CREATE TABLE " + TABLE_PRODUCTS + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_MESSAGEADDRESS
+ " TEXT," + COLUMN_MESSAGEBODY + " TEXT" + COLUMN_MESSAGETIME + " LONG" + ")";
As you can see, when i added the new column i forgot to include a comma after type TEXT. this means that when this code is executed, there will be syntax error as the compiler will read the last part as:
COLUMN_MESSAGEBODY TEXTCOLUMN_MESSAGETIME LONG
as opposed to:
COLUMN_MESSAGEBODY TEXT, COLUMN_MESSAGETIME LONG
Solution: ensure that your syntax is correct and you heed to spaces and commas.
kindly check the below link for more info:
Android : Table has no column named "variable name" MySql Database error
This problem occurs mostly when you make a change in the database but do not delete the previous database.
Uninstall the app and then run it.
You can just specify the version like this:
private static final int VERSION = 4;
Uninstall the app, and again install it, because it can be solve by using two approaches, one by using
alter method and increment version
or
creating the table again by reinstalling the app
As #joeabala has mentioned above, much time this problem is caused by syntax like you forgot the space or commas, but if you checked there is no problem with it but youstill get the problem, maybe you need to uninstall the app on the virtual device and restart it which may help you
Uninstall the app, because a version is installed in the phone that does not have this table and therefore can not find this table
or
to raise database version and it will update the database with the newly created tables.
Check if you have any syntax errors. If no syntax errors found just uninstall and reinstall the app. After which everything should work fine.
P.S. My thoughts: This uninstalling and reinstalling is really annoying. Developers spent so much time finding the bug but at the end the solution turns out to be uninstall and reinstall. This also happens if you add permissions(e.g. Internet Access permission) to your app. This database thing is second such thing i m finding. Android Team at Google should do something about this.
You can just Update version like this: private static final int VERSION = 4;
OR
make sure that you have create correct table.
I have a table with 2 columns, a numeric id and unique text. Created like this:
String CREATE_MY_TABLE = "CREATE TABLE " + TABLE_TEST + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_FOO + " TEXT UNIQUE"
+ ")";
db.execSQL(CREATE_MY_TABLE);
I want that when I insert KEY_FOO value and it's already in the db, nothing happens. But what I get is that the id is always incremented. No new row is inserted, that's good, but the id is autoincremented.
What I'm doing to insert is as follows:
db.insertWithOnConflict(TABLE_TEST , null, values, SQLiteDatabase.CONFLICT_NONE);
I tried CONFLICT_IGNORE, CONFLICT_ABORT, CONFLICT_ROLLBACK, all the same.
The reason I need this is because other table has a foreign key on this id, thus if the id is changed, the other table points nowhere.
How I just say to let the existing entry untouched?
Try this way. In your dbhelper class write the method like following to insert.
public int insertData(String desc) {
db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
try {
db.beginTransaction();
cv.put(KEY_FOO, desc);
db.insertOrThrow(TABLE_TEST, null, cv);
db.setTransactionSuccessful();
} catch (Exception ex) {
return 1;
} finally {
db.endTransaction();
db.close();
}
return 0;
}
Then from your actvity you call this method with the parameter value of KEY_FOO. This method will return 1 if the exception is occurs (If you try insert a unique value) and it will return 0 if the transaction is successfull.
I hope this way will help you. Let me know if any problem.
I have built a database helper class with an open() method and extended sqlite helper with onCreate() overridden. (shown below). Despite all of this, I am getting 'SQLiteException, no such table' error. I do not understand, why is the openHelper not helping?
public void open() {
try{
db = openHelper.getWritableDatabase();
} catch (SQLiteException e) {
db = openHelper.getReadableDatabase();
}
}
//other stuff
public static final String database_create = "create table " + database_table + " (" + primary_key + " integer primary key autoincrement, "
+ company_column + " text not null, " + product_column + " text not null);";
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(database_create);
}
the following code is meant to insert an entry temporarily, because the database cannot be empty for other reasons. It seems to execute perfectly, yet the last bit of code, which comes after is what throws the error
CompanyAndProductDatabaseAdapter cpdAdapter = new CompanyAndProductDatabaseAdapter(this);
cpdAdapter.open();
errorguard = cpdAdapter.insertPair("Loading", "...");
cpdAdapter.close();
//other stuff
cpdAdapter.open();
Cursor cursor = cpdAdapter.getAllPairsCursor(); //error here
cursor.requery();
startManagingCursor(cursor);
I don't know why you implemented a open-method, also the database_create is not what it should be.
I assume the first code is part of CompanyAndProductDatabaseAdapter.
Take a look here:
Android - Sqlite database method undefined fot type
That's almost all you need to create/get a DB with inherted SQLiteOpenHelper.
Your problem is this function:
db = openHelper.getWritableDatabase();
db = openHelper.getReadableDatabase();
First: check your path/name of the database is correct. It can create a default database, an empty database ( no tables, no nothing) if the database is not found.
Second: try to open your database this way:
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE); // or OPEN_READONLY, depending on situation.
I am creating my SQLite database for my App at runtime if it does not exist and insert rows if it does. Since it is supposed to be created at runtime and I have implemented it by creating a subclass of SQLiteOpenHelper and overriding the onCreate() method -
"Do I need to put anything in the /assets folder of my project?"
I am not using any Content Provider "Do I need to add any tags in the AndroidManifest.xml?"
Here is what I have done. The strings have been defined properly and I do not get any runtime exceptions.
Implementation of the SQLiteOpenHelper subclass.
public class MyDB extends SQLiteOpenHelper {
public MyDB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION );
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(USERAUTH_TABLE_CREATE);
db.execSQL(USERPREF_TABLE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
Log.w("Example", "Upgrading database, this will drop tables and
recreate.");
db.execSQL("DROP TABLE IF EXISTS " + USERAUTH_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + USERPREF_TABLE_NAME);
onCreate(db);
}
}
Here is where I create an instance of the MyDB subclass of the SQLiteOpenHelper.
MyDB tdb = new MyDB(Activity.this);
SQLiteDatabase db = tdb.getReadableDatabase();
Everything runs and when I go to the sqlite shell and write the following query
select * from table_name - it just tells me no such record exist. I set breakpoints and it seems after the getReadableDatabase() is called the #Override OnCreate() method is never executed which is where I execute the Create table SQLs. I have tried getWritableDatabase()
as well.
I dont understand why the tables are not being created. If anyone can help that would be awesome.
Thanks.
Query Text String#1
private static final String USERAUTH_TABLE_CREATE =
"CREATE TABLE " + USERAUTH_TABLE_NAME + " (" +
"number INTEGER NOT NULL," +
"dip TEXT NOT NULL," +
"email TEXT NOT NULL," +
"password TEXT NOT NULL," +
"flag INTEGER" + ");" ;
Query Text String #2
private static final String USERPREF_TABLE_CREATE =
"CREATE TABLE " + USERPREF_TABLE_NAME + " (" +
"tpd TEXT NOT NULL ," +
"cat TEXT NOT NULL" + ");";
If onCreate() is not being called, then the database has already been created for your app. The quickest way to solve it is to delete your project on the emulator (Settings --> Applications --> Your application), and then restart your application. Alternatively you could use ADB to just drop your database -- it's up to you. Restarting the app after dropping the database will call onCreate() because the database does not exist, and then your table creation sql will be run. onCreate() is only called if your database DOES NOT exist (so pretty much the first time you call the database in your code.
"Do I need to put anything in the /assets folder of my project?"
No
"Do I need to add any tags in the AndroidManifest.xml?"
No
Your syntax is ok ... could you paste the query you are making for creating tables ?
This might be a silly question, but have you defined the DATABASE_NAME and DATABASE_VERSION variables?
Issue resolved. Code was working all the way once again. sqlite shell was not showing me the tables and the database. When I kept my app running on the emulator and navigated to data > data > your-package-name > databases > your-database-file using DDMS the system shows me the SQLite DB was created fine. I have checked the tables are there as well.
Thank you all guys!!
This simple application will create a data base and 1 table w and at the end it will
retrieve the value which u have enetered and vl show in textBox.
SQLiteDatabase myDB= null;
String TableName="Profile";
String ShowData="";
/* This function create new database if not exists. */
try {
myDB = openOrCreateDatabase("DataBase.db",SQLiteDatabase.CREATE_IF_NECESSARY, null);
/* Create a Table in the Database. */
myDB.execSQL("CREATE TABLE IF NOT EXISTS "+ TableName + " (id INT(4),firstname VARCHAR,lastname VARCHAR);");
/* Insert data to a Table*/
//myDB.execSQL("INSERT INTO "+ TableName +"(id, firstname, lastname) "+ " VALUES (1, 'Pir', 'Fahim');");
Toast.makeText(this," DATA BASE HAVE BEEN CREATED ", Toast.LENGTH_SHORT).show();
/*Fetch data from database table */
Cursor c = myDB.rawQuery("SELECT* FROM " + TableName , null);
int id = c.getColumnIndex("id");
int fristName = c.getColumnIndex("firstname");
int lastName = c.getColumnIndex("lastname");
// Check result.
c.moveToFirst();
if (c != null) {
// Loop through all Results
do {
int personId = c.getInt(id);
String FirstName = c.getString(fristName);
String LastName = c.getString(lastName);
ShowData =ShowData +personId+" .) " +FirstName+" "+LastName+"\n";
txt.append("********************"+"\n"+personId+"\n"+FirstName+"\n"+LastName+"\n");
// Toast.makeText(this," RESULT 2 IS = "+ ShowData, Toast.LENGTH_LONG).show();
}
while(c.moveToNext());
}
// Toast.makeText(this," RESULT 2 IS = "+ ShowData, Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Toast.makeText(this, "Error = "+e.getMessage(), Toast.LENGTH_LONG).show();
}
finally
{
if (myDB != null)
myDB.close();
}