Android SQLite data inserting - java

I am creating an android application that has two databases. One is offline SQLite database directly on the device and another one on public server that is used for update the offline one.
This is the way I'm inserting data into my SQLite database:
My activity:
package com.empekapp;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class Linie extends Activity {
DBAdapter db
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.linie);
openDB();
}
private void openDB(){
db = new DBAdapter(this);
db.open();
db.insertLineRecord("1");
db.insertLineRecord("2");
}
And in my database adapter:
public static final String KEY_LINE_ROWID = "_id";
public static final String KEY_LINE_NAME = "line_name";
public static final int COL_LINE_ROWID = 0;
public static final int COL_LINE_NAME = 1;
public static final String[] ALL_LINE_KEYS = new String[] {KEY_LINE_ROWID, KEY_LINE_NAME};
private static final String TABLE_LINE = "lines";
private static final String TABLE_LINE_CREATE =
"create table if not exists " + TABLE_LINE + "("
+ KEY_LINE_ROWID + " integer primary key autoincrement, "
+ KEY_LINE_NAME + " VARCHAR not null unique);";
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) {
db.execSQL(TABLE_LINE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LINE);
}
}
public DBAdapter open(){
db = DBHelper.getWritableDatabase();
return this;
}
public void close(){
DBHelper.close();
}
public void insertLineRecord(String line_name){
db.execSQL("INSERT OR IGNORE INTO " + TABLE_LINE + "('"
+ KEY_LINE_NAME + "') VALUES ('"
+ line_name + "');");
}
Generally this solution is enough for me.. but data is inserted to the table everytime I'm opening that activity to prevent this I set the unique constraint but how to insert data only once, when I'm creating that table to avoid situation like this?

use the data insertion in onCreate of database adapter class as this will be called only once when database created by this you can make it insert only once and no need to unique constaraint as well
Like this:
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_LINE_CREATE);
db.insertLineRecord("1");
db.insertLineRecord("2");
}

Related

Android Studio: SQLite database doesn't create

I am currently building a password manager app for myself. I plan to save the passwords in a SQLite database. For that I use this code:
package com.example.passwordmanager;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import androidx.annotation.Nullable;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String COLUMN_PASSWORD = "password";
public static final String PASSWORDS_TABLE = COLUMN_PASSWORD + "s_table";
public static final String COLUMN_ID = "id";
public static final String COLUMN_SERVICE = "service";
public static final String COLUMN_CREATION_DATE = "creation_date";
public static final String COLUMN_USED_NAME = "used_name";
public static final String COLUMN_USED_EMAIL = "used_email";
public DatabaseHelper(#Nullable Context context) {
super(context, "passwordManager.db", null,1);
Log.d("DatabaseHelper","Constructor reached");
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTableStatement = "CREATE TABLE "+ PASSWORDS_TABLE + " ( " + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_SERVICE + " VARCHAR(40), " + COLUMN_PASSWORD + " VARCHAR(40), " + COLUMN_CREATION_DATE + " VARCHAR(11), " + COLUMN_USED_NAME + " VARCHAR(40), " + COLUMN_USED_EMAIL + " VARCHAR(40), master VARCHAR(20), firstTime BOOLEAN)";
Log.d("DatabaseHelper","OnCreate1 reached");
db.execSQL(createTableStatement);
Log.d("DatabaseHelper","OnCreate2 reached");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+PASSWORDS_TABLE);
onCreate(db);
}
public boolean addToTable(Registration profile){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_PASSWORD,profile.hashedPassword);
cv.put(COLUMN_SERVICE,profile.service);
cv.put(COLUMN_CREATION_DATE,profile.creation_date);
cv.put(COLUMN_USED_NAME,profile.used_name);
cv.put(COLUMN_USED_EMAIL,profile.used_email);
long insert = db.insert(PASSWORDS_TABLE, null, cv);
if(insert==-1){
return true;
}else{
return false;
}
}
}
The problem with this code is, it just doesn't create the database or the folder of the database in data\data\com.example.passwordmanager. I tried outputting which methods it will reached when the constructor is called and I realized that it never reaches the onCreate method.
The DatabaseHelper class is only called once so for:
package com.example.passwordmanager;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.hardware.input.InputManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class CreatingNewEntryActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_creating_new_entry);
DatabaseHelper dh = new DatabaseHelper(CreatingNewEntryActivity.this);
}
Is this a problem with the code? Do I have to give permissions in the manifest.xml? Did I mess something up with the emulator? The App starts fine, it just doesn't create the database.
You need to call getWritableDatabase() or getReadableDatabase() on your database helper to make the framework create the database file and trigger onCreate(). Just calling the constructor is not enough.
See also: When is SQLiteOpenHelper onCreate() / onUpgrade() run?

Inserting or Reading values in an SQLite database doesn't yield any results

Started with SQLite in Android this evening. Practiced all the code from the Google documentation but it's still going wrong and I can't figure out where I'm going wrong. Take a look and see if you can find out any details.
DatabaseHelperContract.java
package com.practice.sqlitepractice;
import android.provider.BaseColumns;
//final class to prevent inheritance
public final class DatabaseHelperContract {
//Create Entry String
public static final String CREATE_ENTRY = "CREATE TABLE " + DatabaseSchema.TABLE_NAME + " (" +
DatabaseSchema._ID + " INTEGER PRIMARY KEY, " + DatabaseSchema.COLUMN_NAME + " TEXT)";
//private constructor to prevent accidental instantiation
private DatabaseHelperContract(){
}
/*Inner class that defines individual table contents*/
public static class DatabaseSchema implements BaseColumns{
public static final String TABLE_NAME = "details";
public static final String COLUMN_NAME = "name";
}
}
DatabaseHelper.class
package com.practice.sqlitepractice;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
class DatabaseHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "table.db";
public DatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(DatabaseHelperContract.CREATE_ENTRY);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
MainActivity.java
package com.practice.sqlitepractice;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText nameEditText;
private Button insertButton;
private Button readButton;
private ListView detailsListView;
private DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeWidgetsMethod();
}
#Override
protected void onDestroy() {
super.onDestroy();
databaseHelper.close();
}
private void insertionMethod(String name) {
//gets the data repository in write mode
SQLiteDatabase sqLiteDatabase = databaseHelper.getWritableDatabase();
//create a new map of values, where the columns are the keys
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelperContract.DatabaseSchema.COLUMN_NAME, name);
try {
long newRowID = sqLiteDatabase.insert(DatabaseHelperContract.DatabaseSchema.TABLE_NAME, null, contentValues);
Toast.makeText(this, "ID for newly created row: " + newRowID, Toast.LENGTH_SHORT).show();
} catch (SQLException exception) {
exception.printStackTrace();
}
}
private void readMethod() {
SQLiteDatabase sqLiteDatabase = databaseHelper.getReadableDatabase();
String[] projection = {DatabaseHelperContract.DatabaseSchema.COLUMN_NAME};
try {
Cursor cursor = sqLiteDatabase.query(
DatabaseHelperContract.DatabaseSchema.TABLE_NAME,
projection,
null,
null,
null,
null,
null);
List<String> itemIDs = new ArrayList<>();
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(DatabaseHelperContract.DatabaseSchema.COLUMN_NAME));
itemIDs.add(name);
}
cursor.close();
displayMethod(itemIDs);
} catch (SQLiteException exception) {
exception.printStackTrace();
}
}
private void displayMethod(List<String> list) {
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, R.id.details_list_view, list);
detailsListView.setAdapter(arrayAdapter);
}
#Override
public void onClick(View view) {
if (view == readButton) {
readMethod();
}
if (view == insertButton) {
String name = nameEditText.getText().toString();
insertionMethod(name);
}
}
private void initializeWidgetsMethod() {
nameEditText = findViewById(R.id.name_edit_text);
insertButton = findViewById(R.id.insert_button);
readButton = findViewById(R.id.read_button);
detailsListView = findViewById(R.id.details_list_view);
databaseHelper = new DatabaseHelper(getApplicationContext());
}
}
Note: I know that database transactions are expensive and should always be performed asynchronously. This code is just for practice and I will be performing all those at a later stage.
The problem with your code is the way that you initialize the ArrayAdapter in displayMethod().
The 3d argument of this definition:
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
R.id.details_list_view,
list
);
is R.id.details_list_view which is the ListView resource id, while you should have used a TextView resource id but only if you have created one to use inside the ListView.
Did you create such a TextView?
If not then you can use the default TextView, by not passing this argument.
So change the code to this:
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
list
);

how to use context in class which implements Screen?

