Android studio JDBC MySQL - java

I am trying to solve this problem for 4 hours and I am completely without hope.
I am using android studio for coding this application. I have created a simple activity which holds edit field for user name and password and next there is a button which is meant to be to submit data from these two edit fields.
I am using mysql connector/j and the java code is following:
package allanko.quizzerappandroid;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.sql.*;
public class LoginActivity extends AppCompatActivity
{
private static CDatabase db;
#Override
protected void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_login );
db = new CDatabase();
}
/*
public static CDatabase getDB()
{
return db;
}*/
public class CDatabase
{
private String db_name;
private String db_user;
private String db_pass;
private Connection connection;
private boolean isConnected;
public CDatabase()
{
db_name = "jdbc:mysql://localhost:3306/quizzer?useSSL=false";
db_user = "quizzer";
db_pass = "pass";
connection = null;
if( connect() == true )
isConnected = true;
else
isConnected = false;
printResult();
}
private boolean connect()
{
try
{
connection = DriverManager.getConnection( db_name, db_user, db_pass );
return true;
}
catch( Exception exc )
{
exc . printStackTrace();
return false;
}
}
private void printResult()
{
TextView dbText = (TextView)findViewById( R.id.dbText );
if( ! isConnected )
dbText . setText( "Connection to database failed" );
else
dbText . setText( "Connected to database." );
}
public ResultSet query( String query) throws SQLException
{
Statement statement = connection . createStatement();
return statement . executeQuery( query );
}
public boolean isConnected()
{
return isConnected;
}
}
}
When I start this application on whether emulator or my phone, it every time write "Connection to database failed." and I am getting this from console:
W/art: Common causes for lock verification issues are non-optimized dex code
W/art: and incorrect proguard optimizations.
W/art: Class android.support.v4.util.LruCache failed lock verification and will run slower.
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
W/System.err: java.sql.SQLException: java.lang.VerifyError: Verifier rejected class com.mysql.jdbc.CharsetMapping: void com.mysql.jdbc.CharsetMapping.<clinit>() failed to verify: void com.mysql.jdbc.CharsetMapping.<clinit>(): [0x4287] Invalid reg type for array index (Precise Reference: com.mysql.jdbc.MysqlCharset[]) (declaration of 'com.mysql.jdbc.CharsetMapping' appears in /data/app/allanko.quizzerappandroid-1/base.apk)
W/System.err: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:963)
W/System.err: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:896)
W/System.err: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:885)
W/System.err: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
W/System.err: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:877)
W/System.err: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:873)
W/System.err: at com.mysql.jdbc.Util.handleNewInstance(Util.java:422)
W/System.err: at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:410)
W/System.err: at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:328)
W/System.err: at java.sql.DriverManager.getConnection(DriverManager.java:569)
W/System.err: at java.sql.DriverManager.getConnection(DriverManager.java:219)
W/System.err: at allanko.quizzerappandroid.LoginActivity$CDatabase.connect(LoginActivity.java:55)
W/System.err: at allanko.quizzerappandroid.LoginActivity$CDatabase.<init>(LoginActivity.java:43)
W/System.err: at allanko.quizzerappandroid.LoginActivity.onCreate(LoginActivity.java:19)
W/System.err: at android.app.Activity.performCreate(Activity.java:6664)
W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
W/System.err: at android.app.ActivityThread.-wrap12(ActivityThread.java)
W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err: at android.os.Looper.loop(Looper.java:154)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6077)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
W/System.err: Caused by: java.lang.VerifyError: Verifier rejected class com.mysql.jdbc.CharsetMapping: void com.mysql.jdbc.CharsetMapping.<clinit>() failed to verify: void com.mysql.jdbc.CharsetMapping.<clinit>(): [0x4287] Invalid reg type for array index (Precise Reference: com.mysql.jdbc.MysqlCharset[]) (declaration of 'com.mysql.jdbc.CharsetMapping' appears in /data/app/allanko.quizzerappandroid-1/base.apk)
W/System.err: at com.mysql.jdbc.CharsetMapping.getNumberOfCharsetsConfigured(CharsetMapping.java:687)
W/System.err: at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:464)
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:430)
W/System.err: at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
W/System.err: ... 19 more
W/gralloc_ranchu: Gralloc pipe failed
I am completely desperate because I tried to google everything that came to my mind and nothing worked.
Thanks in advance for your answers.

Hope that this link should help you in resolving the issue. It so happens that you would've been referring to the project instead of referring to the corresponding library.
The compiler flags problems of this kind where method signatures won't tally. JVM verifies the bytecode when the class is loaded, and throws a VerifyError when the bytecode tries to do something that it should not be allowed to.
Other possibilities to check on this can be:
It can be because of change in the referenced libraries. Clean Project and followed by a Build might help!
Restarting your IDE might also help as it can be the IDE's fault to refer an incorrect version of the necessary jar.

