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!
Related
I've made a SQL Server and managed to form a database. Implemented everything in my Android Studio app and opened the app on my phone.
When I access the database from the same WiFi network where the database is formed, everything works, but when I access the database from another WiFi network I get the exception:
java.sql.SQLException: Network error IOException: Host unreachable
Can you make the server accessible from every other network apart from the network that the database is connected to? Or do I have to do something else to make it accessible from everywhere?
Things I've already done:
Every SQL services are up and running.
Shared Memory, Named Pipes and TCP/IP are enabled.
Remote server connections is Allowed on my database.
New account is created (I don't use the sa account).
I've made an exception in the firewall for the port (1433).
I will add the code from my app if that helps in any way.
import android.Manifest;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.Window;
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 {
TextView moreGames;
String b;
private static String ip = "xxx.xxx.x.x";
private static String port = "1433";
private static String Classes = "net.sourceforge.jtds.jdbc.Driver";
private static String database = "xxxx";
private static String username = "xxxxxx";
private static String password = "xxxx";
private static String url = "jdbc:jtds:sqlserver://" + ip + ":" + port + "/" + database;
private Connection connection = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
moreGames = findViewById(R.id.moreGames);
ActivityCompat.requestPermissions(this, new String[]{(Manifest.permission.INTERNET)}, PackageManager.PERMISSION_GRANTED);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
Class.forName(Classes);
connection = DriverManager.getConnection(url, username, password);
moreGames.setText(R.string.NewGame);
} catch (ClassNotFoundException e){
e.printStackTrace();
Toast.makeText(this, "Error somewhere.", Toast.LENGTH_SHORT).show();
} catch (SQLException e){
b = String.valueOf(e);
Toast.makeText(this, b, Toast.LENGTH_LONG).show();
}
I've looked at many tutorials on this yet none of them seem to work so no idea whether it's the server, client or potentially something on my network that's stopping it I don't know, so I come here for help.
Just for reference this is the tutorial that this is mainly based on: https://socket.io/blog/native-socket-io-and-android/
So this is my server. All it's supposed to do at the moment is detect when a user connects and then detect users sending messages and send them back to all the clients.
index.js
const express = require("express");
const app = express();
const path = require("path");
const server = require("http").createServer(app);
const io = require("socket.io")(server);
server.listen(3000, () => {
console.log("Server listening at 3000");
});
app.use(express.static(path.join(__dirname, "public")));
io.on("connection", (socket) => {
console.log("User connected");
socket.on("new message", (data) => {
console.log("New message" + data)
socket.emit("new message", {
message: data
});
})
});
My Android client is made up of 3 classes. But to try and keep this shorter I'll only include 2 of them as if the problem can be found in these it's fixable in the 3rd.
This is what's launched at the start and simply pressing the button brings you to the main 'chat' part, but on clicking the button the server should log the connection but nothing appears in the console. So I can only assume the socket connection isn't working for some reason. Also you can ignore the nickname, I've not implemented that yet, been trying to get the main part working first.
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import io.socket.client.Socket;
public class MainActivity extends AppCompatActivity {
private EditText nickname;
private Button enterChat;
private Socket mSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nickname = findViewById(R.id.nickname);
enterChat = findViewById(R.id.enterChat);
ChatApplication app = (ChatApplication) getApplication();
mSocket = app.getSocket();
mSocket.connect();
enterChat.setOnClickListener(v -> {
mSocket.emit("connection");
Intent i = new Intent(MainActivity.this, ChatActivity.class);
i.putExtra("name", nickname.getText().toString());
startActivity(i);
});
}
}
This is just to be able to get the Socket from any other activity.
ChatApplication.java
import android.app.Application;
import java.net.URISyntaxException;
import io.socket.client.IO;
import io.socket.client.Socket;
public class ChatApplication extends Application {
private Socket mSocket;
{
try {
//My IPv4 address here
mSocket = IO.socket("http://xxx.xxx.x.xxx:3000");
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public Socket getSocket() {
return mSocket;
}
}
Any help appreciated :)
Found the problem, I need to add this to the AndroidManifest.xml
<application
...
android:usesCleartextTraffic="true"
...
</application>
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.
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