Syntax error code 1 while compiling

By adding new items to the database I get this error: near ")": syntax error (code 1): , while compiling: CREATE TABLE Events(name TEXT,art TEXT,tag TEXT primarymonat TEXT primaryjahr TEXT primary)

By adding new items to the database I get this error:

near «)»: syntax error (code 1): , while compiling: CREATE TABLE Events(name TEXT,art TEXT,tag TEXT primarymonat TEXT primaryjahr TEXT primary)

What did I do wrong? Can’t find the mistake..

public class database extends SQLiteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "eventsManager";

// Contacts table name
private static final String TABLE_EVENTS = "Events";

// Contacts Table Columns names
private static final String KEY_NAME = "name";
private static final String KEY_ART = "art";
private static final String KEY_TAG = "tag";
private static final String KEY_MONAT = "monat";
private static final String KEY_JAHR = "jahr";

public database(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_EVENTS + "("
            + KEY_NAME + " TEXT," + KEY_ART + " TEXT,"
            + KEY_TAG + " TEXT primary" + KEY_MONAT + " TEXT primary" + KEY_JAHR + " TEXT primary"+ ")";
    db.execSQL(CREATE_CONTACTS_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_EVENTS);

    // Create tables again
    onCreate(db);
}

/**
 * All CRUD(Create, Read, Update, Delete) Operations
 */

// Adding new contact
void addContact(events contact) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName()); // Event Name
    values.put(KEY_ART, contact.getArt());
    values.put(KEY_TAG, contact.getTag());
    values.put(KEY_MONAT, contact.getMonat());
    values.put(KEY_JAHR, contact.getJahr());

    // Inserting Row
    db.insert(TABLE_EVENTS, null, values);
    db.close(); // Closing database connection
} }

Logcat:

    10-24 20:11:38.360    2107-2107/com.example.michael... D/AndroidRuntime﹕ Shutting down VM
10-24 20:11:38.360    2107-2107/com.example.michael... W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40ca3930)
10-24 20:11:38.370    2107-2107/com.example.michael... E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.michael.../com.example.michael...e.FullscreenActivity}: android.database.sqlite.SQLiteException: near ")": syntax error (code 1): , while compiling: CREATE TABLE Events(name TEXT,art TEXT,tag TEXT primarymonat TEXT primaryjahr TEXT primary)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
            at android.app.ActivityThread.access$600(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5041)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: android.database.sqlite.SQLiteException: near ")": syntax error (code 1): , while compiling: CREATE TABLE Events(name TEXT,art TEXT,tag TEXT primarymonat TEXT primaryjahr TEXT primary)
            at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
            at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
            at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
            at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
            at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
            at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
            at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1663)
            at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1594)
            at com.example.michael....database.onCreate(database.java:42)
            at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
            at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
            at com.example.michael....database.addContact(database.java:61)
            at com.example.michael....FullscreenActivity.onCreate(FullscreenActivity.java:149)
            at android.app.Activity.performCreate(Activity.java:5104)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
            at android.app.ActivityThread.access$600(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5041)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
            at dalvik.system.NativeStart.main(Native Method)

I am trying to create a table using sqlite in Android studio, but when I click the button that adds the data to the table I am getting this error.

07-22 14:19:01.836 23818-23818/com.example.user.restapp E/SQLiteLog: (1) no such table: rest_tables
07-22 14:19:01.851 23818-23818/com.example.user.restapp E/SQLiteDatabase: Error inserting Tablenumber=2 Taken=0
07-22 11:12:20.576 21924-21924/com.example.user.restapp E/SQLiteLog: (1) near "0": syntax error
07-22 11:12:20.596 21924-21924/com.example.user.restapp E/SQLiteDatabase: Error inserting 0=0 TABLENUMBER=1
    android.database.sqlite.SQLiteException: near "0": syntax error (code 1): , while compiling: INSERT INTO rest_tables(0,TABLENUMBER) VALUES (?,?)
        at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
        at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1093)
        at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:670)
        at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
        at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
        at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
        at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1590)
        at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1462)
        at com.example.user.restapp.DatabaseHelper.InsertData(DatabaseHelper.java:39)