I had same problem. (Sorry, I can't speak english well).
My solution was change MySql Driver x MariaDB Driver.
I think that problem is that there are two class with same name com.mysql.jdbc.CharsetMapping. When I use MariaDB, org.mariadb.jdbc.Driver I change second class to org.mariadb.jdbc.CharsetMapping, and problem solved.
I wish that this help you.
Best regards.

Related

Connection between Arduino bluetooth module HC-05 and Androidstudio app

i've a problem with the connection between the module HC-05 of Arduino and my android app on AndroidStudio.
When i try to connect, the log show me that after the socket creation, it doesn't make the connection. Why?
This is the part of code where i make the connection:
if(nome_device.equals("BT05") || nome_device.equals("BT06")){
BluetoothDevice dev = mBlueadapter.getRemoteDevice(MAC_address);
ParcelUuid list[] = dev.getUuids();
System.out.println("ciao");
System.out.println(dev);
BluetoothSocket btSocket = null;
int count = 0;
do {
try {
btSocket = dev.createRfcommSocketToServiceRecord(uuid); //creo un socket per comunicare
// System.out.println(dev);
// System.out.println(btSocket);
btSocket.connect(); //avvio la connessione
System.out.println(btSocket.isConnected());
} catch (IOException e) {
e.printStackTrace();
}
count++;
} while(!btSocket.isConnected() && count < 3);
try {
OutputStream outputStream = btSocket.getOutputStream();
outputStream.write(48);
} catch (IOException e) {
e.printStackTrace();
}
try {
InputStream inputStream = btSocket.getInputStream();
inputStream.skip(inputStream.available()); //pulisce il buffer
for(int i=0; i<26; i++){
byte b = (byte) inputStream.read();
System.out.println((char) b);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
btSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
else
Toast.makeText(this, "The selected device is not compatible with this app! ", Toast.LENGTH_SHORT).show();
And this is the log after i click on the name of the module:
2021-03-15 21:22:43.978 8585-8585/com.example.skatex W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
2021-03-15 21:22:43.983 8585-8585/com.example.skatex D/BluetoothUtils: isSocketAllowedBySecurityPolicy start : device null
2021-03-15 21:22:43.984 8585-8585/com.example.skatex W/System.err: java.io.IOException: bt socket closed, read return: -1
2021-03-15 21:22:43.985 8585-8585/com.example.skatex W/System.err: at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:721)
2021-03-15 21:22:43.985 8585-8585/com.example.skatex W/System.err: at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:59)
2021-03-15 21:22:43.986 8585-8585/com.example.skatex W/System.err: at com.example.skatex.Bluetooth.connection(Bluetooth.java:200)
2021-03-15 21:22:43.986 8585-8585/com.example.skatex W/System.err: at com.example.skatex.Bluetooth.access$200(Bluetooth.java:32)
2021-03-15 21:22:43.986 8585-8585/com.example.skatex W/System.err: at com.example.skatex.Bluetooth$2.onItemClick(Bluetooth.java:93)
2021-03-15 21:22:43.987 8585-8585/com.example.skatex W/System.err: at android.widget.AdapterView.performItemClick(AdapterView.java:374)
2021-03-15 21:22:43.987 8585-8585/com.example.skatex W/System.err: at android.widget.AbsListView.performItemClick(AbsListView.java:1736)
2021-03-15 21:22:43.987 8585-8585/com.example.skatex W/System.err: at android.widget.AbsListView$PerformClick.run(AbsListView.java:4207)
2021-03-15 21:22:43.988 8585-8585/com.example.skatex W/System.err: at android.widget.AbsListView$7.run(AbsListView.java:6692)
2021-03-15 21:22:43.988 8585-8585/com.example.skatex W/System.err: at android.os.Handler.handleCallback(Handler.java:883)
2021-03-15 21:22:43.989 8585-8585/com.example.skatex W/System.err: at android.os.Handler.dispatchMessage(Handler.java:100)
2021-03-15 21:22:43.989 8585-8585/com.example.skatex W/System.err: at android.os.Looper.loop(Looper.java:237)
2021-03-15 21:22:43.989 8585-8585/com.example.skatex W/System.err: at android.app.ActivityThread.main(ActivityThread.java:8107)
2021-03-15 21:22:43.990 8585-8585/com.example.skatex W/System.err: at java.lang.reflect.Method.invoke(Native Method)
2021-03-15 21:22:43.990 8585-8585/com.example.skatex W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
2021-03-15 21:22:43.990 8585-8585/com.example.skatex W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
2021-03-15 21:22:43.992 8585-8585/com.example.skatex D/BluetoothSocket: close() this: android.bluetooth.BluetoothSocket#3a48555, channel: -1, mSocketIS: android.net.LocalSocketImpl$SocketInputStream#26adb6a, mSocketOS: android.net.LocalSocketImpl$SocketOutputStream#455e85bmSocket: android.net.LocalSocket#6c1d8f8 impl:android.net.LocalSocketImpl#87521d1 fd:java.io.FileDescriptor#2d34436, mSocketState: INIT
2021-03-15 21:22:43.994 8585-8585/com.example.skatex I/Choreographer: Skipped 1163 frames! The application may be doing too much work on its main thread.
If someone can help me i appreciate a lot.
isSocketAllowedBySecurityPolicy start : device null
this means you didn't get the remote device.
The application may be doing too much work on its main thread
This is another important message, you are running a long task on the main thread.
Take a look on this google example on how to manage the bluetooth connection

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);}
}
}
}
}

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

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

Categories

Resources