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
Related
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
);
The onCreate void of my SQLiteOpenHelper is not called even when get a database with "database = helper.getWritableDatabase();". I read lots of posts on this page here but I didn't find any solution that worked for me.
SQLiteOpenHelper:
package eu.michael1011.currencies.sql;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class Helper extends SQLiteOpenHelper {
public static final String database_name = "currencies.db";
public static final String col1 = "id";
public static final String col2 = "value";
public Helper(Context context) {
super(context, database_name, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d("database", "started");
db.execSQL("create table EUR ("+col1+" TEXT, "+col2+" TEXT)");
Log.d("database", "finished");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("drop table if exists EUR");
onCreate(db);
}
}
I call it in my main activity like this:
helper = new Helper(getBaseContext());
database = helper.getWritableDatabase();
I'm a beginner with android studio, so I'm stumbling my way through building my first app. I've come up with and error when attempting to save my data to a database. Whenever I try to save any digits, the app crashes.
Database Java file:
package com.miahollins.basketballfinal;
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;
/**
* Created by pumpkin on 6/17/16.
*/
public class DataHandler {
public static final String GAMES = "games_played";
public static final String GAMES2 = "games_started";
public static final String GAMES3 = "points";
public static final String TABLE_NAME = "statstable";
public static final String DATA_BASE_NAME = "mydatabase.sqlite";
public static final int DATABASE_VERSION = 2;
public static final String TABLE_CREATE = "create table statstable (games_played VARCHAR not null, games_started VARCHAR not null, points VARCHAR not null)";
DatabaseHelper dbhelper;
Context ctx;
SQLiteDatabase db;
public DataHandler(Context ctx){
this.ctx = ctx;
dbhelper = new DatabaseHelper(ctx);
}
private static class DatabaseHelper extends SQLiteOpenHelper{
public DatabaseHelper(Context ctx){
super(ctx, DATA_BASE_NAME,null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(TABLE_CREATE);
} catch(SQLException e){
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS statstable");
onCreate(db);
}
}
public DataHandler open(){
db = dbhelper.getWritableDatabase();
return this;
}
public void close(){
dbhelper.close();
}
public long insertData(String games_played, String games_started, String points){
ContentValues content = new ContentValues();
content.put(GAMES, games_played);
content.put(GAMES2, games_started);
content.put(GAMES3, points);
return db.insertOrThrow(TABLE_NAME, null, content);
}
public Cursor returnData(){
return db.query(TABLE_NAME, new String[]{GAMES, GAMES2, GAMES3},null, null, null, null, null);
}
}
In my logcat I get an error saying that columns cannot be found. Any help is appreciated!
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");
}
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.