Here is all of my code. I am trying to connect to my SQL server. These contents in sentences are actually exist. Real username and passwords. But I am getting Null on error catch (not connected). Please let me know where the error could be.
And I also added Internet permission in manifest.
I came across from this article - link
package com.eample.databasetester;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.widget.TextView;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class MainActivity extends Activity {
TextView txv1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txv1=(TextView)findViewById(R.id.text_view);
query2();
}
public void query2()
{
txv1.setText("connected");
Log.i("Android"," MySQL Connect Example.");
Connection conn = null;
try {
String driver = "net.sourceforge.jtds.jdbc.Driver";
Class.forName(driver).newInstance();
String connString = "jdbc:jtds:sqlserver://50.62.209.49:3306/test;encrypt=fasle;user=XXXX;password=YYYY;instance=SQLEXPRESS;";
String username = "XXXX";
String password = "YYYY";
conn = DriverManager.getConnection(connString,username,password);
Log.w("Connection","open");
Statement stmt = conn.createStatement();
ResultSet reset = stmt.executeQuery("select * from test");
while(reset.next()){
txv1.setText("Data:"+reset.getString(3));
}
conn.close();
} catch (Exception e)
{
txv1.setText("Error connection" + e.getMessage());
}
}
}
THis is a really bad idea. You should not connect to a database over the network from a phone. First off, it requires your DB to be publically addressable which is a security risk. Secondly, it means your password for the db is on the clients, and you don't physically control them. Your app will be reverse engineered, they'll get your password, and then your data is fucked. You should always abstract access to the database from any hardware you don't control by use of a webservice. Then the password never leaves your machines and the damage an attacker can do is limited.
Third, this code wont work anyway, you cant do network IO on the UI thread. That's likely why conn returned null. But take this as a sign of the universe telling you to fix things the right way rather than just changing threads.
Related
I'm trying to connect my Android app to Oracle Database Express Edition 11g hosted on my laptop. I'm testing the app on my phone with its hotspot ON to which the laptop is connected via WiFi.
I've added ojdbc14.jar to app/libs directory and selected Add as Library option on it through Android Studio.
I'm getting the following errors:
Rejecting re-init on previously-failed class java.lang.Class<oracle.jdbc.pool.OracleDataSource>: java.lang.NoClassDefFoundError: Failed resolution of: Ljavax/naming/Referenceable;
Caused by: java.lang.ClassNotFoundException: Didn't find class "javax.naming.Referenceable" on path: DexPathList
W/System.err: java.sql.SQLException: Io exception: The Network Adapter could not establish the connection
P.s. I know using a server is a better approach. Doing this for a client who wants to use it in a secure private network and they don't want to host a separate server for the database connection.
I read elsewhere that I need to use Async task for connecting JDBC but I'm not sure how; consider me a beginner. All other answers I found related to this keep going off topic. I just want to know how to make JDBC work on Android, considering the risks.
Here's my MainActivity.java:
package com.absingh.apptest;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MainActivity extends AppCompatActivity {
private static final String DEFAULT_DRIVER = "oracle.jdbc.driver.OracleDriver";
private static final String DEFAULT_URL = "jdbc:oracle:thin:#192.168.42.49:1521:XE";
private static final String DEFAULT_USERNAME = "myusername";
private static final String DEFAULT_PASSWORD = "mypassword";
private Connection connection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
TextView tv = (TextView) findViewById(R.id.hello);
try {
this.connection = createConnection();
Toast.makeText(MainActivity.this, "Connected",
Toast.LENGTH_SHORT).show();
Statement stmt=connection.createStatement();
StringBuffer stringBuffer = new StringBuffer();
ResultSet rs=stmt.executeQuery("select * from testtable");
while(rs.next()) {
stringBuffer.append( rs.getString(1)+"\n");
}
tv.setText(stringBuffer.toString());
connection.close();
}
catch (Exception e) {
Toast.makeText(MainActivity.this, ""+e,
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
public static Connection createConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException {
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
public static Connection createConnection() throws ClassNotFoundException, SQLException {
return createConnection(DEFAULT_DRIVER, DEFAULT_URL, DEFAULT_USERNAME, DEFAULT_PASSWORD);
}
}
Nevermind, I figured it out.
The code in the question works fine if you add this above the application tag in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
I'll leave the question be, in case someone else gets the same problem.
I am new to this JDBC driver. I am looking for ways to save user data from my android app to the google cloud mySQL. I happen to come across that JDBC might get this done.
However, I encounter this error No suitable driver found for jdbc:mysql://google/waveUserData?cloudSqlInstance=wavdata&socketFactory=com.google.cloud.sql.mysql.SocketFactory&useSSL=false
I have already downloaded the JDBC driver and put inside /library/java/extensions
Please help me with this, or please recommend me a method to efficiently user data from app to Google cloud mysql.
This is the code I am referring to: https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory/blob/master/examples/compute-engine/src/main/java/com/google/cloud/sql/mysql/example/ListTables.java
package com.google.cloud.sql.mysql.example;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* A sample app that connects to a Cloud SQL instance and lists all available tables in a database.
*/
public class ListTables {
public static void main(String[] args) throws IOException, SQLException {
// TODO: fill this in
// The instance connection name can be obtained from the instance overview page in Cloud Console
// or by running "gcloud sql instances describe <instance> | grep connectionName".
String instanceConnectionName = "<insert_connection_name>";
// TODO: fill this in
// The database from which to list tables.
String databaseName = "mysql";
String username = "root";
// TODO: fill this in
// This is the password that was set via the Cloud Console or empty if never set
// (not recommended).
String password = "<insert_password>";
if (instanceConnectionName.equals("<insert_connection_name>")) {
System.err.println("Please update the sample to specify the instance connection name.");
System.exit(1);
}
if (password.equals("<insert_password>")) {
System.err.println("Please update the sample to specify the mysql password.");
System.exit(1);
}
//[START doc-example]
String jdbcUrl = String.format(
"jdbc:mysql://google/%s?cloudSqlInstance=%s"
+ "&socketFactory=com.google.cloud.sql.mysql.SocketFactory&useSSL=false",
databaseName,
instanceConnectionName);
Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
//[END doc-example]
try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery("SHOW TABLES");
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
}
}
}
}
I'm new to Android Studio and I hope you don't consider my question silly.I am trying to write a small program in the terminal of the android studio.When I try to run the same program in my terminal(not android studio) it's working fine.I added the MySQL-connector.jar file in android studio lib by going through this mysql JDBC driver to the android studio.But it didn't work.Please help me.Thanks in advance.
//MySQConnectionExample.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
public class MySQLConnectionExample {
public static void main(String[] args) {
Connection conn1 = null;
String result = " ";
try {
Class.forName("com.mysql.jdbc.Driver");
String url1 = "jdbc:mysql://127.0.0.1:3306/demo";
String user = "root";
String password = "mypassword";
conn1 = DriverManager.getConnection(url1, user, password);
if (conn1 != null) {
System.out.println("Connected to the database test1");
}
String sql = " select address from pharmacy";
PreparedStatement prest = conn1.prepareStatement(sql);
ResultSet rs = prest.executeQuery();
while(rs.next()) {
result = rs.getString(1);
System.out.println(result);
}
} catch (SQLException ex) {
System.out.println("An error occurred. Maybe user/password is invalid");
ex.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
//Error after execution
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at MySQLConnectionExample.main(MySQLConnectionExample.java:16)
When I remove "Class.forName("com.mysql.jdbc.Driver")" from the program this is the error i get
An error occurred. Maybe user/password is invalid
java.sql.SQLException: No suitable driver found for
jdbc:mysql://127.0.0.1:3306/demo
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at MySQLConnectionExample.main(MySQLConnectionExample.java:22)
You can't connect directly to databases from android devices. Build APIs that connects to your database. then connect your Android Application to these APIs.
Check this answer for a the same question https://stackoverflow.com/a/12233178/4442067
I assume you're trying to directly connect to a MySQL database from your Android device. But first, you have a ClassNotFound exception, which means you haven't imported the library.
And when you get the driver to work, there's more problem in this part:
....
try {
Class.forName("com.mysql.jdbc.Driver");
String url1 = "jdbc:mysql://127.0.0.1:3306/demo";
String user = "root";
String password = "mypassword";
conn1 = DriverManager.getConnection(url1, user, password);
....
By specifying 127.0.0.1 on your Android device, you're trying to connect to a MySQL server on your device. Now I don't know if you can install MySQL on Android, but you may want to install a MySQL server on your computer. This goes without saying that you must use the IP of that computer and have the MySQL port (3306) open on your computer.
So, what you may want to see is something like
....
try {
Class.forName("com.mysql.jdbc.Driver");
String url1 = "jdbc:mysql://192.168.1.10:3306/demo";
String user = "root";
String password = "mypassword";
conn1 = DriverManager.getConnection(url1, user, password);
....
This assumes your MySQL server is installed and configured on your computer with IP address 192.168.1.10
Good luck.
EDIT: I can't really recommend this approach for a production application though, because I'm afraid what a hacker who can decompile your code can do with it.
I'm a complete beginner in android programming and am trying to make an app which requires access to the database on local host using the android studio, using the IP address of the server, I've watched many tutorial videos but still am not sure where to pass the IP address of the server.
The server uses MySQL, I've tried using JDBC but still unable to achieve the result.
Here is my code, any help would be appreciated.
`package com.example.vishal.connectiontest;
import java.sql.*;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import static android.R.attr.name;
import static com.example.vishal.connectiontest.DemoClass.main;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button B1 = (Button)findViewById(R.id.button);
final TextView e1 = (TextView) findViewById(R.id.HelloWorld);
B1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
String result = main();
e1.setText(result.toString());
}
catch(java.lang.Exception e){
System.out.println("Exception");
}
}
});
}
}
class DemoClass
{
public static String main()throws Exception
{
String url = "jdbc:mysql://125.10.10.214/demo" ;
String uname = "root";
String pass = "";
String ip = "";
String query = "Select UserName from user_info where Id = '90000515'";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, uname,pass);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
rs.next();
String name = rs.getString("UserName");
return (name);
}
}`
Easiest way of integrating Database to your Android Application is using Firebase.
It's really easy to use and other than Database, it has File Storage Services, Cloud Messaging, Analytics and many more.
I would recommend use of firebase database.
Here have a look at it's Documentation:
https://firebase.google.com/docs/database/
First of all I'd like to say that it is a project for a course in my university and at the same time my first app for Android which is more complicated that a calculator, so I understand that I could have done some unforgivable mistakes, but my priority is that the code should work. It can be insecure and not considering some cases, but as long as those cases won't appear, it will do.
My app is intended to be running on Android and first of all there should appear login screen which takes login and password, makes the hash of the password and contacts a database on a web server to compare hashes. I was told to use a free database db4free.net.
I created a class Serwer, which would be responsible exclusively for contacting the database. As far as I understood from tutorials and stackoverflow questions and answers, the connection should consist of:
Loading the driver,
Registering it in the DriverManager class,
Using getConnection method to open the connection, passing the credentials,
Preparing and executing SQL query,
Fetching a result set.
I also learned that I should download a mysql-connector-java-5.1.38-bin.jar file. As some threads on stackoverflow suggested, I copied it into main directory of the project (I have to copy the workspace and take to professor's computer when I finish), added it to Libraries tab of properties as an external library. Now when I run the project on my smartphone, I get a java.lang.ClassNotFoundException: Didn't find class "com.mysql.jdbc.Driver" error. I also tried to check the library in Order and Export tab - then it even doesn't compile, returning Conversion to Dalvik format failed with error 1.
I've tried many scenarios in other stackoverflow threads, such as cleaning the project in many configurations, changing the order of build path, etc. I suspect that I've made a simple, stupid mistake that I do not see and I hope you will recognize it.
Here is my Serwer class:
package com.planer.serwer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Driver;
import com.planer.MainActivity;
import com.example.planer.R;
import com.planer.pracownik.Pracownik;
public class Serwer {
private Connection conn = null;
private static Driver driver;
private static int status;
private MainActivity parentActivity;
private final String user = parentActivity.getResources().getString(R.string.db_login);
private final String pass = parentActivity.getResources().getString(R.string.db_pass);
private final String url= "jdbc:mysql://db4free.net:3306/kalendarzplaner";
public static final int STATUS_GOOD = 0;
public static final int STATUS_NO_CONNECTION = 1;
public static final int STATUS_NOT_AUTHENTICATED = 2;
public static final int STATUS_SQL_EXCEPTION = 4;
public static final int STATUS_NO_DRIVER = 8;
public Serwer(MainActivity parentActivity){
status = STATUS_NO_CONNECTION;
try {
driver = new com.mysql.jdbc.Driver();
} catch (Exception ex) {
status |= STATUS_NO_DRIVER;
} catch (NoClassDefFoundError e){
status |= STATUS_NO_DRIVER;
}
this.parentActivity = parentActivity;
}
public Pracownik authorize(String login, String passhash){
Pracownik pracownik = new Pracownik("","",false,status);
status |= this.polacz();
if(status != Serwer.STATUS_GOOD) {
pracownik.status |= status;
return pracownik;
}
Statement statement = null;
ResultSet resultSet = null;
String query = "select passhash, imie_nazwisko, czy_kierownik from auth where login='" + login + "';";
try {
statement = conn.prepareStatement(query);
resultSet = statement.executeQuery(query);
resultSet.first();
if(resultSet.getString("passhash").toString().compareTo(passhash)!= 0){
status |= Serwer.STATUS_NOT_AUTHENTICATED;
pracownik.status |= status;
return pracownik;
}
pracownik.login = login;
pracownik.imie_nazwisko = resultSet.getString("imie_nazwisko");
pracownik.czy_kierownik = resultSet.getBoolean("czy_kierownik");
} catch (SQLException ex) {
pracownik.status |= Pracownik.STATUS_SQL_EXCEPTION;
}
return pracownik;
}
public int polacz() {
int done = STATUS_NO_CONNECTION;
if((status & STATUS_NO_DRIVER) != 0)
return done;
// Connection
try {
DriverManager.registerDriver(driver);
conn = DriverManager.getConnection(url, user, pass);
done = Serwer.STATUS_GOOD;
} catch (java.sql.SQLException ex) {
done |= Serwer.STATUS_SQL_EXCEPTION;
System.out.println("SQLException: " + ex.getMessage());
}
return done;
}
}
As I said, the status of the result of authorise method is 9, which is expected when the driver is not loaded. I also append my workspace contents.
First, I want to start by suggesting that you tried out Android Studio. It's the new more modern IDE developed specifically for the purpose of Android Development.
Secondly, contacting a database on Android is a lot different than for example contacting a DB from Java/C# in an Desktop application.
To contact an online MySQL Database you need a RESTful service (written in PHP for example) that gets the data from the database and sends it over to the application. The service is like a communication point between the App and the Database. The service usually sends data to the application in a human-unfriendly format like JSON, so your app needs to parse that and then display it.