Here is the DatabaseHelper class:

public static final String TABLE_NAME = "rest_tables";
    public static final String COL_1 = "ID";
    public static final String COL_2 = "TABLENUMBER";
    public static final String TAKEN = "0";

public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,TABLENUMBER TEXT,TAKEN TEXT)");
           // db.execSQL("CREATE TABLE " + TABLE_NAME + "()");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }

    public boolean InsertData(String tablenumber,String taken)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_2,tablenumber);
        contentValues.put(TAKEN,taken);
        long result = db.insert(TABLE_NAME,null,contentValues);
        if(result == -1)
            return false;
        else
            return true;
    }

And in the OnClickListener for the button in the MainActivity class I wrote:

boolean isInserted = myDB.InsertData("2","0");
                if(isInserted == true)
                    Toast.makeText(getApplicationContext(), "Table Added successfully", Toast.LENGTH_LONG).show();
                else
                    Toast.makeText(getApplicationContext(), "Table Not Added", Toast.LENGTH_LONG).show();

Can someone please tell me what exactly is causing this error ?

I want to convert json string into date and save into SQLite table. But getting exception of `Caused by: android.database.sqlite.SQLiteException: near «2016»: syntax error (code 1): , while compiling: update.My application is getting crashed after some time

Here is my Code

for (int j = 0; j < jarr_ActivityObjectList.length(); j++)
            {
                JSONObject jobjVessels = jarr_ActivityObjectList.getJSONObject(j);
                strActivitObj_ActiveStatus =  jobjVessels.getString("ActiveStatus");

                strImageCreatedDate = jobjVessels.getString("CreateDate");
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a", Locale.getDefault());
                Date date = new Date(strImageCreatedDate);
                String newImageCreatedDate = dateFormat.format(date);

                str_imgList_activityId = jobjVessels.getString("activityId");
                str_imgList_activityObjId = jobjVessels.getString("activityObjId");

                int activityObjId = 0;
                try
                {
                    activityObjId = Integer.parseInt(str_imgList_activityObjId);
                } catch(NumberFormatException nfe) {
                    System.out.println("Could not parse " + nfe);
                }

                str_imgList_objectId = jobjVessels.getString("objectId");
                str_imgList_userId = jobjVessels.getString("userId");
                String strImageDownLoadStatus = "0";
                String strUpLoadStatus = "1";

                str_imgList_imageaudioPath = jobjVessels.getString("imageaudioPath");

                if (strActivitObj_ActiveStatus.equals("1"))
                {
                    if (dbhelper.isActivityObject_ImageAudioPath(str_imgList_imageaudioPath))

                    {
                        //dbhelper.update_ActivityObjectList(strActivitObj_ActiveStatus, newImage_DateString , str_imgList_activityId, activityObjId, str_imgList_imageaudioPath, str_imgList_objectId, str_imgList_userId, strImageDownLoadStatus , strUpLoadStatus);
                       db = dbhelper.getWritableDatabase();
                       db.execSQL("update ActivityObjectList set ActiveStatus = '" + strActivitObj_ActiveStatus + " , CreatedDate='" + newImageCreatedDate + "' , activityId='" + str_imgList_activityId + "' , activityObjId= '" + activityObjId + "', objectId= '" + str_imgList_objectId + "', userId= '" + str_imgList_userId + "', DownLoad_Status='" + strImageDownLoadStatus + "', UpLoadStatus='" + strUpLoadStatus + "' where imageaudioPath = '" + str_imgList_imageaudioPath + "'");
                    }
                    else
                    {
                        dbhelper.insert_ActivityObjectList(strActivitObj_ActiveStatus, newImageCreatedDate , str_imgList_activityId, activityObjId, str_imgList_imageaudioPath, str_imgList_objectId, str_imgList_userId, strImageDownLoadStatus , strUpLoadStatus);
                    }
                }
                if (strActivitObj_ActiveStatus.equals("0"))
                {
                    if (dbhelper.isActivityObject_ImageAudioPath(str_imgList_imageaudioPath))
                    {
                        db = dbhelper.getWritableDatabase();
                        db.execSQL("DELETE FROM ActivityObjectList where imageaudioPath = '" + str_imgList_imageaudioPath + "'");
                        Log.e(""," Deleted SuccesFully !!! imageaudioPath " + str_imgList_imageaudioPath);
                    }
                }
            }

Here is my dbhelper code

 String strTable_ActivityObjectList = "CREATE TABLE IF NOT EXISTS " + Table_ActivityObjectList + " ("
                + COL_activityobjlistID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + COL_activeStatus + " TEXT, "
                + COL_CreatedDate + " TEXT, "
                + COL_activityId + " TEXT, "
                + COL_activityObjId + " INTEGER, "
                + COL_imageaudioPath + " TEXT, "
                + COL_objectId + " TEXT, "
                + COL_userId + " TEXT, "
                + COL_ActivityObject_DownLoadStatus  + " TEXT, "
                + COL_ActivityObject_UpLoadStatus + " TEXT" + ");";

 public boolean update_ActivityObjectList(String strActiveStatus,
                                             String CreatedDate ,
                                             String activityId,
                                             int stractivityObjId,
                                             String strimageaudioPath,
                                             String strobjectId,
                                             String struserId,
                                             String strDownLoadStatus ,
                                             String strUpLoadStatus)
    {
        SQLiteDatabase db = getReadableDatabase();
        ContentValues values = new ContentValues();

        values.put(COL_activeStatus, strActiveStatus);
        values.put(COL_CreatedDate , CreatedDate);
        values.put(COL_activityId, activityId);
        values.put(COL_activityObjId, stractivityObjId);
        values.put(COL_imageaudioPath, strimageaudioPath);
        values.put(COL_objectId, strobjectId);
        values.put(COL_userId, struserId);
        values.put(COL_ActivityObject_DownLoadStatus, strDownLoadStatus);
        values.put(COL_ActivityObject_UpLoadStatus ,strUpLoadStatus );

        int i = db.update(Table_ActivityObjectList, values, COL_imageaudioPath + "=" + strimageaudioPath, null);

        return i > 0;

    }

Even If call update_ActivityObjectList this above update method for updating data since getting crashed.Can someone help me how to resolve this issue


Add » space » at :

" 2016 "

in your method?

Есть главное активити в котором по нажатию на кнопку выполняется код:

package test.testdb;

import android.database.Cursor;
import android.database.SQLException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.io.IOException;

import test.testdb.Contract.Entry;
import test.testdb.DBHeler;

public class MainActivity extends AppCompatActivity {

    private TextView output;
    private EditText in;

    DBHeler db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        db = new DBHeler(this);
        try {
            db.createDataBase();
            db.openDataBase();
        } catch (IOException ex) {

        }

        output = (TextView) findViewById(R.id.output);
        output.setMovementMethod(new ScrollingMovementMethod());
        in = (EditText) findViewById(R.id.in);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        db.close();
    }

    public void search() {
            String string = in.getText().toString().trim();
            String query = "SELECT " + Entry.COLUMN_COL2 + " FROM " + Entry.TABLE_NAME
                    + " WHERE " + Entry.COLUMN_COL1 + " = " + """ + string + """;
            Cursor cursor = db.database.rawQuery(query, null);
            output.setText("");
        if (!string.equals("")) {
            try {
                if (cursor.getCount() != 0) {
                    while (cursor.moveToNext()) {
                        int col2ColumnIndex = cursor.getColumnIndex(Entry.COLUMN_COL2);
                        String col2 = cursor.getString(col2ColumnIndex);
                        output.append(col2 + "nn");
                    }
                }
            } catch (SQLException ex) {
            } finally {
                cursor.close();
            }
        }
    }

    public void onClickBtnSearch(View view) {
        search();
    }
}

БД используется готовая, с БД все в порядке. Вот код класса, который использует эту БД

package test.testdb;

import android.provider.BaseColumns;

//Класс контракт. Используется для указания имени таблицы и полей таблицы

public class Contract implements BaseColumns {
    private Contract() {
    };

    public static final class Entry implements BaseColumns {
        public final static String TABLE_NAME = "table";

        public final static String COLUMN_COL1 = "col1";
        public final static String COLUMN_COL2 = "col2";
    }
}

package test.testdb;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class DBHeler extends SQLiteOpenHelper {
    private static String DB_PATH = "/data/data/test.testdb/databases/";
    private static final String DATABASE_NAME = "datab.db";
    private static final int DATABASE_VERSION = 1;
    public SQLiteDatabase database;
    private Context myContext;

    public DBHeler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.myContext = context;
    }

    public void createDataBase() throws IOException{
        boolean dbExist = checkDataBase();

        if(dbExist){
        }else{
            this.getReadableDatabase();

            try {
                copyDataBase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }
    }

    private boolean checkDataBase(){
        SQLiteDatabase checkDB = null;
        try {
            String myPath = DB_PATH + DATABASE_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
        } catch(SQLiteException e){
        }
        if(checkDB != null){
            checkDB.close();
        }
        return checkDB != null ? true : false;
    }

    private void copyDataBase() throws IOException{
        InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
        String outFileName = DB_PATH + DATABASE_NAME;
        OutputStream myOutput = new FileOutputStream(outFileName);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }

        myOutput.flush();
        myOutput.close();
        myInput.close();
    }

    public void openDataBase() throws SQLException {
        String myPath = DB_PATH + DATABASE_NAME;
        database = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    }

    @Override
    public synchronized void close() {
        if(database != null)
            database.close();
        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}

Но при нажатии кнопки выдает ошибку

E/AndroidRuntime: FATAL EXCEPTION: main
Process: test.testdb, PID: 2411
java.lang.IllegalStateException: Could not execute method for android:onClick
  at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
  at android.view.View.performClick(View.java:5610)
  at android.view.View$PerformClick.run(View.java:22265)
  at android.os.Handler.handleCallback(Handler.java:751)
  at android.os.Handler.dispatchMessage(Handler.java:95)
  at android.os.Looper.loop(Looper.java:154)
  at android.app.ActivityThread.main(ActivityThread.java:6077)
  at java.lang.reflect.Method.invoke(Native Method)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.reflect.InvocationTargetException
  at java.lang.reflect.Method.invoke(Native Method)
  at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
  at android.view.View.performClick(View.java:5610) 
  at android.view.View$PerformClick.run(View.java:22265) 
  at android.os.Handler.handleCallback(Handler.java:751) 
  at android.os.Handler.dispatchMessage(Handler.java:95) 
  at android.os.Looper.loop(Looper.java:154) 
  at android.app.ActivityThread.main(ActivityThread.java:6077) 
  at java.lang.reflect.Method.invoke(Native Method) 
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
Caused by: android.database.sqlite.SQLiteException: near "table": syntax error (code 1): , while compiling: SELECT col2 FROM table WHERE col1 = "мама"
  at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
  at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
  at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
  at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
  at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
  at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
  at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
  at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1318)
  at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1257)
  at test.testdb.MainActivity.search(MainActivity.java:52)
  at test.testdb.MainActivity.onClickBtnSearch(MainActivity.java:71)
  at java.lang.reflect.Method.invoke(Native Method) 
  at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
  at android.view.View.performClick(View.java:5610) 
  at android.view.View$PerformClick.run(View.java:22265) 
  at android.os.Handler.handleCallback(Handler.java:751) 
  at android.os.Handler.dispatchMessage(Handler.java:95) 
  at android.os.Looper.loop(Looper.java:154) 
  at android.app.ActivityThread.main(ActivityThread.java:6077) 
  at java.lang.reflect.Method.invoke(Native Method) 
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 

Подскажите где что не так? Вроде все нормально в строчке где rawQuery

Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Niyamat Almass

I am making a simple note taking app.So I made a single database to store note title and note body.
But I app isn’t running and crash.

The error is

01-04 05:45:38.964 2451-2451/? I/art: Late-enabling -Xcheck:jni
01-04 05:45:39.480 2451-2451/com.example.niyamat.notepad W/System: ClassLoader referenced unknown path: /data/app/com.example.niyamat.notepad-1/lib/x86
01-04 05:45:39.662 2451-2451/com.example.niyamat.notepad E/SQLiteLog: (1) near «TABLEnote_table»: syntax error
01-04 05:45:39.662 2451-2451/com.example.niyamat.notepad D/AndroidRuntime: Shutting down VM
01-04 05:45:39.663 2451-2451/com.example.niyamat.notepad E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.niyamat.notepad, PID: 2451
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.niyamat.notepad/com.example.niyamat.notepad.MainActivity}: android.database.sqlite.SQLiteException: near «TABLEnote_table»: syntax error (code 1): , while compiling: CREATE TABLEnote_table(IDINTEGER PRIMARY KEY ,NOTE_TITLEVARCHAR,NOTE_BODYVARCHAR)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.database.sqlite.SQLiteException: near «TABLEnote_table»: syntax error (code 1): , while compiling: CREATE TABLEnote_table(IDINTEGER PRIMARY KEY ,NOTE_TITLEVARCHAR,NOTE_BODYVARCHAR)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
at com.example.niyamat.notepad.DataBaseHelper.onCreate(DataBaseHelper.java:32)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:187)
at com.example.niyamat.notepad.DataBaseHelper.getAllRecords(DataBaseHelper.java:66)
at com.example.niyamat.notepad.MainActivity.onCreate(MainActivity.java:33)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

The database code is

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_TABLE = "CREATE TABLE" + TABLE_NAME + "("
                + NOTE_ID + "INTEGER PRIMARY KEY ,"
                + NOTE_TITLE + "VARCHAR,"
                + NOTE_BODY + "VARCHAR" + ")";
        db.execSQL(CREATE_TABLE);
    }

I am new to android sqlite, so I can’t figure out what’s the problem is.Can someone help me?

I also update my project on github.Here is link https://github.com/niyamatalmass/Notepad

Harry James Steve Hunter

1 Answer

Steve Hunter January 4, 2016 12:32pm

One initial thought (as Android Studio takes ages loading the emulator) — don’t you need more spacing in your SQL?

You’ve got «CREATE TABLE» + TABLE_NAME which will all come out as one string with no string separation. That’s what’s causing this to fail initially.

Look at your error; the SQL statement being executed is:

CREATE TABLEnote_table(IDINTEGER PRIMARY KEY ,NOTE_TITLEVARCHAR,NOTE_BODYVARCHAR)

There’s no spacing so fix that first it may work with that sorted out.

Let me know how you get on.

Steve.

There’s a major activism in which the code is applied to the button:

package test.testdb;

import android.database.Cursor;
import android.database.SQLException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.io.IOException;

import test.testdb.Contract.Entry;
import test.testdb.DBHeler;

public class MainActivity extends AppCompatActivity {

private TextView output;
private EditText in;

DBHeler db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    db = new DBHeler(this);
    try {
        db.createDataBase();
        db.openDataBase();
    } catch (IOException ex) {

    }

    output = (TextView) findViewById(R.id.output);
    output.setMovementMethod(new ScrollingMovementMethod());
    in = (EditText) findViewById(R.id.in);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    db.close();
}

public void search() {
        String string = in.getText().toString().trim();
        String query = "SELECT " + Entry.COLUMN_COL2 + " FROM " + Entry.TABLE_NAME
                + " WHERE " + Entry.COLUMN_COL1 + " = " + """ + string + """;
        Cursor cursor = db.database.rawQuery(query, null);
        output.setText("");
    if (!string.equals("")) {
        try {
            if (cursor.getCount() != 0) {
                while (cursor.moveToNext()) {
                    int col2ColumnIndex = cursor.getColumnIndex(Entry.COLUMN_COL2);
                    String col2 = cursor.getString(col2ColumnIndex);
                    output.append(col2 + "nn");
                }
            }
        } catch (SQLException ex) {
        } finally {
            cursor.close();
        }
    }
}

public void onClickBtnSearch(View view) {
    search();
}

}

The OBD is used with ready, the OBD is fine. This is the class code that uses this OBD.

package test.testdb;

import android.provider.BaseColumns;

//Класс контракт. Используется для указания имени таблицы и полей таблицы

public class Contract implements BaseColumns {
private Contract() {
};

public static final class Entry implements BaseColumns {
    public final static String TABLE_NAME = "table";

    public final static String COLUMN_COL1 = "col1";
    public final static String COLUMN_COL2 = "col2";
}

}


package test.testdb;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class DBHeler extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/test.testdb/databases/";
private static final String DATABASE_NAME = "datab.db";
private static final int DATABASE_VERSION = 1;
public SQLiteDatabase database;
private Context myContext;

public DBHeler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    this.myContext = context;
}

public void createDataBase() throws IOException{
    boolean dbExist = checkDataBase();

    if(dbExist){
    }else{
        this.getReadableDatabase();

        try {
            copyDataBase();
        } catch (IOException e) {
            throw new Error("Error copying database");
        }
    }
}

private boolean checkDataBase(){
    SQLiteDatabase checkDB = null;
    try {
        String myPath = DB_PATH + DATABASE_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    } catch(SQLiteException e){
    }
    if(checkDB != null){
        checkDB.close();
    }
    return checkDB != null ? true : false;
}

private void copyDataBase() throws IOException{
    InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
    String outFileName = DB_PATH + DATABASE_NAME;
    OutputStream myOutput = new FileOutputStream(outFileName);
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))&gt;0){
        myOutput.write(buffer, 0, length);
    }

    myOutput.flush();
    myOutput.close();
    myInput.close();
}

public void openDataBase() throws SQLException {
    String myPath = DB_PATH + DATABASE_NAME;
    database = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}

@Override
public synchronized void close() {
    if(database != null)
        database.close();
    super.close();
}

@Override
public void onCreate(SQLiteDatabase db) {
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}

}

But when the button is pressed, it makes a mistake.

E/AndroidRuntime: FATAL EXCEPTION: main
Process: test.testdb, PID: 2411
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5610) 
at android.view.View$PerformClick.run(View.java:22265) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
Caused by: android.database.sqlite.SQLiteException: near "table": syntax error (code 1): , while compiling: SELECT col2 FROM table WHERE col1 = "мама"
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1318)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1257)
at test.testdb.MainActivity.search(MainActivity.java:52)
at test.testdb.MainActivity.onClickBtnSearch(MainActivity.java:71)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:5610) 
at android.view.View$PerformClick.run(View.java:22265) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 

What’s wrong? I think it’s okay in a line where rawQuery is.

Понравилась статья? Поделить с друзьями:
  • Syntax error cannot use import statement outside a module nodejs
  • Syntax error cannot use import statement outside a module jest
  • Syntax error cannot assign to literal
  • Syntax error cannot assign to function call
  • Syntax error cannot assign to conditional expression