Kotlin: sqlite database table not creating - database

Iam new to Kotlin. I am developing a "personality guessing" app. it was working fine but when i added SQLite database when I run it keeps crashing when i reach to activity on which SQLite is integrated. my table does not create.
error log image here in link
Error log:
2020-06-04 13:18:10.757 16744-16744/? E/example.guessm: Unknown bits set in runtime_flags: 0x8000
2020-06-04 13:18:12.088 16744-16776/com.example.guessme E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
2020-06-04 13:18:12.088 16744-16776/com.example.guessme E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
2020-06-04 13:18:33.961 16744-16744/com.example.guessme E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.guessme, PID: 16744
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.guessme/com.example.guessme.QuizActivity}: java.lang.IllegalStateException: getDatabase called recursively
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.IllegalStateException: getDatabase called recursively
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:357)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:317)
at com.example.guessme.DbHelper.addQuestion(DbHelper.kt:80)
at com.example.guessme.DbHelper.addQuestions(DbHelper.kt:45)
at com.example.guessme.DbHelper.onCreate(DbHelper.kt:35)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:412)
at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:341)
at com.example.guessme.DbHelper.getAllQuestions(DbHelper.kt:93)
at com.example.guessme.QuizActivity.onCreate(QuizActivity.kt:29)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7356) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 
Code snippet of onCreate method in DbHelper class:
private val DATABASE_VERSION = 2
// Database Name
private val DATABASE_NAME = "PersonalityQuiz.db"
// tasks table name
lateinit var dbase: SQLiteDatabase
class DbHelper (context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
override fun onCreate(db: SQLiteDatabase) {
dbase = db
val sql = ("CREATE TABLE IF NOT EXISTS " + TABLE_QUEST + " ( "
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUES
+ " TEXT, " + KEY_OPTA + " TEXT, "
+ KEY_OPTB + " TEXT, " + KEY_OPTC + " TEXT)")
db.execSQL(sql)
addQuestions()
db.close()
}
code snippet of addQuestions function where i insert questions to database:
// Adding new question
fun addQuestion(quest: Question) {
dbase = this.writableDatabase
val values = ContentValues()
values.put(KEY_QUES, quest.getQUESTION())
values.put(KEY_OPTA, quest.getOPTA())
values.put(KEY_OPTB, quest.getOPTB())
values.put(KEY_OPTC, quest.getOPTC())
// Inserting Row
dbase.insert(TABLE_QUEST, null, values)
}
code snipppet for onUpgrade method:
override fun onUpgrade(db: SQLiteDatabase, oldV: Int, newV: Int) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS $TABLE_QUEST")
// Create tables again
onCreate(db)
}

You cannot access writableDatabase within onCreate().
Either remove the addQuestions() call from onCreate(), or pass the SQLiteDatabase from onCreate() as a parameter to addQuestions().

Related

Can't restore a flink job that uses Table API and Kafka connector with savepoint

I canceled a flink job with a savepoint, then tried to restore the job with the savepoint (just using the same jar file) but it said it cannot map savepoint state. I was just using the same jar file so I think the execution plan should be the same? Why would it have a new operator id if I didn't change the code? I wonder if it's possible to restore from savepoint for a job using Kafka connector & Table API.
Related errors:
used by: java.util.concurrent.CompletionException: java.lang.IllegalStateException: Failed to rollback to checkpoint/savepoint file:/root/flink-savepoints/savepoint-5f285c-c2749410db07. Cannot map checkpoint/savepoint state for operator dd5fc1f28f42d777f818e2e8ea18c331 to the new program, because the operator is not available in the new program. If you want to allow to skip this, you can set the --allowNonRestoredState option on the CLI.
used by: java.lang.IllegalStateException: Failed to rollback to checkpoint/savepoint file:/root/flink-savepoints/savepoint-5f285c-c2749410db07. Cannot map checkpoint/savepoint state for operator dd5fc1f28f42d777f818e2e8ea18c331 to the new program, because the operator is not available in the new program. If you want to allow to skip this, you can set the --allowNonRestoredState option on the CLI.
My Code:
public final class FlinkJob {
public static void main(String[] args) {
final String JOB_NAME = "FlinkJob";
final EnvironmentSettings settings = EnvironmentSettings.inStreamingMode();
final TableEnvironment tEnv = TableEnvironment.create(settings);
tEnv.getConfig().set("pipeline.name", JOB_NAME);
tEnv.getConfig().setLocalTimeZone(ZoneId.of("UTC"));
tEnv.executeSql("CREATE TEMPORARY TABLE ApiLog (" +
" `_timestamp` TIMESTAMP(3) METADATA FROM 'timestamp' VIRTUAL," +
" `_partition` INT METADATA FROM 'partition' VIRTUAL," +
" `_offset` BIGINT METADATA FROM 'offset' VIRTUAL," +
" `Data` STRING," +
" `Action` STRING," +
" `ProduceDateTime` TIMESTAMP_LTZ(6)," +
" `OffSet` INT" +
") WITH (" +
" 'connector' = 'kafka'," +
" 'topic' = 'api.log'," +
" 'properties.group.id' = 'flink'," +
" 'properties.bootstrap.servers' = '<mykafkahost...>'," +
" 'format' = 'json'," +
" 'json.timestamp-format.standard' = 'ISO-8601'" +
")");
tEnv.executeSql("CREATE TABLE print_table (" +
" `_timestamp` TIMESTAMP(3)," +
" `_partition` INT," +
" `_offset` BIGINT," +
" `Data` STRING," +
" `Action` STRING," +
" `ProduceDateTime` TIMESTAMP(6)," +
" `OffSet` INT" +
") WITH ('connector' = 'print')");
tEnv.executeSql("INSERT INTO print_table" +
" SELECT * FROM ApiLog");
}
}

