FileNotFoundException open failed: ENOENT (No such file or directory) - java

I have a file called "and.doc" that has big number of records each one has this shape
expression : defenition ;
So I'm trying to
Read the file with scanner
use ; as a delimiter
find a way to split expression from definition
and somehow add them to my Sqlite Database (if someone have any idea how to do that it will be great).
I'm using this code
try {
mf =new File("/home/agh/AndroidStudioProjects/Dicod/app/src/main/res/raw/and.doc");
inputFile = new Scanner(mf);
inputFile.useDelimiter(";");
while (inputFile.hasNext())
{
String x = inputFile.next();
Toast.makeText(getApplicationContext(),x,Toast.LENGTH_LONG).show();
//Splitting and adding to the databse
}
}
catch(FileNotFoundException e) {
e.printStackTrace();
}`
But I keep getting this error
06-23 04:38:28.771 23620-23620/? W/System.err: java.io.FileNotFoundException: /home/agh/AndroidStudioProjects/Dicod/app/src/main/res/raw/and.txt: open failed: ENOENT (No such file or directory)
06-23 04:38:28.771 23620-23620/? W/System.err: at libcore.io.IoBridge.open(IoBridge.java:465)
06-23 04:38:28.771 23620-23620/? W/System.err: at java.io.FileInputStream.<init>(FileInputStream.java:76)
06-23 04:38:28.771 23620-23620/? W/System.err: at java.util.Scanner.<init>(Scanner.java:158)
06-23 04:38:28.772 23620-23620/? W/System.err: at java.util.Scanner.<init>(Scanner.java:138)
06-23 04:38:28.772 23620-23620/? W/System.err: at com.example.agh.dicod.MainActivity.onCreate(MainActivity.java:28)
06-23 04:38:28.772 23620-23620/? W/System.err: at android.app.Activity.performCreate(Activity.java:5990)
06-23 04:38:28.772 23620-23620/? W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
06-23 04:38:28.772 23620-23620/? W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2332)
06-23 04:38:28.772 23620-23620/? W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
06-23 04:38:28.772 23620-23620/? W/System.err: at android.app.ActivityThread.access$800(ActivityThread.java:156)
06-23 04:38:28.772 23620-23620/? W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
06-23 04:38:28.772 23620-23620/? W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
06-23 04:38:28.772 23620-23620/? W/System.err: at android.os.Looper.loop(Looper.java:211)
06-23 04:38:28.772 23620-23620/? W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5389)
06-23 04:38:28.772 23620-23620/? W/System.err: at java.lang.reflect.Method.invoke(Native Method)
06-23 04:38:28.772 23620-23620/? W/System.err: at java.lang.reflect.Method.invoke(Method.java:372)
06-23 04:38:28.772 23620-23620/? W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
06-23 04:38:28.772 23620-23620/? W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
06-23 04:38:28.772 23620-23620/? W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
06-23 04:38:28.773 23620-23620/? W/System.err: at libcore.io.Posix.open(Native Method)
06-23 04:38:28.773 23620-23620/? W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
06-23 04:38:28.773 23620-23620/? W/System.err: at libcore.io.IoBridge.open(IoBridge.java:451)
06-23 04:38:28.773 23620-23620/? W/System.err: ... 17 more

Maybe the file doesn't exist in the selected directory or the READ_EXTERNAL_STORAGE permission is not granted.
Notice that if you target API 23, you have to request for permission on runtime, not only in the Manifest.
http://developer.android.com/training/permissions/requesting.html

The File doesn't exist. Create file using File() class and write the stream to it. Then read the data from it. Try adding the permission to the Manifest.xml and give a try.
<manifest ...>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
/>
...
</manifest>

I think the directory that you are passing
"/home/agh/AndroidStudioProjects/Dicod/app/src/main/res/raw/and.doc"
is present on your computer but the File is expecting the directory from your android device or android emulator that is the reason it is throwing an exception
if your "and.doc" is present in shared external storage of your android device "/storage/emulated/0/Documents/" then I think File will be able to access it given that you extract the directory correctly
here is how you can get the directory of your documents folder present in your sd card as an example
File externalStorageDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS); //getting external storage directory
//it's another method to get the directory of a file inside the external storage of a device
File folder = new File(externalStorageDirectory + "/Password");
instead of "/Password" replace it with your folder name

#Abdul2511 i'm not sure i understand the write stream part
I think What he meant was this although the code below will read the text file contents present in the directory
File myfile that is passed as a Parameter should be the extracted directory
// getdata() is the method which reads the data
// the data that is saved in byte format in the file
private String getdata(File myfile) {
FileInputStream fileInputStream = null;
try {
Log.i("file_read_send_to_getData_function",myfile.toString());
fileInputStream = new FileInputStream(myfile);
int i = -1;
StringBuffer buffer = new StringBuffer();
while ((i = fileInputStream.read()) != -1) {
buffer.append((char) i);
}
return buffer.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}

#Abdul2511 and somehow add them to my Sqlite Database
Here's a sample code that you can use as a reference on how to save and retrieve data from SQLite database on Android devices.
Root class of our SQLite database is SQLiteOpenHelper.
extends SQLiteOpenHelper will import that root class of SQLite database into our database class
// root class of our SQLite database is SQLiteOpenHelper
// extends SQLiteOpenHelper will import that root class of SQLite database into our NoteDatabase class
public class NoteDatabase extends SQLiteOpenHelper {
private static final int DATABASEVERSION= 2;
private static final String DATABASE_NAME = "your database name";
private static final String DATABASE_TABLE = "your table name";
//column names for database
private static final String KEY_ID="id";
private static final String KEY_TITLE="expression";
private static final String KEY_CONTENT="defenition";
private static final String KEY_DATE="date";
private static final String KEY_TIME="time";
public static List<Note> allNotes;
//creating a constructor for our noteDatabase
NoteDatabase(Context context){
super(context,DATABASE_NAME,null,DATABASEVERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
//onCreate is called every time the noteDatabase instance is created inside any class of this application
//creating the database table
String query = "CREATE TABLE " + DATABASE_TABLE +" ("+ KEY_ID +" INTEGER PRIMARY KEY AUTOINCREMENT , "+
KEY_TITLE+" TEXT, "+
KEY_CONTENT+" TEXT, "+
KEY_DATE+" TEXT, "+
KEY_TIME+" TEXT "+")";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//checking for updates for our database
if(oldVersion>=newVersion){
return;
}
else{
//update the table if new version is available
db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE);
onCreate(db);
}
}
//it will take Note as a parameter this note will contain all the information like title, content , date and time
//and it will send that note from addnote activity to this node database
//Note note is the class that we just created
public long addnote(Note note){
//here we will insert the data
SQLiteDatabase db = this.getWritableDatabase();
//this contentValues will create a dictionary like structure
ContentValues contentValues = new ContentValues();
//now we can save our value to the keys that we have created in this class
// contentValues.put(KEY_ID,note.getID()); ***Do not insert Id inside SQLite instead auto increment the id to be unique
contentValues.put(KEY_TITLE,note.getTitle());
contentValues.put(KEY_CONTENT,note.getContent());
contentValues.put(KEY_TIME,note.getTime());
contentValues.put(KEY_DATE,note.getDate());
//now we will insert the data
//if the data is inserted successfully it will return the long value of the primary key
long ID = db.insert(DATABASE_TABLE,null,contentValues);
db.close();
Log.i("ID", Long.toString(ID));
return ID;
}
//this will get all the notes present in the database
//so that we can desplay it in our ListView
public List<Note> getNotes(){
//we will pull the data from the database using element's unique id
//select * from databse where id = whatever the id we have passed on here
//* means acessing all the data in that particular id elements
//creating an instance of our database
SQLiteDatabase db = this.getReadableDatabase();
//creating a list of generic type called Note
allNotes = new ArrayList<>();
String query = "SELECT * FROM "+DATABASE_TABLE;
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst()){
//i am going to pull all the data from the database and pass that data onto our listView
do{
//now creating a new note and save the data from the database by using cursor
Note note = new Note();
note.setID(cursor.getLong(0));
note.setTitle(cursor.getString(1));
note.setContent(cursor.getString(2));
note.setDate(cursor.getString(3));
note.setTime(cursor.getString(4));
//adding this to lisView
allNotes.add(note);
}while(cursor.moveToNext());
}
return allNotes;
}
//updating the database
//replacing the old data with the updated data set inside the database
public int editNote(Note note){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_TITLE,note.getTitle());
contentValues.put(KEY_CONTENT,note.getContent());
contentValues.put(KEY_DATE,note.getDate());
contentValues.put(KEY_TIME,note.getTime());
return db.update(DATABASE_TABLE, contentValues,KEY_ID+"=?",new String[]{String.valueOf(note.getID())});
}
//the method will handel the deletion of the notes
//this method will be called from the noteDetails.class
void deleteNote(long id){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(DATABASE_TABLE,KEY_ID+"=?",new String[]{String.valueOf(id)});
db.close();
}
}
Note:-
You will have to modify the code according to your needs this only deals with writing the data onto the database and reading from the database
create a separate getter and setter java file in order to act as an adapter between your activity and the database
this is just a sample code from my own project
I am assuming that you have already separated expression into a separate string variable from definition

Related

Error connecting Android Studio app to remote MySQL: java.sql.SQLNonTransientConnectionException: Could not create connection to database server

I'm trying to connect an Android Studio app to a remote MYSQL database but an error is displaying that couldn't create a connection to the database.
Some troubleshooting I did:
Reviewed if the database is running (it is)
Connected from MySQL workbench in my computer to the remote database (I was able to connect and retrieve data)
Also I was developing another app (no Android Studio). I used the same connection classes and I was able to access the data.
--- With this, I think that is not a server issue. ---
Used different JDBC drivers (Gradle implementation below of the versions I used)
implementation group: 'mysql', name: 'mysql-connector-java', version: '8.0.22'
implementation group: 'mysql', name: 'mysql-connector-java', version: '8.0.23'
implementation group: 'mysql', name: 'mysql-connector-java', version: '8.0.13'
I also tried to add the .jar file in the project files but had other errors that didn't recognized the driver.
--- With this, I noticed that implementing the driver in Gradle is not an error as apparently it is recognizing the driver ---
Note: I'm currently using the gradle implementation.
I added the internet permissions to the AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
I tried to implement the code that retrieves the data from the data base using an ASYNCTASK but received the following errors
Main class WITH ASYNCTASK (MainActivity.java)*
Note: The code in this class was just to test if I was able to get the data from the database. Is not regarding to any functionality I was trying to implement in the app itself.
public class MainActivity extends AppCompatActivity {
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Data");
new GetCultivos().execute();
builder.setPositiveButton("Accept", null);
AlertDialog dialog = builder.create();
dialog.show();
}
});
class GetCultivos extends AsyncTask<Void, Void, Void>{
String list = "Data = ";
#Override
protected Void doInBackground(Void... voids) {
CultivoDao cultivoDao = new CultivoDao();
List<Cultivo> listaCultivos = cultivoDao.obtenerCultivos();
for (Cultivo i : listaCultivos){
list = i.getIdCultivo() + " " + i.getNombre() + ", ";
}
return null;
}
#Override
protected void onPostExecute(Void eVoid){
builder.setMessage(list);
}
}
}
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.appmov, PID: 5699
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$4.done(AsyncTask.java:399)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Ljava/sql/SQLType;
at com.mysql.cj.jdbc.DatabaseMetaData.getInstance(DatabaseMetaData.java:729)
at com.mysql.cj.jdbc.ConnectionImpl.getMetaData(ConnectionImpl.java:1180)
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:446)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:207)
at java.sql.DriverManager.getConnection(DriverManager.java:580)
at java.sql.DriverManager.getConnection(DriverManager.java:218)
at com.DAO.appmov.CultivoDao.StartConnection(CultivoDao.java:30)
at com.DAO.appmov.CultivoDao.obtenerCultivos(CultivoDao.java:49)
at com.example.appmov.MainActivity$GetCultivos.doInBackground(MainActivity.java:228)
at com.example.appmov.MainActivity$GetCultivos.doInBackground(MainActivity.java:220)
at android.os.AsyncTask$3.call(AsyncTask.java:378)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
at java.lang.Thread.run(Thread.java:919) 
Caused by: java.lang.ClassNotFoundException: Didn't find class "java.sql.SQLType" on path: DexPathList[[zip file "/data/app/com.example.appmov-U33MrmDYU8kMl3MFpFCdcA==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.appmov-U33MrmDYU8kMl3MFpFCdcA==/lib/arm64, /system/lib64]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:196)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at com.mysql.cj.jdbc.DatabaseMetaData.getInstance(DatabaseMetaData.java:729) 
at com.mysql.cj.jdbc.ConnectionImpl.getMetaData(ConnectionImpl.java:1180) 
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:446) 
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240) 
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:207) 
at java.sql.DriverManager.getConnection(DriverManager.java:580) 
at java.sql.DriverManager.getConnection(DriverManager.java:218) 
at com.DAO.appmov.CultivoDao.StartConnection(CultivoDao.java:30) 
at com.DAO.appmov.CultivoDao.obtenerCultivos(CultivoDao.java:49) 
at com.example.appmov.MainActivity$GetCultivos.doInBackground(MainActivity.java:228) 
at com.example.appmov.MainActivity$GetCultivos.doInBackground(MainActivity.java:220) 
at android.os.AsyncTask$3.call(AsyncTask.java:378) 
at java.util.concurrent.FutureTask.run(FutureTask.java:266) 
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
at java.lang.Thread.run(Thread.java:919) 
I/Process: Sending signal. PID: 5699 SIG: 9
So I tried to implement the code without an ASYNCTASK, but I'm receiving the error that you can see below in the error log.
Class I use to connect to the database (CultivoDao.java)
public class CultivoDao {
private Connection connection;
private Statement statement;
//Method to start the connection
private void StartConnection() {
String url = "jdbc:mysql://remotemysql.com:3306/hUfMa4wLpe";
String usuario = ***HERE IS THE USERNAME***;
String password = ***HERE IS THE PASSWORD***;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(url, usuario, password);
statement = connection.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
}
//Method to close the connection
private void CloseConnection(){
try {
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//Methog to get the data
public List<Cultivo> obtenerCultivos(){
List<Cultivo> listaCultivos = new ArrayList<>();
try {
StartConnection();
ResultSet rs = statement.executeQuery("Select * from cultivo");
while(rs.next()){
Cultivo cultivo = new Cultivo(rs.getInt("idCultivo"), rs.getString("nombre"));
listaCultivos.add(cultivo);
}
}catch (Exception e){
e.printStackTrace();
}
CloseConnection();
return listaCultivos;
}
}
Main class WITHOUT ASYNCTASK (MainActivity.java)*
Note: The code in this class was just to test if I was able to get the data from the database. Is not regarding to any functionality I was trying to implement in the app itself.
public class MainActivity extends AppCompatActivity {
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
builder = new AlertDialog.Builder(MainActivity.this);
String list = "Database list = ";
CultivoDao cultivoDao = new CultivoDao();
List<Cultivo> listaCultivos = cultivoDao.obtenerCultivos();
for (Cultivo i : listaCultivos){
list = i.getIdCultivo() + " " + i.getNombre() + ", ";
}
builder.setTitle("Data");
builder.setMessage(list);
builder.setPositiveButton("Accept", null);
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
}
The actual version I'm using is the one without the ASYNCTASK
I'm testing this app in a physical device. I don't know that this can affect in some way.
Error log:
W/System.err: java.sql.SQLNonTransientConnectionException: Could not create connection to database server.
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:110)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
W/System.err: at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:1008)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:825)
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:455)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:207)
at java.sql.DriverManager.getConnection(DriverManager.java:580)
at java.sql.DriverManager.getConnection(DriverManager.java:218)
at com.DAO.appmov.CultivoDao.StartConnection(CultivoDao.java:30)
at com.DAO.appmov.CultivoDao.obtenerCultivos(CultivoDao.java:49)
at com.example.appmov.MainActivity$1.onClick(MainActivity.java:88)
at android.view.View.performClick(View.java:7870)
at android.widget.TextView.performClick(TextView.java:14970)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:967)
at android.view.View.performClickInternal(View.java:7839)
at android.view.View.access$3600(View.java:886)
at android.view.View$PerformClick.run(View.java:29363)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7814)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)
W/System.err: Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1565)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:115)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103)
at java.net.InetAddress.getAllByName(InetAddress.java:1152)
at com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:132)
at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:65)
at com.mysql.cj.NativeSession.connect(NativeSession.java:152)
at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:955)
... 22 more
java.lang.NullPointerException: Attempt to invoke interface method 'java.sql.ResultSet java.sql.Statement.executeQuery(java.lang.String)' on a null object reference
at com.DAO.appmov.CultivoDao.obtenerCultivos(CultivoDao.java:50)
at com.example.appmov.MainActivity$1.onClick(MainActivity.java:88)
at android.view.View.performClick(View.java:7870)
at android.widget.TextView.performClick(TextView.java:14970)
W/System.err: at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:967)
at android.view.View.performClickInternal(View.java:7839)
at android.view.View.access$3600(View.java:886)
at android.view.View$PerformClick.run(View.java:29363)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7814)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)
java.lang.NullPointerException: Attempt to invoke interface method 'void java.sql.Connection.close()' on a null object reference
at com.DAO.appmov.CultivoDao.CloseConnection(CultivoDao.java:40)
at com.DAO.appmov.CultivoDao.obtenerCultivos(CultivoDao.java:58)
at com.example.appmov.MainActivity$1.onClick(MainActivity.java:88)
at android.view.View.performClick(View.java:7870)
at android.widget.TextView.performClick(TextView.java:14970)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:967)
at android.view.View.performClickInternal(View.java:7839)
at android.view.View.access$3600(View.java:886)
at android.view.View$PerformClick.run(View.java:29363)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7814)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)
How can I solve this issue without implementing PHP that is another way I found as I can't edit anything of the server where the database is hosted.
Thanks!
ClassNotFoundException: Didn't find class "java.sql.SQLType"
Since java.sql.SQLType was added in Java 8, and doesn't exist at all on Android, you need to use a JDBC driver that is Java 7 compatible, which means you cannot use Connector/J 8.0, but must use version 5.1.

Added mysql-connector, but connection is still dying

I try to send query to my database in android studio, i managed this a few years back with eclipse, but now i want to code apps with this IDE
First i show you my code:
private static int getAktuelleArtikelID() throws NumberFormatException, SQLException
{
ResultSet ergebnisSet = null;
int ergebnis;
try
{
Connection verbindung = DriverManager.getConnection("jdbc:mysql://localhost:3306/foo", "bar", "foobar!");
Statement statement = verbindung.createStatement();
String abfrage = "SELECT artikel_id FROM Artikel order by 1 desc limit 1";
ergebnisSet = statement.executeQuery(abfrage);
ergebnisSet.next();
}
catch (Exception exc)
{
exc.printStackTrace();
}
ergebnis = Integer.parseInt(ergebnisSet.getString(1));
return ergebnis;
}
The Code seems right in my opinoin, i rather have the problem with jdbc.
I added the mysqlconnector 5.1.44 like eplained here:
Answer 2 from
How to Mysql JDBC Driver to android studio
But i get this error:
W/System.err: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
W/System.err: at java.lang.reflect.Constructor.newInstance0(Native Method)
W/System.err: at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
W/System.err: at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
W/System.err: at com.mysql.jdbc.Util.getInstance(Util.java:408)
W/System.err: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:918)
W/System.err: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
W/System.err: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
W/System.err: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
W/System.err: at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2268)
W/System.err: at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2017)
W/System.err: at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:779)
W/System.err: at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
W/System.err: at java.lang.reflect.Constructor.newInstance0(Native Method)
W/System.err: at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
W/System.err: at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
W/System.err: at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:389)
W/System.err: at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330)
W/System.err: at java.sql.DriverManager.getConnection(DriverManager.java:569)
at java.sql.DriverManager.getConnection(DriverManager.java:219)
W/System.err: at com.example.androidcameraapi2.Database.getAktuelleArtikelID(Database.java:20)
W/System.err: at com.example.androidcameraapi2.Database.artikelHochladen(Database.java:40)
W/System.err: at com.example.androidcameraapi2.MainActivity$7.onClick(MainActivity.java:227)
W/System.err: at android.view.View.performClick(View.java:6597)
W/System.err: at android.view.View.performClickInternal(View.java:6574)
W/System.err: at android.view.View.access$3100(View.java:778)
W/System.err: at android.view.View$PerformClick.run(View.java:25885)
W/System.err: at android.os.Handler.handleCallback(Handler.java:873)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err: at android.os.Looper.loop(Looper.java:193)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6669)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
W/System.err: Caused by: android.os.NetworkOnMainThreadException
W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:117)
W/System.err: at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:105)
at java.net.InetAddress.getAllByName(InetAddress.java:1154)
W/System.err: at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:188)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:300)
W/System.err: at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2189)
W/System.err: at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2222)
W/System.err: ... 24 more
D/AndroidRuntime: Shutting down VM
Also graddle wants an update, but i already tried it and it seems to make everything worse
Here are some suggestions:
Never, ever pass a ResultSet out of method scope. You create it in a method and clean it up in that method. Load the data into objects and return those to the caller.
Never, ever create a Connection in a data access class this way. You should be using pooled connections.
Real applications log exceptions.
Stick to SQL that isn't database specific (e.g. MySQL). You keep your code portable that way.
If a value should be unique, build that requirement into your schema, not the query that fetches it.
Connection parameters like URL, username, password should be externalized from your app in configuration.
You should never use a database admin credential in an application.
Plain text credentials are an invitation to break into your database.
Here's how I might write your method:
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
* JDBC demo.
* User: mduffy
* Date: 5/8/19
* Time: 2:37 PM
* #link https://stackoverflow.com/questions/56046854/added-mysql-connector-but-connection-is-still-dying?noredirect=1#comment98735575_56046854
*/
public class JdbcDemo {
private static final String SELECT_SQL = "SELECT artikel_id FROM Artikel ";
private DataSource dataSource;
public JdbcDemo(DataSource dataSource) {
this.dataSource = dataSource;
}
public List<String> getAktuelleArtikelID() {
List<String> aktuelleArtikelId = new ArrayList<>();
ResultSet rs = null;
Statement st = null;
try {
st = this.dataSource.getConnection().createStatement();
rs = st.executeQuery(SELECT_SQL);
while (rs.next()) {
aktuelleArtikelId.add(rs.getString(1));
}
}
catch (Exception e) {
e.printStackTrace();
} finally {
close(rs);
close(st);
}
return aktuelleArtikelId;
}
// Should be in a utility class
private static void close(ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void close(Statement st) {
try {
if (st != null) {
st.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

Getting `File not found` errors for an `asset`. How can this be?

I'm about to go nuts with this. I keep getting errors when trying to open a text file that's in my assets directory, whose full path name is
C:\Users\Dov\Google Drive\AndroidStudioProjects\WordyHelperton - Copy - Copy\
app\src\main\assets
Even though we can SEE filename Dictionary.dic in the assets folder for my project...
... I keep getting errors that the file doesn't exist:
W/`````: Can't open <Dictionary.dic>
W/System.err: java.io.FileNotFoundException: Dictionary.dic
W/System.err: at android.content.res.AssetManager.openAsset(Native Method)
W/System.err: at android.content.res.AssetManager.open(AssetManager.java:316)
W/System.err: at android.content.res.AssetManager.open(AssetManager.java:290)
W/System.err: at com.dslomer64.servyhelperton.DatabaseConnector$LoadDatabase.doInBackground(DatabaseConnector.java:328)
W/System.err: at com.dslomer64.servyhelperton.DatabaseConnector$LoadDatabase.doInBackground(DatabaseConnector.java:315)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err: at java.lang.Thread.run(Thread.java:841)
Doc says you can use hierarchical name in the open statement:
W/`````: Can't open <C:\Users\Dov\Google Drive\AndroidStudioProjects\WordyHelperton - Copy - Copy\app\src\main\assets\Dictionary.dic>
W/System.err: java.io.FileNotFoundException: C:\Users\Dov\Google Drive\AndroidStudioProjects\WordyHelperton - Copy - Copy\app\src\main\assets\Dictionary.dic
W/System.err: at android.content.res.AssetManager.openAsset(Native Method)
W/System.err: at android.content.res.AssetManager.open(AssetManager.java:316)
W/System.err: at android.content.res.AssetManager.open(AssetManager.java:290)
W/System.err: at com.dslomer64.servyhelperton.DatabaseConnector$LoadDatabase.doInBackground(DatabaseConnector.java:330)
W/System.err: at com.dslomer64.servyhelperton.DatabaseConnector$LoadDatabase.doInBackground(DatabaseConnector.java:317)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
Same problem.
Can you see any problem with my code? The problem HAS to be obvious, but after two days of trying this and that and utterly failing, and it LOOKS so good and therefore MUST be obvious, but I CAN'T SEE IT....
I've included this in case it's not obvious from above. If this doesn't help, I'm on my own.
Here is how DatabaseConnector gets called in onCreate in MainActivity:
assets = getAssets();
dbc = new DatabaseConnector(getApplicationContext(), assets); // to create DB if needed
Here's how mAssets and SOURCE_NAME are defined; also have DatabaseConnector definition and its call to dbOpenHelper.
Here's how LoadDatabase is called from createDbIfNecessary:
LoadDatabase
__loadDb;
__loadDb = new LoadDatabase();
__loadDb.execute((Object[]) null);
EDIT
Another opinion:
EDIT 2
Please note that changing the filename in the code to lowercase doesn't help. AND it's a DOS file, NOT ANDROID. AND File is never leaving drive C:
public static String DATABASE_SOURCE =
"C:\\Users\\Dov\\Desktop\\ServyHelperton\\app\\src\\main" +
"\\assets\\dictionary.dic";
W/`````: Can't open <C:\Users\Dov\Desktop\ServyHelperton\app\src\main\assets\dictionary.dic>
W/System.err: java.io.FileNotFoundException: C:\Users\Dov\Desktop\ServyHelperton\app\src\main\assets\dictionary.dic
I could add more code to prove what I just said, but trust me. The DATABASE_SOURCE name is ALL I changed.
It appears your path is for Dictionary.dic rather than dictionary.dic
See if that helps
In the end, the fix was sort of easy or maybe dumb luck, because I'm not sure why making the InputStream and Scanner local to doInBackground cured the problem.
Refer to the first picture in the original Question. I made no significant changes to MainActivity, but here is the interesting line in it:
dbc = new DatabaseConnector(getApplicationContext(), getAssets());
This is what worked:
public class DatabaseConnector
{
static Context mContext;
public DatabaseConnector(Context _context, AssetManager _assets)
{
mAssets = _assets;
mContext = _context;
mDbOpenHelper = new DbOpenHelper(_context, DATABASE_NAME, null, 1);
createDbIfNecessary();
}
private class DbOpenHelper extends SQLiteOpenHelper
{
DbOpenHelper(Context _context, String _name, CursorFactory _factory, int _version)
{
super(_context, _name, _factory, _version);
}
private class LoadDatabase extends AsyncTask<Object, Integer, Void>
{
protected Void doInBackground(Object[] params)
{
Scanner scDict = null; // ***** MOVING/ADDING THESE
InputStream stream; // ***** TWO LINES HERE WAS KEY
try{
stream = mContext.getAssets().open(DATABASE_SOURCE);
scDict = new Scanner(stream).useDelimiter("\r\n");
}
catch(IOException e){e.printStackTrace(); System.exit(69);}
}
}
}
}

