ANDROID DATABASE - Network error IOException [duplicate] - java

This question already has answers here:
Android ECONNREFUSED (Connection refused)
(2 answers)
Closed 5 years ago.
Hello I am beginner to android.I want to make a database connection to mssql server in my pc. I found example on the net.
I think I have something wrong in connection ip or port. I guess syntax is wrong.
I get this log :
Network error IOException: failed to connect to /127.0.0.1 (port 1433) from /:: (port 55062): connect failed: ECONNREFUSED (Connection refused)
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionClass {
String ip = "127.0.0.1:1433";
String classs = "net.sourceforge.jtds.jdbc.Driver";
String db = "DBAndroid1";
String un = "TestUser";
String password = "123";
Here is my MainActivity.java.
public class MainActivity extends AppCompatActivity {
ConnectionClass connectionClass;
EditText edtuserid, edtpass;
Button btnlogin;
ProgressBar pbbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectionClass = new ConnectionClass();
edtuserid = (EditText) findViewById(R.id.et_username);
edtpass = (EditText) findViewById(R.id.et_password);
btnlogin = (Button) findViewById(R.id.btn_Login);
pbbar = (ProgressBar) findViewById(R.id.pbbar);
pbbar.setVisibility(View.GONE);
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DoLogin doLogin = new DoLogin();
doLogin.execute("");
}
});
}
public class DoLogin extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSuccess = false;
String userid = edtuserid.getText().toString();
String password = edtpass.getText().toString();
#Override
protected void onPreExecute() {
pbbar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r) {
pbbar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this,r,Toast.LENGTH_SHORT).show();
if(isSuccess) {
Toast.makeText(MainActivity.this,r,Toast.LENGTH_SHORT).show();
}
}
#Override
protected String doInBackground(String... params) {
if(userid.trim().equals("")|| password.trim().equals(""))
z = "Please enter User Id and Password";
else
{
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "select password from User";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
z = "Login successfull";
isSuccess=true;
}
else
{
z = "Invalid Credentials";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
z = "Exceptions burda mi ";
}
}
return z;
}
}
}
#SuppressLint("NewApi")
public Connection CONN() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL = null;
try {
Class.forName(classs).newInstance();
ConnURL = "jdbc:jtds:sqlserver://" + ip + ";"
+ "databaseName=" + db + ";user=" + un + ";password="
+ password + ";";
conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
Log.e("ERRO0", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO1", e.getMessage());
} catch (Exception e) {
Log.e("ERRO2", e.getMessage());
}
return conn;
}
}
I hope you can help. Thank you.

Are you doing this from an emulator or your device? On your device make sure you are on the wi-fi and not using your cellular data. It needs to be on the same network. Your IP should be 10.0.2.2 not localhost (aka 127.0.0.1) as Android emulator is on a VM. As local host for the emulator is referring to the emulator itself not the actual localhost.

Related

onPostExecute runs before doInBackground method is finished

So,I simply made a login screen where the data comes from an external server.
All of that happens in the background method.it all works correctly except for onPost and onPre methods.
I don't think they are doing their job.
while the onBackground method is running i would like to:
1.Show a message if the data is right or wrong.
2.Show a custom progress dialog i made while doinbackground is running.
But neither of them work,any ideas?
Here is my code!
public class DoLogin extends AsyncTask<String,String,String>
{
String message = "";
Boolean isSuccess = false;
String userid = dename.getText().toString();
String password = pass.getText().toString();
#Override
protected void onPreExecute() {
progressDialog.showProgress(SignInAr.this,"Loading...",false);
}
#Override
protected String doInBackground(String... params) {
new Thread(new Runnable() {
#Override
public void run() {
if(userid.trim().equals("")|| password.trim().equals(""))
message = "Please enter Username and Password";
else
{
try {
Connection con = connectionClass.CONN();
if (con == null) {
message = "Error in connection with SQL server please contact the administrator";
isSuccess = false;
} else {
String query = "SELECT * FROM CustomerData where CustomerMobile='" + userid + "' and CustomerPassword='" + password + "'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
String id = rs.getString("CustomerID");
String mob = rs.getString("CustomerMobile");
String lng = getIntent().getStringExtra("lng");
String lat = getIntent().getStringExtra("lat");
message = "Welcome " + userid;
Intent intent = new Intent(SignInAr.this,agzakhana_mainAr.class);
intent.putExtra("lat",lat);
intent.putExtra("lng",lng);
intent.putExtra("nameid",id);
String getname = rs.getString("CustomerName");
intent.putExtra("nameofcus",getname);
intent.putExtra("mob",mob);
startActivity(intent);
finish();
isSuccess=true;
}
else
{
message = "Wrong info";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
message = "Exceptions"+ex;
}
}
}
}).start();
return message;
}
#Override
protected void onPostExecute(String r) {
progressDialog.hideProgress();
System.out.println("Message is: "+ r + "and isSuccess = "+ isSuccess);
if(!isSuccess) {
Toast.makeText(SignInAr.this,r,Toast.LENGTH_LONG).show();
}
}
}
Here is how i call the asynctask:
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DoLogin doLogin = new DoLogin();
doLogin.execute();
}
});
You return value before thread run. Simple to fix it you shoukd remove Thread and Runnable in method doInBackground because in AsyncTask it already make doInBackground run in Background Thread.

