Connect my app to my SQL Server database? - android

I am trying to make a login screen that when the users details are entered it will connect to the MS SQL database, the problem is it is not connecting. Am I doing it the right way or is there a better way to do this?
The error I am getting.
E/ERROR: Unknown server host name 'Unable to resolve host "myipaddresstestDatabasetestDatabase": No address associated with hostname'.
Here is my code that I tried.
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 expected it to connect and then take me to the next screen, but the error is persistent?

The error message "Unable to resolve host" indicates that you are not putting the correct sql server hostname or ip in your connection string, or you try to reach an unreachable server (from your test device).
Is the sql server reachable for you from your dev computer? If so, you may need to connect your test device via wifi.
Make sure the device and the sql server are in the same network.

Related

How can I connect my app to MS SQL database?

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.

query is not executed in sql server with android app

I have no idea why is this happening, I mean the connection with the database is established, but the query itself is not giving any output. No exceptions or anything, I press the button and nothing is happening
Here's the Java code:
public class LogIn extends AppCompatActivity {
EditText pass;
EditText usname;
Connection con = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
connectTodatabase();
Button btn=(Button) findViewById(R.id.button);
TextView txtView1=(TextView)findViewById(R.id.textView1);
txtView1.setText("ffgf");
}
public void logIn(View v)
{
EditText usname=(EditText) findViewById(R.id.editText);
EditText pass=(EditText) findViewById(R.id.editText2);
TextView txtView1=(TextView)findViewById(R.id.textView1);
String username=usname.getText().toString();
String password=pass.getText().toString();
txtView1.setText("ffgf");
String SQLStatment = "select * from users where usname='"+username+"' AND uspass='"+password+"'";
try {
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(SQLStatment);
int count=rs.getRow();
txtView1.setText("ffgf");
if(count>0)
{
Toast.makeText(this,"Query success",Toast.LENGTH_LONG).show();
Intent intent=new Intent(getBaseContext(),appPage.class);
startActivity(intent);
}
else
{
txtView1.setText("incorrect");
}
}
catch(Exception e)
{
txtView1.setText(e.getMessage());
}
}
public void connectTodatabase()
{
Connection con;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String url = "jdbc:jtds:sqlserver://192.168.111.14:1433;instanceName=SQLEXPRESS;DatabaseName=test";
String driver = "net.sourceforge.jtds.jdbc.Driver";
String userName = "sam";
String password = "111";
// Declare the JDBC objects.
try
{
// Establish the connection.
Class.forName(driver);
con = DriverManager.getConnection(url, userName, password);
// Create and execute an SQL statement that returns some data.
Toast.makeText(getApplicationContext(),"Success", Toast.LENGTH_LONG).show();
}
catch(Exception ex)
{
Toast.makeText(getApplicationContext(), "aa" + ex.getMessage().toString() + "ss", Toast.LENGTH_LONG).show();
}
}
}

Thread connection Postgresql db dont work