Apache Flink version 1.13 Convert Table to Dataset?

I am converting some legacy Java code written for Flink version 1.5 to Flink version 1.13.1. Specifically, I'm working with Table API. I have to read data from CSV file, perform some basic SQL and then write results back to a file.
For Flink version 1.5, I used the following code to perform above actions
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);
TableSource tableSrc = CsvTableSource.builder()
.path("<CSV_PATH>")
.fieldDelimiter(",")
.field("date", Types.STRING)
.field("month", Types.STRING)
...
.build();
tableEnv.registerTableSource("CatalogTable", tableSrc);
String sql = "...";
Table result = tableEnv.sqlQuery(sql);
DataSet<Row1> resultSet = tableEnv.toDataSet(result, Row1.class);
resultSet.writeAsText("<OUT_PATH>");
env.execute("Flink Table-Sql Example");
In order to convert above code to Flink version 1.13.1, I wrote the following code
import org.apache.flink.table.api.Table;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.table.api.bridge.java.BatchTableEnvironment;
EnvironmentSettings settings = EnvironmentSettings
.newInstance()
.inBatchMode()
.build();
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
TableEnvironment tableEnv = TableEnvironment.create(settings);
final String tableDDL = "CREATE TEMPORARY TABLE CatalogTable (" +
"date STRING, " +
"month STRING, " +
"..." +
") WITH (" +
"'connector' = 'filesystem', " +
"'path' = 'file:///CSV_PATH', " +
"'format' = 'csv'" +
")";
tableEnv.executeSql(tableDDL);
String sql = "...";
Table result = tableEnv.sqlQuery(sql);
// DEPRECATED - BatchTableEnvironment required to convert Table to Dataset
BatchTableEnvironment bTableEnv = BatchTableEnvironment.create(env);
DataSet<Row1> resultSet = bTableEnv.toDataSet(result, Row1.class);
resultSet.writeAsText("<OUT_PATH>");
env.execute("Flink Table-Sql Example");
However, BatchTableEnvironment is marked as "Deprecated" in Flink version 1.13. Is there any alternative to convert Table to Dataset or to directly write a Table to a file?

SQLITE EMPTY CONTROL KOTLIN

Hello I'm trying to get data from database but whenever I try this without try and catch app crashs.
I tried if(cursor.moveToFirst()) structure but it didn't worked .
If I use cursor.moveToFirst() it's kinda work but this time database can't save objects.
This is my getdata function
fun getdata() {
val db = context?.openOrCreateDatabase("DRUGS", Context.MODE_PRIVATE, null)
val cursor = db?.rawQuery("SELECT * FROM drugs", null)
if (cursor != null) {
val drugnameIx = cursor.getColumnIndex("drugname")
val drugtimeIx = cursor.getColumnIndex("drugtime")
val drugpieceIx = cursor.getColumnIndex("drugpiece")
val drugidIx = cursor.getColumnIndex("id")
val maindrugpieceIx = cursor.getColumnIndex("maindrugpiece")
while (cursor.moveToNext()) {
ModelList.add(
DrugModel(
cursor.getInt(drugidIx),
cursor.getString(drugnameIx),
cursor.getString(drugtimeIx),
cursor.getIntOrNull(drugpieceIx)!!,
cursor.getIntOrNull(maindrugpieceIx)!!
)
)
}
cursor?.close()
}
}
This is my error
2021-04-07 04:21:52.017 16650-16650/com.tunahan.maindrugreminder E/SQLiteLog: (1) no such table:
drugs
2021-04-07 04:21:52.021 16650-16650/com.tunahan.maindrugreminder E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.tunahan.maindrugreminder, PID: 16650
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tunahan.maindrugreminder/com.tunahan.maindrugreminder.MainActivity}: android.database.sqlite.SQLiteException: no such table: drugs (code 1): , while compiling: SELECT * FROM drugs
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: android.database.sqlite.SQLiteException: no such table: drugs (code 1): , while compiling: SELECT * FROM drugs
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:890)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:501)
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:46)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1392)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1331)
at com.tunahan.maindrugreminder.MainFragment.getdata(MainFragment.kt:78)
at com.tunahan.maindrugreminder.MainFragment.onViewCreated(MainFragment.kt:59)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:332)
Your exception tells you the problem: no such table: drugs
While you have a database named drugs, from your code it doesn't seem like there is a table with that name in it.

