While compile : Creation table error - java

While compiling, this error shows:
android.database.sqlite.SQLiteException: near "TABLEnewtable": syntax error (code 1): , while compiling: CREATE TABLEnewtable{id INTEGER PRIMERY KEY, editname TEXT, edittel TEXT, editskype TEXT, editaddress TEXT }.
public class DataManipulator {
private static final String DATABASE_NAME = "mydatabase.db";
private static final int DATABASE_VERSION = 1;
static final String TABLE_NAME = "newtable";
private static Context context;
static SQLiteDatabase db;
private SQLiteStatement insertStmt;
private static final String INSERT = "insert into" +TABLE_NAME+ "(editname, edittel, editskype,
editaddress) values(?,?,?,?)";
public DataManipulator(Context context)
{
DataManipulator.context = context;
OpenHelper openHelper = new OpenHelper(DataManipulator.context);
DataManipulator.db = openHelper.getReadableDatabase();
this.insertStmt = DataManipulator.db.compileStatement(INSERT);
}
public long insert(String editname, String edittel, String editskype, String editaddress)
{
this.insertStmt.bindString(1, editname);
this.insertStmt.bindString(2, edittel);
this.insertStmt.bindString(3, editskype);
this.insertStmt.bindString(4, editaddress);
return this.insertStmt.executeInsert();
}
public void deleteAll()
{
db.delete(TABLE_NAME, null, null);
}
public List<String[]> selectAll()
{
List<String[]> list = new ArrayList<String[]>();
Cursor cursor = db.query(TABLE_NAME, new String[]{"id","editname", "edittel", "editskype",
"editaddress"},null, null, null, null, "name asc");
int x=0;
if(cursor.moveToFirst())
{
do {
String[] bb= new String[] {
cursor.getString(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4)};
list.add(bb);
x=x+1;
}
while(cursor.moveToNext());
}
if(cursor != null && !cursor.isClosed())
{
cursor.close();
}
cursor.close();
return list;
}
public void delete(int rowId)
{
db.delete(TABLE_NAME, null, null);
}
private static class OpenHelper extends SQLiteOpenHelper
{
OpenHelper(Context context)
{
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE" +TABLE_NAME+ "{id INTEGER PRIMERY KEY, editname TEXT, edittel TEXT, editskype TEXT, editaddress TEXT }");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS"+ TABLE_NAME);
onCreate(db);
}
}
}

You have a lot of basic SQL syntax problems. Please consider learning some basic SQL and stacktrace reading first.
Add whitespace between SQL keywords such as TABLE and identifiers such as newtable.
For example, change
"CREATE TABLE" +TABLE_NAME+
to
"CREATE TABLE " +TABLE_NAME+
and
"insert into" +TABLE_NAME+
to
"insert into " +TABLE_NAME+
The parentheses in CREATE TABLE should be ( ) and not { }
Typo in PRIMERY, should be PRIMARY.
Plus possibly a lots more; these are just the issues found with the first 10 seconds of looking at your SQL.

Check this :
db.execSQL("CREATE TABLE " +TABLE_NAME+ "(id INTEGER PRIMARY KEY, editname TEXT, edittel TEXT, editskype TEXT, editaddress TEXT )");

Related

SQLite Database Error - No column named task

Error_Database
enter code here
public class DataBaseHandler extends SQLiteOpenHelper {
private static final int VERSION = 1;
private static final String NAME = "toDoListDatabase";
private static final String TODO_TABLE = "todo";
private static final String ID = "id";
private static final String TASK = "task";
private static final String STATUS = "status";
private static final String CREATE_TODO_TABLE = "CREATE TABLE " + TODO_TABLE + "(" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + TASK + " TEXT, "
+ STATUS + " INTEGER)";
private SQLiteDatabase db;
public DataBaseHandler(Context context) {
super(context, NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TODO_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TODO_TABLE);
// Create tables again
onCreate(db);
}
public void openDatabase() {
db = this.getWritableDatabase();
}
public void insertTask(ToDoModel task){
ContentValues cv = new ContentValues();
cv.put(TASK, task.getTask());
cv.put(STATUS, 0);
db.insert(TODO_TABLE, null, cv);
}
public List<ToDoModel> getAllTasks(){
List<ToDoModel> taskList = new ArrayList<>();
Cursor cur = null;
db.beginTransaction();
try{
cur = db.query(TODO_TABLE, null, null, null, null, null, null, null);
if(cur != null){
if(cur.moveToFirst()){
do{
ToDoModel task = new ToDoModel();
task.setId(cur.getInt(cur.getColumnIndexOrThrow(ID)));
task.setTask(cur.getString(cur.getColumnIndexOrThrow(TASK)));
task.setStatus(cur.getInt(cur.getColumnIndexOrThrow(STATUS)));
taskList.add(task);
}
while(cur.moveToNext());
}
}
}
finally {
db.endTransaction();
assert cur != null;
cur.close();
}
return taskList;
}
public void updateStatus(int id, int status){
ContentValues cv = new ContentValues();
cv.put(STATUS, status);
db.update(TODO_TABLE, cv, ID + "= ?", new String[] {String.valueOf(id)});
}
public void updateTask(int id, String task) {
ContentValues cv = new ContentValues();
cv.put(TASK, task);
db.update(TODO_TABLE, cv, ID + "= ?", new String[] {String.valueOf(id)});
}
public void deleteTask(int id){
db.delete(TODO_TABLE, ID + "= ?", new String[] {String.valueOf(id)});
}
}
Can somebody proofread this? The error is :
"no column named task in "INSERT INTO todo(status,task) VALUES (?,?)"
"android.database.sqlite.SQLiteException: table todo has no column named task (code 1 SQLITE_ERROR): , while compiling: INSERT INTO todo(status,task) VALUES (?,?)".
I also attached a ss of the error as a link.
I'm trying to create a database where I can store tasks. Does anyone has a fix for this?
Thanks!
If you're on an emulator, try reinstalling the application! It works sometimes.