Cannot get Android Studio to connect to a MySQL database

I cannot get my Android app (basic just tutorial style app) to connect to my MySQL database. I can get a basic IntelliJ IDEA program with essentially the same code to connect and display a list of names, but my android app just throws com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure.
When I look at the server logs in MySQL Workbench, the result is Access denied for user '(myname)'#'localhost' (using password: NO).
The weird thing is that when I check the log after I connect using my java program on IntelliJ, the logs show the same thing, several reconnect attempts, then Aborted connection 458 to db: 'mydb' user: 'root' host: 'localhost' (Got an error reading communication packets), then the same Access denied... message, but the names DO print out to the terminal in the IntelliJ app.
I created a user of my username on my Mac account I am using and nothing really matters. Same message. Any idea where I should go?
Here is the Android Studio Code:
package com.addydevelopments.sqlllllll;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class MainActivity extends AppCompatActivity {
TextView text, errorText;
Button show;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView2);
errorText = (TextView) findViewById(R.id.textView3);
show = (Button) findViewById(R.id.button);
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Task().execute();
}
});
}
public class Task extends AsyncTask<Void, Void, Void> {
String records="", error="";
String url = "jdbc:mysql://127.0.0.1:3306/mydb?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT";
String user = "root";
String password = "student";
#Override
protected Void doInBackground(Void... voids) {
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try{
Connection conn = DriverManager.getConnection(url, user, password);
Statement stat = conn.createStatement();
String sql = "SELECT * from mydb.fruit";
ResultSet rs = stat.executeQuery(sql);
while(rs.next()){
records += rs.getString("name") + "/n";
}
}
catch(Exception e){
error = e.toString();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
text.setText(records);
if(error != ""){
errorText.setText(error);
}
super.onPostExecute(aVoid);
}
}
}
And here is the IntelliJ IDEA version:
package com.addydevelopments.Dahls;
import java.sql.*;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://127.0.0.1:3306/mydb?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=CONVERT_TO_NULL&serverTimezone=GMT";
String user = "root";
String password = "student";
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
Connection myConn = DriverManager.getConnection(url, user, password);
Statement myState = myConn.createStatement();
String sql = "SELECT * from mydb.fruit";
ResultSet rs = myState.executeQuery(sql);
while (rs.next()){
System.out.println(rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Your code connects to a local sql server. There is not one running on your Android phone whilst I assume there is one running on your computer. You can use httpurlconnection to talk to your external web server and use php/sql on the server side. Just a note if the server doesn’t have a valid ssl certificate it may not work.
https://developer.android.com/reference/java/net/HttpURLConnection

android studio claims this class is abstract, how and why is this class abstract?

My class dose not have a abstract keyword before the class keyword in the class declaration, but when i tried to instantiate the class on an activity it tells me class is abstract; can not be instantiated.
This makes no sense because it doesn't look like an abstract class to me. please help me figer out what I'm doing wrong and how I can fix it
The error is at new ConnectionClass()
Here is the class ConnectionClass
final public class ConnectionClass {
String ip = "";
String classs = "net.sourceforge.jtds.jdbc.Driver";
String db = "tmseprd";
String un = "";
String password = "";
#SuppressLint("NewApi")
public Connection CONN() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL = null;
try {
Class.forName(classs);
ConnURL = "jdbc:jtds:sqlserver://" + ip + ";"
+ "databaseName=" + db + ";user=" + un + ";password="
+ password + ";";
conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
Log.e("ERRO", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO", e.getMessage());
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
}
return conn;
}
}
Here is the activity activity_connection
public class ConnectionActivity extends AppCompatActivity {
ConnectionClass connectionClass;
EditText edtuserid,edtpass;
Button btnlogin;
ProgressBar pbbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connection);
connectionClass = new ConnectionClass();
edtuserid = (EditText) findViewById(R.id.edtuserid);
edtpass = (EditText) findViewById(R.id.edtpass);
btnlogin = (Button) findViewById(R.id.btnlogin);
pbbar = (ProgressBar) findViewById(R.id.pbbar);
pbbar.setVisibility(View.GONE);
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DoLogin doLogin = new DoLogin();
doLogin.execute("");
}
});
}
I am assuming you are getting the error at new ConnectionClass().
There seems no need to have a final class. Add a constructor just to be sure also. You might have meant that you needed a static class with static methods.
Use this instead:
public class ConnectionClass {
String ip = "";
String classs = "net.sourceforge.jtds.jdbc.Driver";
String db = "tmseprd";
String un = "";
String password = "";
public ConnectionClass(){}
#SuppressLint("NewApi")
public Connection CONN() {
....
}
}

Error while connecting android app to remote mySQL database

