Cannot resolve symbol 'MODE_PRIVATE' - java

I am trying to open a database in Android Studio using the line:
SQLiteDatabase gardenDatabase = openOrCreateDatabase("myDatabase",MODE_PRIVATE,null);
but it gives me the error Cannot resolve symbol 'MODE_PRIVATE'. I don't understand what is wrong as have used the exact same line of code elsewhere in my project in different classes and it has worked fine before.
My full code:
public class MyWorker extends Worker {
public MyWorker (#NonNull Context context, #NonNull WorkerParameters params) {
super(context, params);
}
#Override
public Result doWork() {
SQLiteDatabase myDatabase = openOrCreateDatabase("myDatabase",MODE_PRIVATE,null);
//Do stuff
return Result.success();
}
}
Imports:
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import androidx.work.Result;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import static android.database.sqlite.SQLiteDatabase.openOrCreateDatabase;
I have been using this site to help write my database code: https://www.tutorialspoint.com/android/android_sqlite_database.htm

As you can see in the comments under your question, #BarryFruitman pointed out that:
SQLiteDatabase. openOrCreateDatabase() doesn't even take a "mode" as a
second param
and after that I commented:
this openOrCreateDatabase() is a method of the ContextWrapper class
and we are both right.
The problem is revealed now after you posted the link of the tutorial you follow.
Indeed in this tutorial, this method is proposed:
SQLiteDatabase myDatabase = openOrCreateDatabase("myDatabase",MODE_PRIVATE,null);
and this belongs to ContextWrapper class,
but in the same tutorial the mentioned signatures of openOrCreateDatabase() are:
openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)
and
openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)
which are both members of the SQLiteDatabase class.
I believe that this is the tutorial's mistake.
So change to this:
SQLiteDatabase gardenDatabase = SQLiteDatabase.openOrCreateDatabase(databaseNameWithPath, null);
which uses the method from SQLiteDatabase class.
EditOf course you have to provide for the variable databaseNameWithPath a fully qualified path and database name, like:
String databaseNameWithPath = "/data/data/" + <yourpackagename> + "/databases/" + "myDatabase";
and create the directory if it does not already exist.

You haven't imported that constant:
import static android.content.Context.MODE_PRIVATE;

Related

Room prepopulated database error: The columns returned by the query does not have the fields [rowid]

Please bear with me, I am very new to Android development. My goal is to load an app with a prepopulated database from the assets folder using Room.
The problem
After many hours and searches, including all the other questions with this same error, I unable to fix these errors within the Dao file:
This error is at methodA(): The columns returned by the query does not have the fields [rowid,integerB] in com.hfad.appname.ClassName even though they are annotated as non-null or primitive. Columns returned by the query: [textA,integerA]
This error is at methodB(): The columns returned by the query does not have the fields [rowid] in com.hfad.appname.ClassName even though they are annotated as non-null or primitive. Columns returned by the query: [textA,textB,integerA,integerB]
The sample program
I created a sample.db file by importing a .csv file (below) into DB Browser for SQLite.
rowid
textA
textB
integerA
integerB
Yes
No
0
0
The columns within DB Browser are their respective INTEGER and TEXT types.
(It doesn't matter if the rowid has no values as above or numbers placed within it, the errors remain.) I pasted sample.db into a newly created assets folder in Android Studio.
The Entity ClassName.java file:
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.Fts4;
import androidx.room.PrimaryKey;
#Fts4
#Entity(tableName = "sample")
public class ClassName {
#PrimaryKey(autoGenerate = true)
private int rowid;
private String textA;
private String textB;
private int integerA;
private int integerB;
public ClassName(String textA, String textB, int integerA, int integerB){
this.textA = textA;
this.textB = textB;
this.integerA = integerA;
this.integerB = integerB;
}
public int getRowid(){
return this.rowid;
}
public String getTextA(){
return this.textA;
}
public String getTextB(){
return this.textB;
}
public String getIntegerA(){
return this.integerA;
}
public String getIntegerB(){
return this.integerB;
}
public void setRowid(int rowid){
this.rowid=rowid;
}
}
The Dao ClassNameDao.java file:
import androidx.room.Dao;
import androidx.room.Query;
import java.util.List;
#Dao
public interface ClassNameDao {
#Query("SELECT `textA`, integerA FROM sample")
public List<ClassName> methodA();
#Query("SELECT * FROM sample WHERE integerA > :number")
public ClassName[] methodB(int number);
}
The Database ClassNameDatabase.java file:
import androidx.room.Database;
import androidx.room.RoomDatabase;
#Database(entities={ClassName.class}, version=1)
public abstract class ClassNameDatabase extends RoomDatabase {
public abstract ClassNameDao getClassNameDao();
}
Finally, the MainActivity:
import androidx.appcompat.app.AppCompatActivity;
import androidx.room.Room;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Room.databaseBuilder(getApplicationContext(), ClassNameDatabase.class, "sample.db")
.createFromAsset("sample.db")
.build();
}
}
Any help is much appreciated, thank you.
Your ClassName defines 5 columns, but the query methodA() is only selecting 2.
You can either select * in the query, or if you actually only need those 2 columns you should create a new class that only defines the 2 columns you want to use and get methodA() to return that instead of ClassName.
See https://developer.android.com/training/data-storage/room/accessing-data#return-subset

codename native Android application subclassing issues

