Problem creating database in SQLite on Android

Hi, I'm new to android, and I had a problem creating a database.

public class database extends ListActivity {
    /** Called when the activity is first created. */
    private final String MY_DATABASE_NAME = "myCoolUserDB.db";
    private final String MY_DATABASE_TABLE = "t_Users"; 
    Context c;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ArrayList<String> results = new ArrayList<String>();
        setContentView(R.layout.main);
        SQLiteDatabase mydb=null;
        try
        {
            mydb.openOrCreateDatabase(MY_DATABASE_NAME,  null);

        } catch(Exception e){}
    }
}

When I run this code, it throws a runtime exception. Please help me.

+1
source share
4 answers
  • If you intend to call a static method, such as openOrCreateDatabase, do it in the class (SQLiteDatabase.openOrCreateDatabase (...)), and not as an instance. This is much clearer - the way you did it, it looks like you are calling an instance method, so it looks like a valid NullPointerException, which, of course, is misleading.

  • As someone else said, stack tracing will be most useful when accessing an exception for help.

  • () , , . . , , . , , , , , , , .

  • SQLiteOpenHelper. . Android ( , , , ?!), , , , SDK, , , Notepad. NotePadProvider, , , Android. , .

+3

sqlite , SQLiteOpenHelper:

private class DBHelper extends SQLiteOpenHelper {   

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLES);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(UPGRADE_TABLES);
    }

}   

db DbHelper:

DBHelper dbHelper = new DBHelper(Activity.this);
SQLiteDatabase db = dbHelper.getReadableDatabase();
+1

. ,

  • dir " "
  • ".db" .

,

File dbFile = getDatabasePath ("abc.db");

if (dbFile.isDirectory ()) {
    dbFile.delete();
}
if (! dbFile.exists()) {
    String path = dbFile.getParent ();
    new File (path).mkdirs ();
}
database  = SQLiteDatabase.openDatabase (dbFile.getAbsolutePath (), this, SQLiteDatabase.OPEN_READWRITE | SQLiteDatabase.CREATE_IF_NECESSARY);

,

, SQLiteOpenHelper " ". , SQLiteDatabase .

+1

This is a simple post that talks about how to insert data into an SQLite database in Android , and in addition, these links show you how to get data from an SQLite database in Android .

0
source

Source: https://habr.com/ru/post/1779927/


All Articles