Connection between Arduino bluetooth module HC-05 and Androidstudio app - java

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

Related

I don't understand why mkdir() returns false?

I am trying to write my bitmap files to a filepath in a directory I create in androids external storage but when I run my code I recieve a null pointer exception from bitmap.compress (bitmap.CompressFormat.JPEG, 0, outputStream). From debugging I have found that my bitmap object is not null & that the outputStream object is null so the null pointer exception is occuring when I create the outputStream object & I recieve a java.io.FileNotFoundException. From debugging I know that the java.io.FileNotFoundException is occuring because dir.mkdir () returns false so no directory is created for my bitmap files.
I don't understand why dir.mkdir () returns false because I instantiate dir & check if the external storage is writable in isExternalStorageWritable() and add <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in my manifest file and have created askPermission(), onRequestPermissionsResult()& isStoragePermissionGranted () that ask the user for permission for the external storage. So I don't understand why dir.mkdir () returns false and the directory is not created.
This is the class where the exception occurs:
public class BitmapFiles {
public String imagePath;
public String name;
private Bitmap bitmap;
private int resourceId;
private Context context;
private OutputStream outputStream;
private File file;
public BitmapFiles (Context context, int resourceId, String name) {
this.resourceId = resourceId;
this.name = name;
this.context = context;
convertToBitmap();
saveBitmap();
setImagePath();
}
public void convertToBitmap () {
bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId);
}
public void saveBitmap () {
File filePath = Environment.getExternalStorageDirectory ();
File dir = new File (filePath.getAbsolutePath() + "/Items");
if (isExternalStorageWritable()) {
Log.d ("red", "external storage is writable");//I recieve this in the log cat
}
if (!dir.exists ()) {
try {
boolean direct = dir.mkdir();//Returns false
if (dir.exists()) {
Log.d ("blue", "directory exists now");//I don't recieve this in the log cat
}
if (!direct) {
Log.d ("green", "the directory was not created");//I recieve this in the log cat
}
} catch (SecurityException e) {
e.printStackTrace();
}
} else {
Log.d ("yellow", "the directory already exists");
}
file = new File (dir, name + ".jpg");
try {
outputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace ();
}
if (outputStream == null) {
Log.d ("grey", "outputstream is null");//I recieve this in log cat
}
bitmap.compress (Bitmap.CompressFormat.JPEG, 0, outputStream);
}
public boolean isExternalStorageWritable () {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals (state)) {
return true;
}
return false;
}
}
This is the class where I ask the user for permission:
public class GroceryItem extends AppCompatActivity {
private static final int STORAGE_PERMISSION_CODE = 101;
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grocery_item);
askForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, STORAGE_PERMISSION_CODE);
}
public void askForPermission (String permission, int requestCode) {
if (isStoragePermissionGranted()) {
ActivityCompat.requestPermissions(this, new String [] {permission}, requestCode);
} else {
Toast.makeText (this, "Permission already granted", Toast.LENGTH_SHORT)
.show();
}
}
public void onRequestPermissionsResult (int requestCode, String [] permissions, int [] grantResults) {
super.onRequestPermissionsResult (requestCode, permissions, grantResults);
if (requestCode == STORAGE_PERMISSION_CODE) {
if (grantResults.length > 0 && grantResults [0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Storage Permission Granted", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(this, "Storage Permission Denied", Toast.LENGTH_SHORT)
.show();
}
}
}
public boolean isStoragePermissionGranted () {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "permission granted", Toast.LENGTH_SHORT)
.show();
return true;
}
return false;
}
}
This is the exception I recieve:
2020-09-23 10:18:20.829 32212-32263/com.myapp.groceryapp W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Items/faan.jpg: open failed: ENOENT (No such file or directory)
2020-09-23 10:18:20.829 32212-32263/com.myapp.groceryapp W/System.err: at libcore.io.IoBridge.open(IoBridge.java:496)
2020-09-23 10:18:20.829 32212-32263/com.myapp.groceryapp W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:235)
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:186)
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp W/System.err: at com.myapp.groceryapp.BitmapFiles.saveBitmap(BitmapFiles.java:82)
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp W/System.err: at com.myapp.groceryapp.BitmapFiles.<init>(BitmapFiles.java:30)
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp W/System.err: at com.myapp.groceryapp.MyDatabaseHelper.createBitmapFiles(MyDatabaseHelper.java:42)
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp W/System.err: at com.myapp.groceryapp.MyDatabaseHelper.upgradeDatabase(MyDatabaseHelper.java:37)
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp W/System.err: at com.myapp.groceryapp.MyDatabaseHelper.onCreate(MyDatabaseHelper.java:33)
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp W/System.err: at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:412)
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp W/System.err: at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:341)
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp W/System.err: at com.myapp.groceryapp.GroceryItem.accessDataBase(GroceryItem.java:44)
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp W/System.err: at com.myapp.groceryapp.GroceryItem$StartDatabase.doInBackground(GroceryItem.java:101)
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp W/System.err: at com.myapp.groceryapp.GroceryItem$StartDatabase.doInBackground(GroceryItem.java:93)
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp W/System.err: at android.os.AsyncTask$3.call(AsyncTask.java:378)
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp W/System.err: at java.lang.Thread.run(Thread.java:919)
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp W/System.err: at libcore.io.Linux.open(Native Method)
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:252)
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp W/System.err: at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7581)
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp W/System.err: at libcore.io.IoBridge.open(IoBridge.java:482)
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp W/System.err: ... 18 more
2020-09-23 10:18:20.830 32212-32263/com.myapp.groceryapp D/outty: outputstream is null
2020-09-23 10:18:20.836 32212-32263/com.myapp.groceryapp E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.myapp.groceryapp, PID: 32212
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.NullPointerException
at android.graphics.Bitmap.compress(Bitmap.java:1407)
at com.myapp.groceryapp.BitmapFiles.saveBitmap(BitmapFiles.java:95)
at com.myapp.groceryapp.BitmapFiles.<init>(BitmapFiles.java:30)
at com.myapp.groceryapp.MyDatabaseHelper.createBitmapFiles(MyDatabaseHelper.java:42)
at com.myapp.groceryapp.MyDatabaseHelper.upgradeDatabase(MyDatabaseHelper.java:37)
at com.myapp.groceryapp.MyDatabaseHelper.onCreate(MyDatabaseHelper.java:33)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:412)
at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:341)
at com.myapp.groceryapp.GroceryItem.accessDataBase(GroceryItem.java:44)
at com.myapp.groceryapp.GroceryItem$StartDatabase.doInBackground(GroceryItem.java:101)
at com.myapp.groceryapp.GroceryItem$StartDatabase.doInBackground(GroceryItem.java:93)
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) 
The NullPointerException and FileNotFoundException are caused by incorrect error recover code. Put simply, your code tries too hard to write that bitmap, in situations where it is simply not possible to do so. (If the directory doesn't exist after your attempt to create it, there is no way you could possibly save the bitmap. Persistence is futile!)
The root cause of the cascade of problems is that mkdir() is (in some circumstances) by creating the the required directory.
I don't understand why mkdir() returns false.
This could be happening for a variety of reasons, including some of the following:
The parent directory for the directory may not exist
The parent directory's ownership and permissions may be wrong
The app may not be permitted to write in this file system.
The device could be read only
The device could be corrupted or experiencing hardware errors
The file system could be so full that a directory cannot be created.
The problem is that it is not possible to find out which of those possible causes is the actual cause. File.mkdir() doesn't tell you, and doesn't provide a way to find out. java.io.File is a clunky old interface ... and you shouldn't be using it anymore. (It was superseded in Java 7!)
The first step in solving this is to change your application to using the NIO2 Files and Path APIs. In particular, you need to use one of:
Files.createDirectory(Path dir, FileAttribute<?>... attrs) (javadoc)
Files.createDirectories(Path dir, FileAttribute<?>... attrs) (javadoc)
These both will throw an exception if the directory could not be created. In addition, createDirectory will throw an exception if the directory already exists.
In either case, the exception and its message should tell you why the operation failed. This will help you to figure out what is really going on ... and hence work out how to fix it.

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

Unable to resolve host "My URL" - No address associated with hostname

The exception occurs randomly and then its hard to get rid of. I am tired of this error and despite the fact that I have tried almost everything on stackoverflow from changing url to respective IP address, using real device, adding internet permissions as mentioned or checking wifi connection. Everything is all right except the error which keeps coming back. Yes I also added checking connection code as below :
try {
ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm.getActiveNetworkInfo().isConnectedOrConnecting()) {
URL url = new URL(urlx);
HttpURLConnection urlc = (HttpURLConnection) url
.openConnection();
urlc.setConnectTimeout(1000); // mTimeout is in seconds
urlc.connect();
if (urlc.getResponseCode() == 200) {
runOnUiThread(new Runnable() {
public void run() {
//Do something on UiThread
upsuccess = true;
}
});
} else {
runOnUiThread(new Runnable() {
public void run() {
//Do something on UiThread
upsuccess = false;
}
});
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and System.setProperty("http.proxyHost", "myurl.com");
System.setProperty("http.proxyPort", "8080");
but each of them separately as well as together did not fetch me any useful results. Can you suggest me what to do?
I am basically doing this : I am uploading a pdf file on my server and loading the google docs viewer url with that url. I however see the following exception several times. I also added retrying in case I find the exception but the exception randomly happens and is not easy to get out of if you encounter it.
Exception :
java.net.UnknownHostException: Unable to resolve host "myurl.com": No
address associated with hostname 07-20 01:12:11.554
24907-24997/securitymsg.listmydocs W/System.err: at
java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:95)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at java.net.InetAddress.getAllByName(InetAddress.java:752) 07-20
01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err: at
okhttp3.Dns$1.lookup(Dns.java:39) 07-20 01:12:11.554
24907-24997/securitymsg.listmydocs W/System.err: at
okhttp3.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:173)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
okhttp3.internal.http.RouteSelector.nextProxy(RouteSelector.java:139)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at okhttp3.internal.http.RouteSelector.next(RouteSelector.java:81)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
okhttp3.internal.http.StreamAllocation.findConnection(StreamAllocation.java:172)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
okhttp3.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:123)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
okhttp3.internal.http.StreamAllocation.newStream(StreamAllocation.java:93)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at okhttp3.internal.http.HttpEngine.connect(HttpEngine.java:296) 07-20
01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err: at
okhttp3.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at okhttp3.RealCall.getResponse(RealCall.java:243) 07-20 01:12:11.554
24907-24997/securitymsg.listmydocs W/System.err: at
okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:201)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:163)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at okhttp3.RealCall.execute(RealCall.java:57) 07-20 01:12:11.554
24907-24997/securitymsg.listmydocs W/System.err: at
securitymsg.listmydocs.CloudViewer$UploadFileAsync.doInBackground(CloudViewer.java:678)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
securitymsg.listmydocs.CloudViewer$UploadFileAsync.doInBackground(CloudViewer.java:650)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at android.os.AsyncTask$2.call(AsyncTask.java:305) 07-20 01:12:11.554
24907-24997/securitymsg.listmydocs W/System.err: at
java.util.concurrent.FutureTask.run(FutureTask.java:237) 07-20
01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err: at
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 07-20
01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err: at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at java.lang.Thread.run(Thread.java:761) 07-20 01:12:13.016
24907-24907/securitymsg.listmydocs W/cr_BindingManager: Cannot call
determinedVisibility() - never saw a connection for the pid: 24907
07-20 01:12:13.677 24907-24907/securitymsg.listmydocs
W/cr_BindingManager: Cannot call determinedVisibility() - never saw a
connection for the pid: 24907 07-20 01:12:13.678
24907-24907/securitymsg.listmydocs W/cr_BindingManager: Cannot call
determinedVisibility() - never saw a connection for the pid: 24907
My Permissions in manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
My code to upload file :
*PHP :
<?php
$file_path = "images/";
$neran = $_GET['neran'];
$ext = pathinfo(basename( $_FILES['uploaded_file']['name']), PATHINFO_EXTENSION);
$file_path = "images/".$neran.".".$ext;
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path) ){
echo "success";
} else{
echo "fail";
}
?>
Android side (I use Retrofit) : The following code is in doinbackground block of AsyncTask
String file_path = f.getAbsolutePath();
OkHttpClient client = new OkHttpClient();
RequestBody file_body = RequestBody.create(MediaType.parse(content_type),f);
Log.e("msh", content_type);
RequestBody request_body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("type",content_type)
.addFormDataPart("uploaded_file",file_path.substring(file_path.lastIndexOf("/")+1), file_body)
.build();
Request request = new Request.Builder()
.url("http://reviewitapp.co/retrofit_example/save_file.php?neran="+neran)
.post(request_body)
.build();
response = client.newCall(request).execute();
} catch (UnknownHostException e) {
e.printStackTrace();
/*uploadFile(selectedFilePath);*/
upsuccess = false;
} catch (IOException e) {
e.printStackTrace();
upsuccess = false;
} catch (NullPointerException e) {
e.printStackTrace();
/*uploadFile(selectedFilePath);*/
upsuccess = false;
}
if(response!=null) {
if (response.isSuccessful()) {
upsuccess = true;
}
response.body().close();
}

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