Search code examples
javaandroidandroid-sqlitesqliteopenhelper

Android APP crashes on getWritableDatabase() or getReadableDatabase()


I am php developer, trying to learn android and I am trying to set up a DB and insert some data.

I have followed some tutorials but my app gets stuck when I use getWritableDatabase() or getReadableDatabase().

Below is the code for my DBHelper I created.

package com.example.bootstart;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBHelper extends SQLiteOpenHelper {
    private static final String LOGTAG = "THEDBHELPER";

    private static final String DATABASE_NAME = "geolocation.db";
    private static final int DATABASE_VERSION = 1;

    private static final String TABLE_LOCATIONS = "locations";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_welawa = "welawa";
    private static final String COLUMN_lati = "latitude";
    private static final String COLUMN_longi = "longitude";

    private static final String TABLE_CREATE = "CREATE TABLE " + TABLE_LOCATIONS + " ("  
            + COLUMN_ID + "INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_welawa + " TEXT, " + COLUMN_lati 
            + " TEXT, " + COLUMN_longi + " TEXT)"; 


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

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(TABLE_CREATE);
        Log.i(LOGTAG, "TABLE HAS BEEN CREATED");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOCATIONS);
        onCreate(db);
    }

}

I access it through my MainActivity class.

package com.example.bootstart;

import android.os.Bundle;
import android.widget.Toast;
import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


public class MainActivity extends Activity {
    SQLiteOpenHelper dbhelper;
    SQLiteDatabase database;
    @Override 
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toast.makeText(getApplicationContext(), "Main Activity", Toast.LENGTH_LONG).show();

        dbhelper = new DBHelper(this);
            //Works upto here
        database = dbhelper.getReadableDatabase(); //App crashes on this line


    }
}

My emulator crashes on every launch so I am stuck on testing with my phone.

My min SDK is 8, if it is of anyhelp.

Any help is very much appreciated guys.


Solution

  • Simply add a space after 'id' in the

    private static final String COLUMN_ID = "id";
    

    I always print my db commands constructed in the code in the log to check as I always make mistakes with the space, brackets or commas. Saves a lot of heartache.