Sqlite database is corrupted after copy on some devices android

I'm new in android development and this is my first app with a database. I created a database with DB Browser for SQlite under Ubuntu.
It seems that the problem is present on Android devices below marhmallow but i'm not completely sure.
here ther's my code to copy database:
//version number.
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "db.sqlite";
private static String DATABASE_PATH = "/data/data/com.andrea.risuscito_passaggi/databases/";
private SQLiteDatabase myDataBase;
private final Context myContext;
public DBHelper(Context context ) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.myContext = context;
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
public void copyDataBase() throws IOException{
boolean bCopyOk = false;
try{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
// Path to the just created empty db
String outFileName = DATABASE_PATH + DATABASE_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>-1) myOutput.write(buffer, 0, length);
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
bCopyOk = true;
}catch(Exception ex){
ex.printStackTrace();
}finally{
if (bCopyOk) Log.v(TAG, "[copyDataBase] - Database copied OK!");
}
}
With all devices with Android Nougat (7.0.x) all works fine but, if i test this app on another version of android, i find this error log:
03-22 20:08:21.660 9010-9010/com.andrea.risuscito_passaggi E/SQLiteLog: (14) cannot open file at line 31278 of [2ef4f3a5b1]
03-22 20:08:21.661 9010-9010/com.andrea.risuscito_passaggi E/SQLiteLog: (14) os_unix.c:31278: (2) open(/data/data/com.andrea.risuscito_passaggi/databases/db.sqlite) -
03-22 20:08:21.661 9010-9010/com.andrea.risuscito_passaggi E/SQLiteDatabase: Failed to open database '/data/data/com.andrea.risuscito_passaggi/databases/db.sqlite'.
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:207)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:191)
at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:845)
at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:830)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:723)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:690)
at com.andrea.risuscito_passaggi.DBHelper.openDataBase(DBHelper.java:154)
at com.andrea.risuscito_passaggi.MainActivity.onCreate(MainActivity.java:94)
at android.app.Activity.performCreate(Activity.java:6304)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2539)
at android.app.ActivityThread.access$900(ActivityThread.java:159)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1384)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:152)
at android.app.ActivityThread.main(ActivityThread.java:5507)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
03-22 20:08:21.662 9010-9010/com.andrea.risuscito_passaggi W/SQLiteDatabase: Retry to open database[/data/data/com.andrea.risuscito_passaggi/databases/db.sqlite] due to error: android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
03-22 20:08:21.662 9010-9010/com.andrea.risuscito_passaggi E/SQLiteLog: (14) cannot open file at line 31278 of [2ef4f3a5b1]
03-22 20:08:21.662 9010-9010/com.andrea.risuscito_passaggi E/SQLiteLog: (14) os_unix.c:31278: (2) open(/data/data/com.andrea.risuscito_passaggi/databases/db.sqlite) -
03-22 20:08:21.663 9010-9010/com.andrea.risuscito_passaggi E/SQLiteDatabase: Failed to open database '/data/data/com.andrea.risuscito_passaggi/databases/db.sqlite'.
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:207)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:191)
at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:845)
at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:830)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:732)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:690)
at com.andrea.risuscito_passaggi.DBHelper.openDataBase(DBHelper.java:154)
at com.andrea.risuscito_passaggi.MainActivity.onCreate(MainActivity.java:94)
at android.app.Activity.performCreate(Activity.java:6304)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2539)
at android.app.ActivityThread.access$900(ActivityThread.java:159)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1384)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:152)
at android.app.ActivityThread.main(ActivityThread.java:5507)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I've searched a lot but i don't find any solution. Thanks
EDIT:
I stopped looking for the error only in java code and I began to look into the database code. I found two errors:
the folder to the empty database was not created, so I added this code before copy database
// check if databases folder exists, if not create one and its subfolders
File databaseFile = new File( DATABASE_PATH);
if (!databaseFile.exists()){
databaseFile.mkdir();
}
there was a view in the database that was clobbered, I could not fix it but I solved by writing the query from java
I stopped looking for the error only in java code and I began to look into the database code. I found two errors:
1.the folder to the empty database was not created, so I added this code before copy database
// check if databases folder exists, if not create one and its subfolders
File databaseFile = new File( DATABASE_PATH);
if (!databaseFile.exists()){
databaseFile.mkdir();
}
there was a view in the database that was clobbered, I could not fix it but I solved by writing the query from java