i have a problem to use a database in libGdx, for use this first i create this class:
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(Context context, String name,CursorFactory factory, int version)
{
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase _db)
{
_db.execSQL(DataBaseClass.DATABASE_RECORD);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");
onCreate(_db);
}
}
and this class:
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
public class DataBaseClass {
static final String DATABASE_NAME = "my.database";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
static final String DATABASE_RECORD = "create table "+"RECORD"+
"( " + "SCORE text, GAMES_PLAYED text); ";
public SQLiteDatabase db;
private final Context context;
private DataBaseHelper dbHelper;
public DataBaseClass(Context _context) {
context = _context;
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public DataBaseClass open() throws SQLException {
db = dbHelper.getWritableDatabase();
return this;
}
public void close() {
db.close();
}
public SQLiteDatabase getDatabaseInstance() {
return db;
}
public void updateGamesPlayed(String game) {
ContentValues updatedValues = new ContentValues();
updatedValues.put("GAMES_PLAYED", game);
String where="GAMES_PLAYED = ?";
db.update("RECORD",updatedValues, where, new String[]{game});
}
public void updateBestScore(String score) {
ContentValues updatedValues = new ContentValues();
updatedValues.put("SCORE", score);
String where="SCORE = ?";
db.update("RECORD",updatedValues, where, new String[]{score});
}
}
but when i call the DataBaseClass in my principal class, which implement the interface Screen, i have problem here:
DBClass = new DataBaseClass(CONTEXT);
what is the context in this class? i try to use: "this", "getContext()", getActivity","this.getActivity", etc... but nothing works.
can someone help me?
Context here refers to your current class context you can simply pass this or principal.this

Cannot Find own symbol Class?

I have two files which both utilise a specific symbol class "Car". I have chosen this as a recurring pattern throughout the project.
My error:
DBhelper.java:
package com.example.brad.myapplication;
/**
* Created by Brad on 21/07/2014.
*/
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.graphics.Bitmap;
import android.view.View;
import android.view.TextureView;
public class DBhelper {
public static final String CAR_ID = "id";
public static final String CAR_PHOTO = "photo";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "CarDB.db";
private static final int DATABASE_VERSION = 1;
private static final String CARS_TABLE = "Cars";
private static final String CREATE_CARS_TABLE = "create table "
+ CARS_TABLE + " (" + CAR_ID
+ " integer primary key autoincrement, " + CAR_PHOTO
+ " blob not null);";
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_CARS_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + CARS_TABLE);
onCreate(db);
}
}
public void Reset() {
mDbHelper.onUpgrade(this.mDb, 1, 1);
}
public DBhelper(Context ctx) {
mCtx = ctx;
mDbHelper = new DatabaseHelper(mCtx);
}
public DBhelper open() throws SQLException {
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public void insertCarDetails(**Car** car) {
ContentValues cv = new ContentValues();
cv.put(CAR_PHOTO, Utility.getBytes(car.getBitmap()));
mDb.insert(CARS_TABLE, null, cv);
}
public **Car** retriveCarDetails() throws SQLException {
Cursor cur = mDb.query(true, CARS_TABLE, new String[] { CAR_PHOTO}, null, null, null, null, null, null);
if (cur.moveToFirst()) {
byte[] blob = cur.getBlob(cur.getColumnIndex(CAR_PHOTO));
cur.close();
return new Car(Utility.getPhoto(blob));
}
cur.close();
return null;
}
}
InsertandRetriveBlobData:
package com.example.brad.myapplication;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
/**
* Created by Brad on 20/07/2014.
*/
public class InsertandRetriveBlobData extends MyActivity {
private DBhelper DbHelper;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
DbHelper = new DBhelper(this);
**Car** car_One = new Car(BitmapFactory.decodeResource(
getResources(), R.drawable.photo), 1);
DbHelper.open();
DbHelper.insertCarDetails(car_One);
DbHelper.close();
car_One = null;
DbHelper.open();
car_One = DbHelper.retriveCarDetails();
DbHelper.close();
ImageView carphoto = (ImageView) findViewById(R.id.photo);
carphoto.setImageBitmap(car_One.getBitmap());
}
}
I have a feeling it is a slight bug as I am also having errors with any use of getBitmap() "Cannot resolve method getBitmap()" despite importing it's library.
Check whether your Car class is in myapplication directory along with the other two classes you mentioned here.
And then compile from myapplication directory.

SQLite database ..onCreate() is not being called

Kohli.java
package com.kohli;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.content.Context;
public class KohlifActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("KOHLIActivity", "qwert11111111");
setContentView(R.layout.main);
Log.i("KOHILActivity", "qwert22222222222");
DbHelper1 DbHelper=new DbHelper1(this) ;
Log.i("KOHLIfActivity", "qwert3333333333");
}
}
DbHelper1.java
package com.kohli;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;
public class DbHelper1 extends SQLiteOpenHelper
{
static final String TAG = "DbHelper1";
static final String DB_NAME = "timeline.db";
static final int DB_VERSION = 1;
static final String TABLE = "timeline";
static final String C_ID = BaseColumns._ID;
static final String C_CREATED_AT = "created_at";
static final String C_SOURCE = "source";
static final String C_TEXT = "txt";
static final String C_USER = "user";
Context context;
public DbHelper1(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
Log.d(TAG, "constructor111111");
//System.out.println("dbhelper constructor");
}
// Called only once, first time the DB is created
public void onCreate(SQLiteDatabase db) {
String sql = "create table " + TABLE + " (" + C_ID + " int primary key, "
+ C_CREATED_AT + " int, " + C_USER + " text, " + C_TEXT + " text)";
db.execSQL(sql);
Log.d(TAG, "onCreated sql:22222222 ");
//System.out.println("dbhelper oncreate");
}
// Called whenever newVersion != oldVersion
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Typically do ALTER TABLE statements, but...we're just in development,
// so:
db.execSQL("drop table if exists " + TABLE); // drops the old database
Log.d(TAG, "onUpdated 33333333");
//System.out.println("dbhelper onupgrade");
onCreate(db); // run onCreate to get new database
}
}
i wrote the following code to make a database with a table... the output at logcat is :: qwert111111 qwert22222 constructor111111 qwert3333 .. that is the oncreate function is not being called so the database is also not created...
The database isn't actually created until you call getWritableDatabase() on the
dbHelper object.

Categories

Resources