my problem is that I want connect to a db of Postgresql in android, and I see that I need do with a thread, I make this thread in a private class under main class, but dont work, the "Toast" always show "Vacío". What I do bad? :/
public class MainActivity extends AppCompatActivity {
Button btnEntrar;
EditText etUsuario;
EditText etPass;
public static String login = "Vacío";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnEntrar = (Button) findViewById(R.id.btnEntrar);
etUsuario = (EditText) findViewById(R.id.etUsuario);
etPass = (EditText) findViewById(R.id.etPass);
btnEntrar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String usuario = etUsuario.getText().toString();
String pass = etPass.getText().toString();
new ConnUsers(usuario, pass).execute();
Toast.makeText(MainActivity.this, login, Toast.LENGTH_SHORT).show();
/*if(login){
Intent intent = new Intent(MainActivity.this, IncidenciasActivity.class);
startActivity(intent);
Toast.makeText(MainActivity.this, "Acceso es TRUE", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this, "Acceso es FALSE", Toast.LENGTH_SHORT).show();
} */
}
});
}
private class ConnUsers extends AsyncTask <String, String, String>{
private static final String DB_DRIVER = "org.postgresql.Driver";
private static final String url = "jdbc:postgresql://xxx/xxx";
private static final String user = "xxx";
private static final String password = "xxx";
private String usuario;
private String pass;
public ConnUsers(String usuario, String pass){
this.usuario = usuario;
this.pass = pass;
}
#Override
protected String doInBackground(String... params) {
String acceso = "doInBackground";
try{
Class.forName(DB_DRIVER);
Connection connection = DriverManager.getConnection(url, user, password);
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM usuarios WHERE usuario = '" + usuario +"'");
if(rs.next()!=false){
if(Funciones.md5(pass).equalsIgnoreCase(rs.getString("password"))){
int id = rs.getInt("id");
acceso = "Todo correcto";
}
else{
//Toast.makeText(context, "Password incorrecto", Toast.LENGTH_LONG).show();
acceso = "Falla la pass";
}
}
else{
//Toast.makeText(context, "Usuario incorrecto", Toast.LENGTH_LONG).show();
acceso = "Falla el usuario";
}
rs.close();
st.close();
connection.close();
}catch(SQLException e){
cancel(true);
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return acceso;
}
#Override
protected void onPostExecute(String s) {
MainActivity.login = s;
}
#Override
protected void onCancelled() {
}
}
}
Maybe your connection can't access to PostgreSQL server for security. İt's mean your database working just Localhost. Because some servers block directly connection in general.
İf your problem is it, You should use WebService. Like that

Open different activities according to the login credentials entered

Below is my login activity.
It has a simple layout,where user enters his username and password and click login button.
A list of username and passwords is being stored in ms sql server.
And connection is also being established.
But the problem is on different combinations of usernames and passwords i want to open different activities.
How can i do it?
Lets say I have two combinations of username and password in my database-1.username1 , password1 (should open activity 1 on login button click)
2.username2, password2 (shoud open activity 2 on login button click)
Here is the code-----
public class Login extends Activity
{
private static final String DUMMY_CREDENTIALS = "user#test.com:hello";
// private UserLoginTask userLoginTask = null;
private View loginFormView;
private View progressView;
ConnectionClass connectionClass;
private AutoCompleteTextView emailTextView;
private EditText passwordTextView;
private Button btnlogin;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
connectionClass = new ConnectionClass();
emailTextView = (AutoCompleteTextView) findViewById(R.id.email);
//loadAutoComplete();
passwordTextView = (EditText) findViewById(R.id.password);
btnlogin=(Button) findViewById(R.id.email_sign_in_button);
class DoLogin extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSuccess = false;
String userid = emailTextView.getText().toString();
String password = passwordTextView.getText().toString();
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String r) {
Toast.makeText(Login.this, r, Toast.LENGTH_SHORT).show();
if(isSuccess) {
Intent i = new Intent(Login.this, Activity1.class);//For any combination ,it will open activity1 now.
startActivity(i);
finish();
}
}
#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 EmailID,Password from Login_DB where EmailID='" + userid + "' and Password='" + password + "'";
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";
}
}
return z;
}
}
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DoLogin doLogin = new DoLogin();// this is the Asynctask
doLogin.execute("");
}
});
}
}
Create a table in your database that links usernames to activities, and then query it after authenticating the user.

Issue about using Async with an Android Client

