Added mysql-connector, but connection is still dying - java

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

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

I'm trying to connect to mySql db in my server but whenever i try to do that the application shut down on its own

Hello i have a problem connecting to mySql Db on my server whenever i try to do so it shut down on its own i have imorted the jdbc lib into my project this version of it(mysql-connector-java-8.0.15.jar)
here is my connection class
Connection connection;
Statement statement;
public Database() {
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://ip:3306/test", "root", "pass");
statement = connection.createStatement();
//test = "Connected succefully";
} catch (ClassNotFoundException e) {
System.err.println(e);
// e.printStackTrace();
} catch (SQLException e) {
//test = e.getMessage();
System.err.println(e);
//e.printStackTrace();
}
}
and here is my error in the logcat error
2019-03-04 14:11:36.701 16708-16708/com.example.sony.test E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sony.test, PID: 16708 <br />
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sony.test/com.example.sony.test.settings}: java.lang.UnsupportedOperationException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.UnsupportedOperationException
at java.util.regex.Matcher.group(Matcher.java:383)
at com.mysql.cj.conf.ConnectionUrlParser.isConnectionStringSupported(ConnectionUrlParser.java:152)
at com.mysql.cj.conf.ConnectionUrl.acceptsUrl(ConnectionUrl.java:258)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:187)
at java.sql.DriverManager.getConnection(DriverManager.java:569)
at java.sql.DriverManager.getConnection(DriverManager.java:219)
at com.example.sony.test.Database.<init>(Database.java:25)
at com.example.sony.test.settings.onCreate(settings.java:61)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
i have been able to fix that problem, i just tried an older version of mysql-connector-java but now it throw an exception : could not create connection to database server.

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

Android studio JDBC MySQL

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.

Android UnkownHostException on devices with a lower API level

When trying my app on lower api levels such as 15 or 19(on emulators and real devices), i get a UnknownHostException for a specific URL: http://jotihunt-api_v2.mysite123.nl/login mysite123 is fictional. But i don't get a UnknownHostException for other urls such as that of google . So i seems the URL is wrong, but on API level 22 for example i don't get this exception. I have a Internet Connection and i have the required permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I use this code to execute post/get requests to a web API:
#Override
protected List<WebResponse> doInBackground(WebRequest... params) {
ArrayList<WebResponse> responses = new ArrayList<>();
WebRequest current;
for(int i = 0; i < params.length; i++)
{
current = params[i];
try {
InetAddress address = InetAddress.getByName(current.getUrl().getHost());
Log.i("WebRequestTask", address.toString());
} catch (UnknownHostException exception) {
Log.e("WebRequestTask", exception.toString(), exception);
}
TRYCATCH:
try
{
if(current.getUrl() == null) break TRYCATCH;
HttpURLConnection connection = (HttpURLConnection)current.getUrl().openConnection();
switch (current.getMethod())
{
case WebRequestMethod.POST:
if(current.hasData())
{
connection.setDoOutput(true);
connection.setRequestMethod(WebRequestMethod.POST);
OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
streamWriter.write(current.getData());
streamWriter.flush();
streamWriter.close();
}
break;
}
InputStream response;
if(connection.getResponseCode() == 200)
{
/*
* Get the response stream.
* */
response = connection.getInputStream();
}
else
{
/*
* Get the error stream.
* */
response = connection.getErrorStream();
}
/**
* Read the stream.
* */
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response));
StringBuilder builder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
bufferedReader.close();
/**
* Create a response
* */
responses.add(new WebResponse(current, builder.toString(), connection.getResponseCode()));
current.setExecutionDate(new Date());
connection.disconnect();
}
catch(Exception e)
{
/**
* Print the stack trace
* */
e.printStackTrace();
/**
* Log a error.
* */
Log.e("WebRequestTask", e.toString(), e);
/**
* Add a response with as text the error message
* */
responses.add(new WebResponse(current, e.toString(), 0));
}
}
return responses;
}
The state of the objects: http://imgur.com/8ehGBUf
The creation and execution of the request:
WebRequest request = new WebRequest.Builder()
.setId(MY_REQUEST_ID)
.setMethod(WebRequestMethod.POST)
.setUrl(new UrlBuilder().append("http://jotihunt-api_v2.mysite123.nl/login").build())
.setData("sfsf")
.create();
request.executeAsync(new WebRequest.OnWebRequestCompletedCallback() {
#Override
public void onWebRequestCompleted(WebResponse response) {
Log.i("",response.getData());
}
});
This is the exception i get:
08-16 12:33:36.340 4277-4356/nl.rsdt.japp W/System.err: java.net.UnknownHostException: http://jotihunt-api_v2.mysite123.nl/login
08-16 12:33:36.342 4277-4356/nl.rsdt.japp W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:279)
08-16 12:33:36.344 4277-4356/nl.rsdt.japp W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
08-16 12:33:36.346 4277-4356/nl.rsdt.japp W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
08-16 12:33:36.348 4277-4356/nl.rsdt.japp W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
08-16 12:33:36.352 4277-4356/nl.rsdt.japp W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
08-16 12:33:36.355 4277-4356/nl.rsdt.japp W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197)
08-16 12:33:36.356 4277-4356/nl.rsdt.japp W/System.err: at com.rsdt.anl.WebRequestTask.doInBackground(WebRequestTask.java:53)
08-16 12:33:36.357 4277-4356/nl.rsdt.japp W/System.err: at com.rsdt.anl.WebRequestTask.doInBackground(WebRequestTask.java:21)
08-16 12:33:36.358 4277-4356/nl.rsdt.japp W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
08-16 12:33:36.359 4277-4356/nl.rsdt.japp W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
08-16 12:33:36.360 4277-4356/nl.rsdt.japp W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
08-16 12:33:36.365 4277-4356/nl.rsdt.japp W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
08-16 12:33:36.372 4277-4356/nl.rsdt.japp W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
08-16 12:33:36.373 4277-4356/nl.rsdt.japp W/System.err: at java.lang.Thread.run(Thread.java:848)
UPDATE
I can resolve the host with InetAdress, but it still doesn't work
UPDATE 2
I found similar issues after some more googling, it seems that underscores are not valid URLs characters.
Sources:
(i cannot include more than 2 links so i left the begin of the link out)
stackoverflow.com/questions/36074952/unknown-host-exception-using-emulator-and-httpurlconnection
code.google.com/p/android/issues/detail?id=37577
github.com/google/ExoPlayer/issues/239
I changed the hostname so that is doesn't contain a underscore, this resolved my issues. It seems that the DNS on older android versions does not support URLs with a underscore
Sources:
Similiar issue
http://code.google.com/p/android/issues/detail?id=37577

Categories

Resources