Sqlite database insert returns always -1 on some devices

I try to insert an entry in sqlite db, but this does not work on some devices!
The insertion works with the device Huawei Nexus 6P (Android 6.0, API23) very well, but not with the device Samsung SM-G930F (Android 6.0.1, API23).
Can you please help me! The return code is always "res = -1".
Here is my code for inserting a new registration:
public boolean insertRegistration(Registration registration) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("phoneNumber", registration.getPhoneNumber());
cv.put("serverPassword", registration.getServerPassword());
cv.put("chatPassword", registration.getChatPassword());
cv.put("username", registration.getUsername());
cv.put("fileURL", registration.getFileURL());
long res = 0;
try
{
res = db.insert(TABLE_USER, null, cv);
}
catch(SQLException e)
{
// Sep 12, 2013 6:50:17 AM
Log.e("Exception", "SQLException" + String.valueOf(e.getMessage()));
e.printStackTrace();
}
if(res == -1)
throw new RuntimeException("New registration can not be inserted into local db");
db.close();
return res >= 0;
}
The debugger will also not come to the catch! No warning or errors will be returned!
And the db looks like this:
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE_USER);
}
Create user db string:
private static final String DATABASE_CREATE_USER = "create table "
+ TABLE_USER + "("
+ "id integer primary key autoincrement, "
+ "phoneNumber text not null, "
+ "serverPassword text not null, "
+ "chatPassword text not null, "
+ "fileURL text not null, "
+ "username text not null"
+ ");";
I always get the return code "-1", if I debug this line "res = db.insert(TABLE_USER, null, cv);" on the device "Samsung SM-G930F".
Thank you in Advance!

Exception: conversion from UNKNOWN to UNKNOWN is unsupported

I'm converting some jdbc code from MySql to SQL Server. When trying to
query = "Update ReportSetup "
+ "set N_ID=?, "
+ "R_Default=?, "
+ "R_Name=?, "
+ "R_Module=? "
+ " where R_ID = ?";
}
PreparedStatement stmt =
(PreparedStatement) con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
stmt.setInt(1, ri.getNodeID());
stmt.setInt(2, (ri.isDefault()) ? 1 : 0);
stmt.setString(3, ri.getName());
Object o = ri.getReportModule();
stmt.setObject(4, o);
The last statement stmt.setObject(4,o) throws the exception.
ri.getReportModule returns an instance of a class which implements Externalizable.
The method writeExternal() of that class is implemented as
public final void writeExternal(final ObjectOutput objectOutput) throws IOException {
for (int i=0; i<pdV.size(); i++) {
PropertyDescriptor pd = pdV.elementAt(i);
try {
Method m = pd.getReadMethod();
Object val = pd.getReadMethod().invoke(this);
System.out.print("writing property " + i + ": " + pd.getName() + " = " + val);
objectOutput.writeObject(val);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The database column in question is defined as
varbinary(max), not null
The code works well using MySql but I can't figure out what to do to make it run with Sql Server.
Any suggestions would be very much appreciated
The problem was that sql server is not happy to save a serialization (as done when implementing externalizable). .setObject() fails. The solution is to use setBinaryStream().
// Sql Server can't do an stmt.setObject(4,o) "Conversion from UNKNOWN to UNKNOWN not supported"
// Serialize the object to an output stream and then read it in again into the stmt.
Object o = ri.getReportModule();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream objectOutput = new ObjectOutputStream(bos);
objectOutput.writeObject(o);
objectOutput.flush();
InputStream objectInput = new ByteArrayInputStream(bos.toByteArray());
stmt.setBinaryStream(4, objectInput);
Cheers
Christian

Resources