简体   繁体   中英

java.sql.SQLException: Network error IOException: failed to connect ETIMEDOUT

I am developing an android app in which I have to connect android application with SQL server database in order to authenticated the user with their username and password. I have used the jtds library in order to provide Sql connection to android.Below is my code:

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    EditText username,password;
    CheckBox mCbShowPwd;
    Connection con;
    String un,pass,db,ip,in;
    TextView t;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        username = (EditText) findViewById(R.id.username_edtext);
        password = (EditText) findViewById(R.id.passwd_edtext);
        mCbShowPwd = (CheckBox) findViewById(R.id.cbShowPwd);
        t = (TextView) findViewById(R.id.text);
        final Button forget_btn = (Button) findViewById(R.id.forget_btn);
        forget_btn.setOnClickListener(this);
        final Button login_btn = (Button) findViewById(R.id.login_button);
        login_btn.setOnClickListener(this);
        ip = "172.16.0.**";
        in="********";
        db = "*******";
        un = "****";
        pass = "****";
        mCbShowPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // checkbox status is changed from uncheck to checked.
                if (!isChecked) {
                    password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                } else {
                    password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());}
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.forget_btn:
            {
                Intent intent=new Intent("com.example.pc.uowv1.ForgetPassActivity");
                startActivity(intent);
                break;
            }
            case R.id.login_button:
            {
                CheckLogin checkLogin = new CheckLogin();// this is the Asynctask, which is used to process in background to reduce load on app process
                checkLogin.execute("");
                break;
            }
        }
    }
    public class CheckLogin extends AsyncTask<String,String,String>
    {
        String z = "";
        Boolean isSuccess = false;
        String usernam = username.getText().toString();
        String passwordd = password.getText().toString();

        @Override
        protected void onPreExecute()
        {
            //progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected void onPostExecute(String r)
        {
            Toast.makeText(MainActivity.this, r, Toast.LENGTH_SHORT).show();
            if(isSuccess)
            {
                Toast.makeText(MainActivity.this , "Login Successfull" , Toast.LENGTH_SHORT).show();
            }
        }
        @Override
        protected String doInBackground(String... params)
        {
            if(usernam.trim().equals("")|| passwordd.trim().equals(""))
                z = "Please enter Username and Password";
            else
            {
                try
                {
                    con = connectionclass(un, pass, db, ip,in);
                    if (con == null)
                    {
                        z = "Check Your Internet Access!";
                    }
                    else
                    {
                        String query = "select * from Login where username= '" + usernam.toString() +"'and password='"+passwordd.toString()+"'";
                        Statement stmt = con.createStatement();
                        ResultSet rs = stmt.executeQuery(query);
                        if(rs.next())
                        {
                            //mApp.setmGuser(usernam);
                            z = "Login successful";
                            isSuccess=true;
                            con.close();
                            Intent intent=new Intent(MainActivity.this,MAin2Activity.class);
                            intent.putExtra("username",usernam.toString());
                            startActivity(intent);
                        }
                        else
                        {
                            z = "Invalid Username and password!";
                            isSuccess = false;
                        }
                    }
                }
                catch (Exception ex)
                {
                    isSuccess = false;
                    z = ex.getMessage();
                }
            }
            return z;
        }
    }
    @SuppressLint("NewApi")
    public Connection connectionclass(String user, String password, String database, String server,String instance)
    {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Connection connection = null;
        String ConnectionURL = null;
        try
        {

            Class.forName("net.sourceforge.jtds.jdbc.Driver");
            ConnectionURL = "jdbc:jtds:sqlserver://" + server + "/"+ database+";instance=" + instance + ";user=" + user+ ";password=" + password + ";";
            connection = DriverManager.getConnection(ConnectionURL);
        }
        catch (SQLException se)
        {
            Log.e("error here 1 : ", se.getMessage());
            t.setText(se.getMessage());
        }
        catch (ClassNotFoundException e)
        {
            Log.e("error here 2 : ", e.getMessage());
            t.setText(e.getMessage());
        }
        catch (Exception e)
        {
            Log.e("error here 3 : ", e.getMessage());
            t.setText(e.getMessage());
        }
        return connection;
    }
}

The Code works on same network but when I connect to other network in my android device it throws

Exception E/error here 1 :: Network error IOException: failed to 
connect to /172.16.0.** (port 1433): connect failed: ETIMEDOUT 
(Connection timed out).

IMНO you have chosen the wrong way. Do not use the connection to the SQL server from Android. It is necessary to make a web service on the SQL server's side and use this web service from Android. JDBC drivers are not designed to work in mobile networks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM