am successfully finished login form in android using mysql connection via jdbc in java...its successfully worked in my localhost...but development site its not worked...the following error is displyed.
java.sql.SQLException: Unable to connect to any hosts due to exception: java.net.SocketException: java.net.ConnectException: Connection timed out: connect
** BEGIN NESTED EXCEPTION **
java.net.SocketException
MESSAGE: java.net.ConnectException: Connection timed out: connect
STACKTRACE:
java.net.SocketException: java.net.ConnectException: Connection timed out: connect
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:143)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:225)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:1805)
at com.mysql.jdbc.Connection.<init>(Connection.java:452)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:411)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.retrieve.retrieve.main(retrieve.java:15)
** END NESTED EXCEPTION **
at com.mysql.jdbc.Connection.createNewIO(Connection.java:1875)
at com.mysql.jdbc.Connection.<init>(Connection.java:452)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:411)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.retrieve.retrieve.main(retrieve.java:15)
why dis error is occurred.give me some solutions.
if am running localhost means my sql query is
package com.example.login;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class LoginLayoutActivity extends Activity {
EditText username,password;
TextView error;
Button ok;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
username=(EditText)findViewById(R.id.et_un);
password=(EditText)findViewById(R.id.et_pw);
error=(TextView)findViewById(R.id.tv_error);
ok=(Button)findViewById(R.id.btn_login);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Editable user = username.getText();
Editable pass = password.getText();
try {
**Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/people", "root", "");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT password FROM customers where login='"+user+"'");**
if(rs.next())
{
String dbpass = rs.getString(1);
if(dbpass.equals(pass)){
error.setText("Correct Username or Password");
}
else
{
error.setText("Sorry!! Incorrect Username or Password");
}
}
}
catch (SQLException e) {
username.setText(e.toString());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
if am running development site means my query is:
package com.example.login;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class LoginLayoutActivity extends Activity {
EditText username,password;
TextView error;
Button ok;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
username=(EditText)findViewById(R.id.et_un);
password=(EditText)findViewById(R.id.et_pw);
error=(TextView)findViewById(R.id.tv_error);
ok=(Button)findViewById(R.id.btn_login);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Editable user = username.getText();
Editable pass = password.getText();
try {
**Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://dev.xxxxx.com/xxx", "xxxx", "xxxx");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT password FROM customers where login='"+user+"'");**
if(rs.next())
{
String dbpass = rs.getString(1);
if(dbpass.equals(pass)){
error.setText("Correct Username or Password");
}
else
{
error.setText("Sorry!! Incorrect Username or Password");
}
}
}
catch (SQLException e) {
username.setText(e.toString());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
dis development site username,password,database name and url all r correct only...then why dis error is occured....give me solutions...
If you are trying to connect your mysql in the localhost from an android application, it may not get communication, refer this.
This exception seems like the mysql doesn't have public access.
Make your mysql available in a remote system and give the remote system's ip. Let 192.168.1.102 be its ip, then change this statement as jdbc:mysql://192.168.1.102:3306/people.
You have to modify the mysql configuration file. It may be /etc/mysql/my.cnf (in linux) or \xampp\mysql\bin\my.ini (depends on mysql refer more).
By default it contains bind-address = 127.0.0.1, change it as bind-address = 0.0.0.0. When this change is made, then the mysql is available publicaly i.e. it can be accessed remotely. Now your application can access this mysql.
Sounds like a network problem. Verify if you can access the Database host and port from the device you're making the connection, and if the DBMS is up and running.
The key question is whether or not the mobile device is on the network when you try to connect to the database. If you're on the network, you'll need to talk to the MySQL database administrator to see if you have permission to access that database. I'm guessing that you do not, because you're trying to log in as root without a password. No administrator in their right mind would allow you to do that.
If you're the administrator, please call your therapist of pharmacist.
If the mobile device is not on the network, I'm guessing that the database is behind a firewall of some kind. At best you'll have to talk to some administrator to get firewall rules set up to allow access from the mobile device. Those usually require some information about the device. Firewall rules won't be practical if you intend to release an app for several users.
A better solution would be to set up a proxy that would authenticate incoming mobile devices and communicate with the database on their behalf.
I would not have a mobile device connecting directly to a database, especially the way you're trying to do it.
Who else knows about what you're trying to do? It looks to me like you're trying to connect to a database, but that fact isn't widely known. Who else knows about your project?
If you use en emulator use a special IP to your localhost.
10.0.2.2
jdbc:mysql://10.0.2.2:3306/people
Related
I'm trying to connect to a sql database with java but this isn't really working out. normally people say they have a user and password but I never created anything like that. I downloaded sqlite studio and you can pretty much just make a database without having to create some kind of account but when i'm trying to connect it gives me an error that it can't connect com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure.
How do I resolve this issue? This is the code I have right now:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class MyJDBC {
public static void main(String[] args) {
try {
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/JDBC-video");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from people");
while (resultSet.next()) {
System.out.println(resultSet.getString("firstname"));
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
I'm trying to connect from SSMS(SQL Server Management Studio) to Eclipse(Java), but I keep getting this error message:
com.microsoft.sqlserver.jdbc.SQLServerException: The connection to the host localhost, named instance sqlexpress failed. Error: "java.net.SocketTimeoutException: Receive timed out". Verify the server and instance names and check that no firewall is blocking UDP traffic to port 1434. For SQL Server 2005 or later, verify that the SQL Server Browser Service is running on the host.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:234)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.getInstancePort(SQLServerConnection.java:6132)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.primaryPermissionCheck(SQLServerConnection.java:2609)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:2346)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:2213)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:1276)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:861)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at net.codejava.sql.JavaConnect2SQL.main(JavaConnect2SQL.java:16)
The code I do have is:
import java.sql.DriverManager;
import java.sql.SQLException;
//import com.sun.jdi.connect.spi.Connection;
public class JavaConnect2SQL {
public static void main(String[] args) {
// TODO Auto-generated method stub
String url = "jdbc:sqlserver://localhost\\SQLEXPRESS;databaseName=students"; // This is where I think the error is
String user = "sa";
String password = "123";
try {
java.sql.Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("Succesfully connected to Microsoft SQL Server");
}catch (SQLException e) {
System.out.println("Oops! There was an error: ");
e.printStackTrace();
}
}
}
I think the problem is in the connection URL, but I don't know the host name/instance name. If you can tell me how to get my host name/instance name, that would be appreciated. But if the problem is something else, please tell me!
Edit: I have changed the code, and I'm now getting a different. Here is the new code:
package net.codejava.sql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JavaConnect2SQL {
public static void main(String[] args) {
// Create a variable for the connection string.
String url = " jdbc:sqlserver://LAPTOP-5697KK36:1433;databaseName=students";
String user= "sa";
String password = "123";
try {
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("Connection succesful!");
}
// Handle any errors that may have occurred.
catch (SQLException e) {
System.out.println("Here is your error message: ");
e.printStackTrace();
}
}
}
The new error message is this:
java.sql.SQLException: No suitable driver found for jdbc:sqlserver://LAPTOP-5697KK36:1433;databaseName=students
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at net.codejava.sql.JavaConnect2SQL.main(JavaConnect2SQL.java:40)
I think the problem is that I installed the wrong version of JDBC Driver. My JRE version is 12.0.1. What is the correct JDBC Driver to install.
You can check in SQL server configuration manager and Microsoft SQL server management studio. The state must be running in server configuration manager and you can try to connect your database in Microsoft SQL server management with your password.
if you connect successfully then there is another problem but it looks like the database is stopped.
Hi I'm new to android and Im
Trying to get my android app to connect to a my server that is running on my local computer. Im just trying to get the app to send a simple string message to the server first but keep getting an error. From the print out statements i can see that the app terminates as soon as it hits the line with the try in it so i believe there is an issue with creating the client connection. I have also enable Internet,ACCESS_NETWORK_STATE, ACCESS_WIFI_STATE,READ_EXTERNAL_STORAGE,WRITE_EXTERNAL_STORAGE permissions
i tried changing the localhost to InetAddress.getLocalHost() but still wouldn't work
heres my code :
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.StringBuilderPrinter;
import android.view.View;
import android.widget.Button;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import static java.net.InetAddress.getLocalHost;
public class MainActivity extends AppCompatActivity{
private Button cam;
private Socket client;
DataOutputStream os;
private String IP = "localhost";
private static final String TAG = "testing";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
setContentView(R.layout.activity_main);
cam = (Button) findViewById(R.id.Button_camera);
cam.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "trying to connect to server");
try {
client = new Socket("My IP address entered", 8080);
Log.v(TAG, "client socket initalised");
String hey = "hey";
os = new DataOutputStream(client.getOutputStream());
Log.v(TAG, "outptu stream created");
os.flush();
Log.v(TAG, "flush");
os.writeBytes(hey);
Log.v(TAG, "written to server");
os.close();
} catch (UnknownHostException e) {
Log.v(TAG, "Unknown error");
Log.v(TAG, e.toString());
} catch (IOException e) {
Log.v(TAG, "IO exception u numpty");
Log.v(TAG, e.toString());
}
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
}
});
}
}
my code prints out the statement trying to connect to server but doesn't reach any of the other print out statements and my server is still not receiving anything
connect failed: ETIMEDOUT (Connection timed out)
ACTION_DOWN before UnsetPressedState. invoking mUnsetPressedState.run()
I/Choreographer: Skipped 3792 frames! The application may be doing too much work on its main thread.
I believe this is definitely just an issue with your IP, you are obviously giving ti the wrong ip address because everything else is fine. I would recommend either accessing the terminal and using the ifconfig command to find your ip or access your network settings, if your using a mac like I am select network , advance options , select tcp/ip tab and use ipv4 address as the ip address. If that doesn't work try using a different port or checking your firewall setting on your local computer. Hope that helps.
Localhost is the phone itself, not your computer. If on a simulator, localhost is the simulator, not your computer- the simulator doesn't know its a simulator, it has its own IP address. Fix the IP you're using.
by clicking a button, i want to execute a select query to show some results,i used the Internet permission and the AsyncTask and the address ip of my PC to perform this call but it didn t work for me,Also the Log doesn't show me Anything to figure out the issue,this is the code:
in Manifest file:
<uses-permission android:name="android.permission.INTERNET"/>
Android programm:
package com.ammach.oraclecon;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
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 {
class Task extends AsyncTask<Void,Void,String>{
#Override
protected String doInBackground(Void... params) {
String param="mal9a walou";
String driver="oracle.jdbc.driver.OracleDriver";
String bd="ORCL";
String user="SYSTEM";
String passwd="SYSTEM";
String port="1521";
String ip="192.168.1.7";
String url="jdbc:oracle:thin:#"+ip+":"+port+":"+bd;
Connection con=null;
try {
Class.forName(driver);
con = DriverManager.getConnection(url, user, passwd);
Log.e("coooon", "coooon");
Statement st=con.createStatement();
Log.e("Statement", "Statement");
ResultSet resultSet = st.executeQuery("select * from auteur");
Log.e("ResultSet", "ResultSet");
Log.e("con", "You made it, take control your database now!");
if(resultSet.next()){
param=resultSet.getString("nom");
Log.e("dkhal", "rah dkhal");
}else{
Log.e("walou", "walou");
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
return param;
}
#Override
protected void onPostExecute(String param) {
super.onPostExecute(param);
textView.setText(param);
Toast.makeText(MainActivity.this, "finished", Toast.LENGTH_SHORT).show();
}
}
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView= (TextView) findViewById(R.id.txt);
}
public void fetchOracle(View view) {
new Task().execute();
Toast.makeText(MainActivity.this, "starting", Toast.LENGTH_SHORT).show();
}
}
i Also run the same procedure in a simple java project(void main) in Netbeans, and it works perfectly,i tried so many times the Android application but i failed ,could someone help me to solve this issue.
this is the java programm:
String param = "nothing";
String driver = "oracle.jdbc.driver.OracleDriver";
String bd = "ORCL";
String user = "SYSTEM";
String passwd = "SYSTEM";
String port = "1521";
String ip = "localhost";
String url = "jdbc:oracle:thin:#" + ip + ":" + port + ":" + bd;
Connection con = null;
try {
Class.forName(driver);
con = DriverManager.getConnection(url, user, passwd);
Statement st = con.createStatement();
ResultSet resultSet = st.executeQuery("select * from auteur");
if (resultSet.next()) {
param = resultSet.getString("nom");
} else {
System.out.println("no result");
}
System.out.println("nom: "+param);
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
Your catch clause with the only statement e.printStackTrace(); makes the trick. It just swallows the exception and you, of course, unable to see it. It is much better to use the Log class to report the caught exception. Insert there something like Log.e("tag", e.toString()); and you'll see the problem.
Next you should always close all the resources you have used. In your case it's the Connection, the Statement and the ResultSet. The correct place to close them is in your (missed) finally clause.
But anyway, if you want to work with Oracle from Android device then you should ensure the network 192.168.1.* is reachable from your device and the address (192.168.1.7) at least can be pinged successfully (from your device). Have you managed to somehow test the connection? And there can be much more reasons to get an exception (which is silently swallowed in your code), it means the first thing you should do is to change your code and to log exception properly. Next it can be a missing JDBC driver library, it can be a network configuration problem which makes the database unreachable (most probable), it can be the problem on the side of the Oracle if you have no permission to read from "auteur", etc.
I am a beginner to Android Eclipse. However, I have a project to do an Android application. I am unable to connect to the Android emulator using the MySQL connector to create a login page. Am I missing an important file?
Loginpage
package com.example.logininterface;
import com.example.logininterface.R.menu;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText txtUserName;
EditText txtPassword;
Button btnLogin;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtUserName = (EditText)this.findViewById(R.id.txtUname);
txtPassword = (EditText)this.findViewById(R.id.txtPwd);
btnLogin = (Button)this.findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if ((txtUserName.getText().toString()).equals(txtPassword.getText().toString())) {
Toast.makeText(MainActivity.this, "Login Successful", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(MainActivity.this, "Invalid Login", Toast.LENGTH_LONG).show();
}
}
});
}
}
MySQLConn
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Main {
public static void main(String[] args) throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mobiledb", "teddy", "password");
PreparedStatement statement = con.prepareStatement("select * from androidlogin");
ResultSet result = statement.executeQuery();
while(result.next())
{
System.out.println(result.getString(1) + "" + result.getString(2));
}
}
}
I don't think accessing any database directly from the Android layer is a good idea. It would be better if you could pass required parameters to a server page (PHP, JSP, etc.) and database connections could be done from server pages.
Coming to your question, localhost means Android in this case, so it will be looking for a MySQL database inside your emulator. Instead, you need to use your computer's IP address. Go to a terminal and type ipconfig or ifconfig if you are on *nix/Macintosh machine to get the IP address.
I suggest to use JSON with PHP to connect to the MySQL database. It is just an opinion.
It is better that you use JSON to communicate with the PHP script and within the PHP script to communicate with your localhost MySQL database. And you may try this to connect to your PHP script.
Example:
public class Login {
...
private static final String LOGIN_URL = "http://XXX.XXX.X.XX/Example/login.php";
...
// Invoke by Intent activity by Login class
class AttemptLogin extends AsyncTask<String, String, Integer> {
...
protected void onPreExecute() {
....
}
protected Integer doInBackground() {
....
// Getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
params);
....
}
protected void onPostExecute() {
....
}
}
The XXX.XXX.X.XX is the local IP address of your computer, which means when your mobile is connected on the same network as your computer, the IP address is the computer local IP address. Do not put in localhost. It won't work.
Instead of using "Localhost" use 10.0.2.2. Hope it helps!