Reputation: 2793
I am using Eclipse and Android Emulator. I can access to 10.0.2.2 in emulator browser. But in my app, this code not run :
Connection con = DriverManager.getConnection("jdbc:mysql://10.0.2.2/stu", "user", "pass");
Anybody has some idea?
The error is :
com.mysql.jdbc.CommunicationsException
I am confused that why i have access to phpMyAdmin in emulator's browser, but not inside the code! :(
Note that full code is this :
public class LearningActivity extends Activity {
private static final String url = "jdbc:mysql://10.0.2.2/stu";
private static final String user = "root";
private static final String pass = "11111";
private Button button;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button)this.findViewById(R.id.button1);
tv = (TextView)this.findViewById(R.id.textView1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Connect();
}
});
}
private class Connect extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, pass);
// System.out.println("Database connection success");
String result = "Database connection success\n";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from users");
ResultSetMetaData rsmd = rs.getMetaData();
while(rs.next()) {
result += rsmd.getColumnName(1) + ": " + rs.getInt(1) + "\n";
result += rsmd.getColumnName(2) + ": " + rs.getString(2) + "\n";
result += rsmd.getColumnName(3) + ": " + rs.getString(3) + "\n";
}
tv.setText(result);
}
catch(Exception e) {
e.printStackTrace();
tv.setText(e.toString());
}
return response;
}
@Override
protected void onPostExecute(String result) {
tv.setText(result);
}
}
public void Connect() {
Connect task = new Connect();
task.execute();
}
}
Upvotes: 0
Views: 481
Reputation: 2793
Damn it! I missed to add Internet permission to manifest! :( I add that and problem solved.
The browser of phone(android emulator) has this permission and it could connect to network, but my application haven't that permission. So I should add only this line to manifest.xml:
<manifest ... >
.
.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
.
.
</manifest>
Upvotes: 1
Reputation: 204
you didnt change the ip...... 1>get ur machines ip 2>then Connection con = DriverManager.getConnection("jdbc:mysql://"your_ip"/stu", "user", "pass");
Upvotes: 0
Reputation: 13844
your mysql database should have access from remote system.
You should grant permission for remote access something like this
GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.1.%'
IDENTIFIED BY PASSWORD 'password'
WITH GRANT OPTION;
FLUSH PRIVILEGES;
Upvotes: 1