My codenameone application crashes anything I use this native code
package com.mycompany.interfaces;
import android.app.Application;
import android.content.Context;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
public class InitialiseApp extends Application{
private static Context context;
public static Context getContext() {
return context;
}
#Override
public void onCreate()
{
super.onCreate();
context = getApplicationContext();
try
{
FirebaseApp.initializeApp(this, new FirebaseOptions.Builder().
setApiKey("XXXXXXXXXXXXXX").
setApplicationId("XXXXXXXX").
setGcmSenderId("XXXXXXXXXX")
.build());
FirebaseInstanceId.getInstance().deleteInstanceId();
FirebaseInstanceId.getInstance().getToken("XXXXXXXXXX",FirebaseMessaging.INSTANCE_ID_SCOPE);
FirebaseMessaging.getInstance().subscribeToTopic("test");
}
catch(Exception c)
{
c.printStackTrace();
}
}
}
I declare the class in the android.xapplication_attr android:name="com.mycompany.interfaces.InitialiseApp"
Need a assistance
Are you putting this in the native interface stub or in the CN1 part of the code?
Also, I don’t think that’s how you get a context in CN1. Look in the developer guide and video tutorials for Native Interfaces. I also recall a series of blog posts about native interfaces that dive into writing the Android code. You’ll need to use something from the AndroidNativeUtil class like: AndroidNativeUtil.getActivity().

AsyncLoader - wont accept 'this'

This is a follow up to a question I asked here.
I have copied and pasted this code from this tutorial. When I paste it into Android Studio, the 'this' parameter of of content.getLoadManager.initLoader() is highlighted in red and shows the following error:
Wrong 3rd Argument Type. Found 'com.example.carl.loaderDemo.FooLoaderClient', requried: 'android.app.LoaderManager.LoaderCallBacks
I've ran into this previously (see first link). I was hoping this tutorial would help but I just seem to be going in endless circles!
Can anyone point me in the right direction?!
package com.example.carl.loaderdemo;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
public class FooLoader extends AsyncTaskLoader {
public FooLoader(Context context, Bundle args) {
super(context);
// do some initializations here
}
public String loadInBackground() {
String result = "";
// ...
// do long running tasks here
// ...
return result;
}
}
class FooLoaderClient implements LoaderManager.LoaderCallbacks {
Activity context;
// to be used for support library:
// FragmentActivity context2;
public Loader onCreateLoader(int id, Bundle args) {
// init loader depending on id
return new FooLoader(context, args);
}
#Override
public void onLoadFinished(Loader loader, Object data) {
}
public void onLoaderReset(Loader loader) {
// ...
}
public void useLoader() {
Bundle args = new Bundle();
// ...
// fill in args
// ...
Loader loader =
context.getLoaderManager().initLoader(0, args, this);
// with support library:
// Loader loader =
// context2.getSupportLoaderManager().initLoader(0, args, this);
// call forceLoad() to start processing
loader.forceLoad();
}
}
Screenshot of error message:
There is a mismatch in your imports:
import android.support.v4.app.LoaderManager;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
But you need
import android.app.LoaderManager;
import android.content.AsyncTaskLoader;
import android.content.Loader;
You cannot mix the support library with the android framework. Alternatively you can subclass FragmentActivity and call getSupportLoaderManager() instead.
You're implementing android.support.v4.app.LoaderManager.LoaderCallbacks but the client is expecting android.app.LoaderManager.LoaderCallbacks. You need to be consistent in which loader API you're using.

The DBAdapter constructor is undefined

First Off: this is my first time ever looking at Java & the Android platform
I found a some sample code online that does some basic SQL database stuff using java and android.
I am receiving the "the constructor AssignmentTracker.DBAdapter(AssignmentTracker) is undefined" error.
(_ AssignmentTracker.java _) at this line:
public class AssignmentTracker extends Activity{
.....
DBAdapter db = new DBAdapter(this);
}
The DBAdapter.java looks like this:
public class DBAdapter{
....
private final Context context;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
I've seen very similar questions on this site, but none of them have helped me so far.
I found the issue.
I had another function/constructor named "DBAdapter" at the bottom of my AssignmentTracker.java file that was causing a conflict. I removed that and it all started working

Exporting SQLite Tables in XML

Situation: I am trying to export my SQLite Tables to a XML file and have followed this answer as well as a post deleted from here and also this question (apparently both last links from the same author :) )
Update-2: I already have another class named DBAdapter which extends the SQLiteOpenHelper. So I have this:
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);
}
/*...*/
onCreate()
/*...*/
onUpgrade()
/*...*/
}
already in my DBAdapter class file. How can I reuse this?
Also, I tried passing as:
DataXmlExporter dm = new DataXmlExporter(SQLiteDatabase
Database(getReadableDatabase ()));
But still got an error.
Update-1: I used the 2nd Link to implement my solution.
Problem: I am getting a Null Pointer Exception; I guess because I haven't initialized my object correctly. At the time of calling the DataXmlExporter / exportData method what is supplied as parameter? : DataXmlExporter dm = new DataXmlExporter(WHAT_IS_PASSED_HERE?);
Thanks..
looks like you need an SQLiteDatabase.
for example you can get one with getReadableDatabase() or with getWritableDatabase().
If you implemented DatabaseAssistant like in the first link you provided you have as constructor parameter a reference to a SQLiteDatabase....
You need to pass SQLiteDatabase Database ( getReadableDatabase () ):
As per constructor
public DataXmlExporter(final SQLiteDatabase db) {
this.db = db;
}
And as per comments:
Android DataExporter that allows the passed in SQLiteDatabase
to be exported to external storage (SD card) in an XML format
What I did was to extend the SQLiteOpenHelper inside the DatabaseAssistant class and used it.

Categories