I made a very simple app just to stabilished a connection with my SQL database on Raspberry Pi with JDBC but when I tried to connect, the app give me a error, any suggest?
code:
public class MainActivity extends AppCompatActivity {
private static final String url = "jdbc:mysql://192.168.1.65:3306/myDB";
private static final String user = "user";
private static final String pass = "userpass";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void connect(View v){
TextView tv = (TextView) findViewById(R.id.textView);
try{
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url,user,pass);
if(con!=null){
tv.setText("Connection Successfully");
}else
tv.setText("FAAAAIL ");
}catch (Exception e){
e.printStackTrace();
tv.setText(e.toString());
}
}
}

How can I find the network IP address automatic and connect to it?

I'm using Android Studio 1.3
Today I'm giving a manual IP address in a string.
On my laptop I'm running a web server.
On my Android Studio I'm running a client.
The problem is that I'm currently connecting to the web server manually using the hard-coded IP address.
I have a router in my PC room and I connect to the router network with my laptop.
For example, my laptop IP address is 10.0.0.3 and if I log in to my router settings I can see the laptop connected.
The problem is sometimes if my PC shut down for some reason it might be that next time it will be connected to my router with a different IP address.
In my Java side in the Android Studio I did:
package com.test.webservertest;
public class MainActivity extends ActionBarActivity
{
private static final int MY_DATA_CHECK_CODE = 0;
public static MainActivity currentActivity;
TextToSpeech mTts;
private String targetURL;
private String urlParameters;
private Button btnClick;
private String clicking = "clicked";
private String[] ipaddresses = new String[]{
"http://10.0.0.3:8098/?cmd=nothing"};
private String iptouse = "";
private TextView text;
private boolean connectedtoipsuccess = false;
private int counter = 0;
private NotificationCompat.Builder mbuilder;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
currentActivity = this;
initTTS();
}
Then in the addListenerOnButton:
public void addListenerOnButton()
{
btnClick = (Button) findViewById(R.id.checkipbutton);
btnClick.setOnClickListener(new OnClickListener()
{
byte[] response = null;
#Override
public void onClick(View arg0)
{
text = (TextView) findViewById(R.id.textView2);
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
for (int i = 0; i < ipaddresses.length; i++)
{
counter = i;
try
{
response = Get(ipaddresses[i]);
}
catch (Exception e)
{
String err = e.toString();
}
if (response!=null)
{
try
{
final String a = new String(response, "UTF-8");
text.post(new Runnable()
{
#Override
public void run()
{
text.setText(a + " Oמ " + ipaddresses[counter]);
String successconnected = null;
successconnected = "Successfully connected";
textforthespeacch = successconnected;
MainActivity.currentActivity.initTTS();
}
});
iptouse = ipaddresses[i].substring(0,ipaddresses[i].lastIndexOf("=")+1);
connectedtoipsuccess = true;
Logger.getLogger("MainActivity(inside thread)").info(a);
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
Logger.getLogger("MainActivity(inside thread)").info("encoding exception");
}
Logger.getLogger("MainActivity(inside thread)").info("test1");
break;
}
else
{
}
}
counter = 0;
if (response == null)
{
text.post(new Runnable()
{
#Override
public void run()
{
text.setText("Connection Failed");
String successconnected = null;
successconnected = "connection failed";
textforthespeacch = successconnected;
MainActivity.currentActivity.initTTS();
}
});
}
}
});
t.start();
}
});
}
}
Now in my PC room the laptop IP address is 10.0.0.3
I also added my laptop to my router as a static IP address with the laptop mac.
In my Java code I have a string with 10.0.0.3, but if I take my laptop and my Android device to my living room there there is a different network the laptop's IP address will be something else.
What I want to do is that when I click the button now it's only trying to connect to the given IP address in the string but I want that it will detect automatic the laptop IP address in the router and will connect to it.
So I will not need to change in my java code all the time the IP address in the string.
I think it's called something like umdp not sure.
One option you have is to query the Android device's ARP cache. Unfortunately, since this is only a list of all the devices that your Android has seen it may not be 100% complete. So, what you could do is get your IP then ping all possible IPs on that subnet, forcing the cache to update. From there, you can search the cache for the MAC address of your laptop and read its IP. Here's some (untested) code I threw together that should help you get on the right track:
private static void refereshArp(Context ctx){
//IP aquisition from http://stackoverflow.com/a/6071963/1896516
WifiManager wm = (WifiManager) ctx.getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
String[] parts = ip.split(".");
String subnet = parts[0] + "." + parts[1] + "." + parts[2] + ".";
Runtime rt = Runtime.getRuntime();
for(int i=0; i<256; i++){
try{
rt.exec("ping -c1 " + subnet + i)
}catch(IOException e){
continue;
}
}
}
//Adapted from http://www.flattermann.net/2011/02/android-howto-find-the-hardware-mac-address-of-a-remote-host/
private static String getIpFromMac(String mac) {
if (mac == null)
return null;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = br.readLine()) != null) {
String[] splitted = line.split(" +");
if (splitted != null && splitted.length >= 4 && mac.equals(splitted[3])) {
// return the ip of the device
return splitted[0];
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
If you call refreshArp() then getIpFromMac() with the MAC of your laptop you should get its IP, so long as they're on the same network. Again, I haven't tested this code so it may need some tweaking to get it to work.

Categories