I am currently creating a project that needs to have a simple async task to take care of a thread running behind the scenes. The user needs to login. I am using another class called PVAndroid Client that supplies useful methods and has an XML serializer form packets for me. I am completely new to working with threads or doing anything with servers, so this may be completely wrong or somewhat right.
I get the data the user entered: the ip address and port, their username (I split this into first and last name), their region they selected. I encrypt their password, and attempt to connect to the tcp using ip address and port number. I am trying to work in the async task but am kind of confused on what I should do. Can anyone guide me in the right direction and help me out?
Thank you I really appreciate it.
private TcpClient myTcpClient = null;
private UdpClient udpClient;
private static final String USERNAME_SHARED_PREFS = "username";
private static final String PASSWORD_SHARED_PREFS = "password";
private static final String IP_ADDRESS_SHARED_PREFS = "ipAddressPref";
private static final String PORT_SHARED_PREFS = "portNumberPref";
private String encryptedNameLoginActivity, encryptPassLoginActivity;
private EditText userText, passText;
private String getIpAddressSharedPrefs, getPortNumberPrefs;
private String getUserNameValue;
private String getPasswordValue;
private String fName, lName;
private SharedPreferences settings;
private Editor myEditor;
private boolean getCheckedRemember;
private boolean resultCheck = false;
private int portNum;
private Button submitButton;
private String userMACVARIABLE = "";
private String regionSelected, gridSelected;
private Spinner regSpinner, gridSpinner;
PVDCAndroidClient client;
private int userNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
client = new PVDCAndroidClient();
}
#Override
protected void onStart() {
super.onStart();
// Take care of getting user's login information:
submitButton = (Button) findViewById(R.id.submitButton);
userText = (EditText) findViewById(R.id.nameTextBox);
passText = (EditText) findViewById(R.id.passwordTextBox);
regSpinner = (Spinner) findViewById(R.id.regionSpinner);
// grid selected as well? sometime?
regSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v,
int position, long rowId) {
regionSelected = regSpinner.getItemAtPosition(position)
.toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
submitButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
settings = PreferenceManager
.getDefaultSharedPreferences(AndroidClientCompnt.this);
getIpAddressSharedPrefs = settings.getString(
IP_ADDRESS_SHARED_PREFS, "");
portNum = Integer.parseInt(settings.getString(
PORT_SHARED_PREFS, ""));
if (getIpAddressSharedPrefs.length() != 0 && portNum != 0) {
if (userText.length() != 0 && passText.length() != 0) {
try {
try {
// encrypting the user's password.
encryptPassLoginActivity = Secure.encrypt(passText
.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// first connect attempt.
myTcpClient = new TcpClient();
myTcpClient.connect(getIpAddressSharedPrefs,
portNum);
// here is where I want to call Async to do login
// or do whatever else.
UploadTask task = new UploadTask();
task.execute();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Could not connect.", Toast.LENGTH_LONG)
.show();
e.printStackTrace();
}
}
}
}
});
}
private class UploadTask extends AsyncTask<String, Integer, Void>
{
#Override
protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "Loading...",
Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(String... names) {
resultCheck = myTcpClient.connect(getIpAddressSharedPrefs,
portNum);
if (resultCheck == true) {
while (myTcpClient.getUserNum() < 0) {
// num set? session? with proxy server?
}
String[] firstAndLast;
String spcDelmt = " ";
firstAndLast = userText.toString().split(spcDelmt);
fName = firstAndLast[0];
lName = firstAndLast[1];
// set up the tcp client to sent the information to the
// server.
client.login(fName, lName, encryptPassLoginActivity,regionSelected, 128, 128, 20);
} else {
Toast.makeText(getApplicationContext(),
"Connection not successful", Toast.LENGTH_LONG)
.show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Toast.makeText(getApplicationContext(), "Connected",
Toast.LENGTH_LONG).show();
}
}
}
First
#Override
protected Void doInBackground(String...params) {
new Thread (new Runnable() {
// ...
}
}
Never do this again. There is no need to create new Thread in doInBackground method which actually running on background Thread. So remove it.
The advice to you is tricky because you need to read about Threads, work with Connection etc. So the best advice to you is to read some tutorials, examples of basic applications and read references. So you can start here:
Android TCP Client and Server Communication Programming–Illustrated with Example
I cannot see, where you are yoursing your Task, but I see that you are doing something weired inside doInBackground()! There is absolutely NO reason, to create your own Thread inside it.
remove that, and you could just use your Task like this:
UploadTask task = new UploadTask();
task.execute("someString", "anotherString", "addAsManyStringsYouNeed");
The docs from AsyncTask are very helpfull, too.

Categories

Resources