-2

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.

trial
  • 19
  • 1
  • 6
  • but i could not understand from there. Why should i do? – trial Jun 27 '17 at 21:59
  • What part don't you understand? – President James K. Polk Jun 27 '17 at 22:04
  • Are you doing this from an emulator or your device? If it's your device make sure you are on the wi-fi and not using your cellular data. It needs to be on the same network. If you are using an emulator, your IP should be 10.0.2.2 not localhost (aka 127.0.0.1) as Android emulator is on a VM. – Carson Jun 27 '17 at 22:05
  • I am doing this through an emulator. But I want to connect mssql in my pc. So it should be 127.0.0.1 ? it is for mssql server in pc not for phone – trial Jun 27 '17 at 22:11
  • Nah don't do 127.0.0.1, do 10.0.2.2. Local host on the emulator is going to refer to the emulator not that actual local host where your database is. – Carson Jun 27 '17 at 22:13

1 Answers1

0

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.

Carson
  • 1,147
  • 5
  • 19
  • 41
  • Yes thank you It worked. But now I have another error. It says "Incorrect syntax near the keyword User". – trial Jun 27 '17 at 22:21
  • That sounds like an error with using a reserved word for MS SQL https://stackoverflow.com/questions/25589031/50894-error-reading-incorrect-syntax-near-the-keyword-user-when-tries-to-sele – Carson Jun 27 '17 at 22:26
  • Okey I used [User]. and it worked. Thank you for your help. – trial Jun 27 '17 at 22:28