0

I am trying to create app that can connect to a MS SQL database when the user enters his username and password, I have tried multiple times and just cannot succeed. What would be the best way to connect my app?

This is the code that I have tried below.

public class LoginActivity extends AppCompatActivity {

    private static String ip = "myip";
    private static String port = "myportnum";
    private static String Class = "net.sourceforge.jtds.jtbc.Driver";
    private static String database = "name";
    private static String username = "name";
    private static String password = "password";
    private static String url = "jdbc:jtds:sqlserver://"+ip+":"+port+"/"+database;

    private Connection connection = null;




    private EditText userNameET, passwordEt;
    private Button loginBTN;



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


            userNameET = findViewById(R.id.userNameEditText);
            passwordEt = findViewById(R.id.passEditText);

            loginBTN = findViewById(R.id.loginBtn);


            StrictMode.ThreadPolicy policy = null;
            policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);


        }



   // @android.support.annotation.RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
    private class DoLoginForUser extends AsyncTask<String, Void, String> {
        String emailId, password;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            emailId = userNameET.getText().toString();
            password = passwordEt.getText().toString();
           // progressBar.setVisibility(View.VISIBLE);
            loginBTN.setVisibility(View.GONE);
        }

        @Override
        protected String doInBackground(String... params) {

            try {
                ConnectionHelper con = new ConnectionHelper();
                Connection connect = ConnectionHelper.CONN();

                String query = "Select * from testDatabase where UserId='" + emailId + "'";
                PreparedStatement ps = connect.prepareStatement(query);

                Log.e("query",query);
                ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    String passcode = rs.getString("password");
                    connect.close();
                    rs.close();
                    ps.close();
                    if (passcode != null && !passcode.trim().equals("") && passcode.equals(password))
                        return "success";
                    else
                        return "Invalid Credentials";

                } else
                    return "User does not exists.";
            } catch (Exception e) {

                return "Error:" + e.getMessage();
            }
        }

        @Override
        protected void onPostExecute(String result) {

            //Toast.makeText(signup.this, result, Toast.LENGTH_SHORT).show();
           // ShowSnackBar(result);
           // progressBar.setVisibility(View.GONE);
            loginBTN.setVisibility(View.VISIBLE);
            if (result.equals("success")) {
                SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("userdetails",0);
                SharedPreferences.Editor editor = sharedPreferences.edit();

                editor.putString("email",userNameET.getText().toString());

                editor.commit();

                Intent i = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(i);

            } else {
                //ShowSnackBar(result);
            }
        }
    }

    //public void ShowSnackBar(String message) {
      //  Snackbar.make(lvparent, message, Snackbar.LENGTH_LONG)
               // .setAction("CLOSE", new View.OnClickListener() {
                 //   @Override
                //    public void onClick(View view) {

              ////      }
            //    })
            //    .setActionTextColor(getResources().getColor(android.R.color.holo_red_light))

           //     .show();
   // }

    public void DoLogin(View v)
    {
        DoLoginForUser login = null;
        login = new DoLoginForUser();
        login.execute("");
    }

I am expecting it to connect and then take me to the next screen.

Jesse Tee
  • 1
  • 1
  • 3
    **WARNING:** Your code is **dangerous**. It is wide open to SQL injection attacks. Always, *always, **always*** parametrise your code. [Why do we always prefer using parameters in SQL statements?](//stackoverflow.com/q/7505808) – Thom A Jan 25 '23 at 11:25
  • 2
    Also, please [reconsider your use of JDBC on Android](https://stackoverflow.com/questions/15853367/jdbc-vs-web-service-for-android). – CommonsWare Jan 25 '23 at 11:52
  • 1
    Aside... jTDS hasn't seen a release in nearly ten years. Half its functionality didn't work on servers that were current at the time and it certainly doesn't support TLS 1.2 for encrypted connections or any of the new language features on modern SQL Servers. If you need to connect to SQL Server instances from Java consider using modern and supported drivers such as [Microsoft JDBC Driver for SQL Server](https://learn.microsoft.com/en-us/sql/connect/jdbc/microsoft-jdbc-driver-for-sql-server). And... you shouldn't be doing this from cellular/mobile devices, either, wrap databases in web APIs. – AlwaysLearning Jan 25 '23 at 12:05
  • Appreciate the feedback. Is JDBC the right way to connect if I do want to connect from a mobile device? – Jesse Tee Jan 26 '23 at 12:17
  • No, JDBC is not the right way, and you've already got a pointer to the question with answers that explain why. – Endrju Jan 29 '23 at 09:23

0 Answers0