No such table found even though app successfully opens database from assets folder

I'm new to android development. I'm trying to use a pre-populated database whoch is stored in my assets folder. Log shows that the database gets opened but 'NO SUCH TABLE ERROR' is shown.I can't find any solution to this error. Please help.
MyDatabase.java :
package com.example.android.atlas;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
/**
* Created by Deep on 22-06-2015.
*/
public class MyDatabase extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "appver-1.db";
private static final int DATABASE_VERSION = 1;
public MyDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// you can use an alternate constructor to specify a database location
// (such as a folder on the sd card)
// you must ensure that this folder is available and you have permission
// to write to it
//super(context, DATABASE_NAME, context.getExternalFilesDir(null).getAbsolutePath(), null, DATABASE_VERSION);
}
public SQLiteDatabase getData() {
SQLiteDatabase db = getReadableDatabase();
return db;
}
}
PlayActivity.java
public class PlayActivity extends Activity {
private MyDatabase db;
private SQLiteDatabase dbh;
private Cursor togo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new MyDatabase(this);
dbh = db.getData();
setContentView(R.layout.activity_play);
}
public void onClickGo(View view){
String nm1;
String nm2;
String nm3;
String sendsql,send;
char last;
int l;
TextView tv2_text, tv4_text;
EditText et1_input;
tv2_text = (TextView)findViewById(R.id.tv2_text);
tv4_text = (TextView)findViewById(R.id.tv4_text);
et1_input = (EditText)findViewById(R.id.et1_input);
nm1 = et1_input.getText().toString();
l = nm1.length();
last = nm1.charAt(l - 1);
nm2 = "Africa";
nm3 = "A";
sendsql = "Select PLACES from countries where PLACES like " + "'" + nm3 + "%'" + " LIMIT 1" ;
togo = dbh.rawQuery(sendsql,null);
togo.moveToFirst();
send = togo.getString(0);
tv2_text.setText(send);
tv4_text.setText("A");
}
LOGCAT RESULT :
06-23 11:57:57.193 2330-2330/? I/SQLiteAssetHelper﹕ successfully opened database appver-1.db
06-23 11:57:57.294 2330-2345/? W/EGL_emulation﹕ eglSurfaceAttrib not implemented
06-23 11:57:57.294 2330-2345/? W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5d8a300, error=EGL_SUCCESS
06-23 11:57:57.497 1234-1257/? I/ActivityManager﹕ Displayed com.example.android.atlas/.PlayActivity: +346ms
06-23 11:57:57.623 2330-2345/? D/OpenGLRenderer﹕ endAllStagingAnimators on 0xa6d6e400 (RippleDrawable) with handle 0xae1bb990
06-23 11:57:58.842 2330-2330/? E/SQLiteLog﹕ (1) no such table: COUNTRIES
06-23 11:57:58.843 2330-2330/? D/AndroidRuntime﹕ Shutting down VM
06-23 11:57:58.843 2330-2330/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.android.atlas, PID: 2330
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4007)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: android.database.sqlite.SQLiteException: no such table: COUNTRIES (code 1): , while compiling: SELECT * FROM COUNTRIES
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
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:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1255)
at com.example.android.atlas.PlayActivity.onClickGo(PlayActivity.java:53)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
06-23 11:57:58.851 1234-1508/? W/ActivityManager﹕ Force finishing activity com.example.android.atlas/.PlayActivity
you should copy the .db file from your assets folder to an internal/external storage. You can use following codes,
private static String DB_PATH = "/data/data/your package/database/";
private static String DB_NAME ="final.db";// Database name
To create a database,
public void createDataBase() throws IOException
{
//If database not exists copy it from the assets
boolean mDataBaseExist = checkDataBase();
if(!mDataBaseExist)
{
try
{
//Copy the database from assests
copyDataBase();
Log.e(TAG, "createDatabase database created");
}
catch (IOException mIOException)
{
throw new Error("ErrorCopyingDataBase");
}
}
}
Check that the database exists here: /data/data/your package/database/DB Name
private boolean checkDataBase()
{
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
Copy the database from assets
private void copyDataBase() throws IOException
{
InputStream mInput = getApplicationContext().getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream mOutput = new FileOutputStream(outFileName);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer))>0)
{
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
mOutput.close();
mInput.close();
}
i hope it should help you.
This link may also help you...
If i am not wrong you didn't copy your sqlite database from your assets folder. Try the following
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
If you are not copy database then you got no such table erroer. This is one scenario.
I think there is some problem with table name.
Currently you are using "countries" as table name.

Categories

Resources