Why do I fail to save data in my application?

I am a student and started working on android studio recently. I don't know about it much. I am working on an application where I save the item name and its amount in the database and display toast message if data we entered is saved or not. problem is whenever I click on the save button my application crashes.
following is my DatabaseHelper class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Items.db";
public static final String TABLE_NAME = "item_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "ITEM";
public static final String COL_3 = "AMOUNT";
public DatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE" + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT," + "ITEM TEXT, AMOUNT TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP IF TABLE EXISTS" + TABLE_NAME);
onCreate(db);
}
public boolean addData(String item, String amount){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,item);
contentValues.put(COL_3,item);
long result = db.insert(TABLE_NAME,null, contentValues);
if(result == -1){
return false;
}else {
return true;
}
}
}
following is my MainActivity class:
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDb;
EditText editItem, editAmount;
Button buttonSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DatabaseHelper(this);
editItem = (EditText)findViewById(R.id.item_field);
editAmount = (EditText)findViewById(R.id.amount_field);
buttonSave = (Button)findViewById(R.id.button_save);
AddData();
}
public void AddData(){
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String item = editItem.getText().toString();
String amount = editAmount.getText().toString();
boolean insertData = myDb.addData(item, amount);
if(insertData == true){
Toast.makeText(MainActivity.this,"Amount is saved with Item detail", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(MainActivity.this, "Error occurred : Detailed are not saved", Toast.LENGTH_LONG).show();
}
}
});
}
}
I will appreciate your help.
Thank you
It might be crashing because it's not creating the table:
String createTable = "CREATE TABLE" + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT," + "ITEM TEXT, AMOUNT TEXT)";
A space is missing between table and its name:
String createTable = "CREATE TABLE " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, ITEM TEXT, AMOUNT TEXT)";
You should also close the database after you get the data in db.insert but this only creates a warning:
long result = db.insert(TABLE_NAME,null, contentValues);
db.close();

TextView not populating data from sqlite

I am trying to create a bill template by populating data stored in SQLite. I know there is a way to do this using ListView as well. The app crashes when I run this Activity.
public class Ticket_generator extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ticket_table);
Context context;
context=this;
TableHelper datahelper= new TableHelper(context);
datahelper.insertData("Home foods","Veg Resturant","New Municipal Blog","abc compound","mumbai 400007","01/07/17","COUNTER","BILL NO.-123","Perticulars","Quantity","Rate","gst","06.56AM");
Cursor cr;
cr=datahelper.getInformation();
TextView tv;
tv=(TextView)findViewById(R.id._s1t1);
tv.setGravity(Gravity.CENTER);
tv.setTextSize(16);
tv.setPadding(5, 5, 5, 5);
tv.setText(cr.getString(1));
}
}
This is the TableHelper.java
public class TableHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Ticketdb";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_TICKET = "tblticketdata";
public static final String CREATE_TABLE_TICKET = "CREATE TABLE IF NOT EXISTS " + TABLE_TICKET + "(_id INTEGER PRIMARY KEY AUTOINCREMENT, s1t1 TEXT NULL,s1t2 TEXT NULL,s1t3 TEXT NULL,s1t4 TEXT NULL,s1t5 TEXT NULL,s2t1 TEXT NULL,s2t2 TEXT NULL,s2t3 TEXT NULL, s3t1 TEXT NULL,s3t2 TEXT NULL,s3t3 TEXT NULL,ft1 TEXT NULL,ft2 TEXT NULL)";
public static final String DELETE_TABLE_SERVICES = "DROP TABLE IF EXISTS " + TABLE_TICKET;
public TableHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_TICKET);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DELETE_TABLE_SERVICES);
//Create tables again
onCreate(db);
}
public void insertData(String s1t1, String _s1t2, String _s1t3, String _s1t4, String _s1t5, String _s2t1, String _s2t2,
String _s2t3, String _s3t1, String _s3t2, String _s3t3, String _ft1, String _ft2) {
// Open the database for writing
SQLiteDatabase db = this.getWritableDatabase();
// Start the transaction.
db.beginTransaction();
ContentValues values;
try {
values = new ContentValues();
values.put("s1t1", s1t1);
values.put("s1t2", _s1t2);
values.put("s1t3", _s1t3);
values.put("s1t4", _s1t4);
values.put("s1t5", _s1t5);
values.put("s2t1", _s2t1);
values.put("s2t2", _s2t3);
values.put("s2t3", _s2t3);
values.put("s3t1", _s3t1);
values.put("s3t2", _s3t2);
values.put("s3t3", _s3t3);
values.put("ft1", _ft1);
values.put("ft2", _ft2);
// Insert Row
long i = db.insert(TABLE_TICKET, null, values);
Log.i("Insert", i + "");
// Insert into database successfully.
db.setTransactionSuccessful();
} catch (SQLiteException e) {
e.printStackTrace();
} finally {
db.endTransaction();
// End the transaction.
db.close();
// Close database
}
}
public Cursor getInformation() {
SQLiteDatabase sq = this.getReadableDatabase();
String[] columns = {"s1t1", "s1t2", "s1t3", "s1t4", "s1t5", "s2t1", "s2t2", "s2t3", "s3t1", "s3t2", "s3t3", "ft1", "ft2"};
Cursor cr = sq.query(TABLE_TICKET, columns, null, null, null, null, null);
return cr;
}
}
You need to move your cursor for the first position, like this example:
public String getFirstResult(){
String firstResult;
TableHelper datahelper = new TableHelper(context);
Cursor cursor = datahelper.getInformation();
cursor.moveToFirst();
firstResult = cursor.getString(0);
return firstResult;
}

