Thread connection Postgresql db dont work - android

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

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.

Connect my app to my SQL Server database?

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.

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();
}
}
}

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.

Inner AsyncTask not updating member variables in outer class

I have an app that in one of it's Activities uses AsyncTask to call a method from another class that hooks up to a database to varify a user's login credentials. The Activity EntryActivity Has three member variable that need to be updated with the result of the AsyncTask, carerID, firstName and surName . When I first run the App all three variables are null but if i press the login button a second time the variables are set correctly and the app behaves as it should.
Is there a reason why the three member variables are not set correctly from onPostxecute in the first run of the app?
.
public class EntryActivity extends NfcBaseActivity{
private LoginWebservice loginWebservice;
private static final String TAG = EntryActivity.class.getSimpleName();
private Button login;
private EditText userName;
private EditText passwordPin;
NfcScannerApplication nfcscannerapplication;
public static final String CUSTOM_QRCODE_ACTION = "com.carefreegroup.QRCODE_ACTION";
private String carerID;
private String firstName;
private String surName;
private boolean isValidated = false;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entryscreen);
nfcscannerapplication = (NfcScannerApplication) getApplication();
loginWebservice = new LoginWebservice(this);
carerID = null;
firstName = null;
surName = null;
userName = (EditText)findViewById(R.id.username);
passwordPin = (EditText)findViewById(R.id.password);
login = (Button)findViewById(R.id.buttonlogin);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
////////////get user's input///////////
String compId = "100";
String theUsername = userName.getText().toString();
String thePassword = passwordPin.getText().toString();
String loginType = "1";
String[] params = new String[]{compId, theUsername, thePassword, loginType};
//validate user Asynchonously on background thread
new AsyncValidateCarer().execute(params);
Log.e(TAG, "carerid =" + carerID + " firstname = " + firstName + " surnamee = " + surName);
DateTime now = new DateTime();
long loginTime = now.getMillis();
String fullName = firstName +" " + surName;
Log.e(TAG, "fullname = " + fullName);
if(carerID != null){
ContentValues loginValues = new ContentValues();
loginValues.putNull(LoginValidate.C_ID_INDEX);
loginValues.put(LoginValidate.C_CARER_ID, carerID);
loginValues.put(LoginValidate.C_COMP_ID, compId);
loginValues.put(LoginValidate.C_CARER_NAME, fullName);
loginValues.put(LoginValidate.C_PASSWORD, thePassword);
loginValues.put(LoginValidate.C_DATE_TIME, loginTime);
nfcscannerapplication.loginValidate.insertIntoCarer(loginValues);
Toast.makeText(
EntryActivity.this,
"Carer logged in to System",
Toast.LENGTH_LONG).show();
isValidated = true;
Intent intent = new Intent(EntryActivity.this,
NfcscannerActivity.class);
intent.setAction(CUSTOM_QRCODE_ACTION);
startActivity(intent);
}else{
Toast.makeText(
EntryActivity.this,
"Please check credentials",
Toast.LENGTH_LONG).show();
}
//////////////validate user/////////////////
}
});
Button changeUser = (Button)findViewById(R.id.buttonchangeuser);
changeUser.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e(TAG, "change user button clicked");
nfcscannerapplication.loginValidate.deleteTableCarer();
Toast.makeText(
EntryActivity.this,
"Carer logged out",
Toast.LENGTH_LONG).show();
EntryActivity.this.onCreate(savedInstanceState);
}
});
}//end of onCreate
private void hideSoftKeyboard() {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(passwordPin.getWindowToken(), 0);
}
private class AsyncValidateCarer extends AsyncTask<String, Void, ContentValues> {
#Override
protected ContentValues doInBackground(String... params) {
ContentValues cv = null;
try {
Log.e(TAG, "inside asynctask");
cv = loginWebservice.validateCarer(params[0], params[1], params[2], params[3]);
if (cv != null){
Log.e(TAG, "cv = not null!");
}
} catch (Exception e) {
e.printStackTrace();
}
return cv;
}
#Override
protected void onPostExecute(ContentValues result) {
Log.e(TAG, "inside onpostexecute");
EntryActivity.this.carerID = (String) result.get("carerID");
EntryActivity.this.firstName = (String) result.get("firstname");
EntryActivity.this.surName = (String) result.get("surname");
}
}
}
[update]
private class AsyncValidateCarer extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
ContentValues cv = null;
try {
Log.e(TAG, "inside doInBackground");
cv = loginWebservice.validateCarer(params[0], params[1], params[2], params[3]);
carerID = (String) cv.get("carerID");
firstName = (String) cv.get("firstname");
surName = (String) cv.get("surname");
if (cv != null){
Log.e(TAG, "cv = not null! and exiting doInBackground");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
An AsyncTask will execute asynchronously so you have no guarantee that after the "execute" method call, the task is actually finished. My advice would be to move everything (or at least what is related to those fields) that are after "execute" call in "onPostExecute" method.
The reason why it seems the first click doesn't work and the second works, is that between the first "Login" click and the second one, you wait enough for the AsyncTask to finish. So when you click for the second time you see the results of the first execution. Please add some "Log" messeges in "onPostExecute" to understand what is going on.
Hope it helps:)
carerID = null;
firstName = null;
surName = null;
Remove the above there statements from the onCreate() method, as they have been initialized to their default values as they are in the Class Scope and are known as Instance Variables.

Categories

Resources