get all table name list into array from sqlite database android

How to get all table was i created in SQlite database to string array?.please give me suggestion. Thanks in advance My database class as below
private static class DBHelper extends SQLiteOpenHelper {
/* public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}*/
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VIRSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+DB_TABLE+" ("+
KEY_ROWID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
KEY_NAME+" TEXT NOT NULL, "+
KEY_MOBILE+" NUMBER NOT NULL, "+
KEY_DATE+" TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+DB_TABLE);
}
}
public MyDatabase(Context c){
ourContext=c;
}
public MyDatabase open(){
ourHelper=new DBHelper(ourContext);
ourDatabase=ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
Try this code sample
ArrayList<String> arrTblNames = new ArrayList<String>();
SqlHelper sqlHelper = new SqlHelper(this, "TK.db", null, 1);
SQLiteDatabase DB = sqlHelper.getWritableDatabase();
Cursor c = DB.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
if (c.moveToFirst()) {
while ( !c.isAfterLast() ) {
arrTblNames.add( c.getString( c.getColumnIndex("name")) );
c.moveToNext();
}
}
I solve question like this code
public ArrayList<String> getAllTable() {
ArrayList<String> arrTblNames = new ArrayList<String>();
Cursor c = ourDatabase.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
c.moveToFirst();
while (!c.isAfterLast()) {
arrTblNames.add(c.getString(c.getColumnIndex("name")));
c.moveToNext();
}
// make sure to close the cursor
c.close();
return arrTblNames;
}

Android table not creating

I am trying to create a SQLite DB for my android app. I have all the code but I am getting an error in the logcat saying that the no such table. I think I have the correct code but would appreciate it if you could take a look and see if I am missing something.
package com.example.rory.dbtest;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
public static final String KEY_ROWID = "id";
public static final String KEY_ITEM = "item";
public static final String KEY_LITRES = "litres";
//public static final String KEY_COURSE = "course";
//public static final String KEY_NOTES = "notes";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "DripDrop";
private static final String DATABASE_TABLE = "table1";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE =
"create table if not exists assignments (id integer primary key autoincrement, "
+ "item VARCHAR not null, litres date );";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a record into the database---
public long insertRecord(String item, String litres)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_ITEM, item);
initialValues.put(KEY_LITRES, litres);
//initialValues.put(KEY_COURSE, course);
//initialValues.put(KEY_NOTES, notes);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular record---
public boolean deleteContact(long rowId)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
//---retrieves all the records---
public Cursor getAllRecords()
{
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_ITEM,
KEY_LITRES}, null, null, null, null, null);
}
//---retrieves a particular record---
public Cursor getRecord(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_ITEM, KEY_LITRES},
KEY_ROWID + "=" + rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
//---updates a record---
public boolean updateRecord(long rowId, String item, String litres)
{
ContentValues args = new ContentValues();
args.put(KEY_ITEM, item);
args.put(KEY_LITRES, litres);
//args.put(KEY_COURSE, course);
//args.put(KEY_NOTES, notes);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
And the logcat error after the app crashes is: (Sorry about the formatting I couldn't get it right at all).
package com.pinchtapzoom;
Caused by: android.database.sqlite.SQLiteException: no such table: table1 (code 1): , while compiling: SELECT id, item, litres FROM table1
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
It seems that you want to create table name as assignments and accessing data from table1.So change
private static final String DATABASE_TABLE = "table1";
to
private static final String DATABASE_TABLE = "assignments";
Take a look at your table's name :
private static final String DATABASE_TABLE = "table1";
And your query :
"create table if not exists assignments bla bla"
They are not same, thats why you get this error.
You will need to change one of them so the name will be same.

Categories

Resources