How can I connect my app to MS SQL database? - android

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.

Related

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.

Android SharedPreferences null pointer [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Help me on android SharedPreferences, I have login activity when after login will set the SharedPreferences, but when set SharedPreferences always error null pointer. I try to show the value with toast and all variable have value. this my activity
public class LoginNewActivity extends Activity {
public SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView toRegister = (TextView) findViewById(R.id.link_to_register);
toRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(i);
}
});
final EditText etUsnm = (EditText) findViewById(R.id.tuserid);
final EditText etPswd = (EditText) findViewById(R.id.tpasswd);
Button bLogin = (Button) findViewById(R.id.btnLogin);
bLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String username = etUsnm.getText().toString();
String password = etPswd.getText().toString();
new UserLoginTask().execute(username, password);
}
});
}
public class UserLoginTask extends AsyncTask<String, String, JSONObject> {
ProgressDialog pdLoading = new ProgressDialog(LoginNewActivity.this);
HttpURLConnection conn;
URL url = null;
JSONParser jsonParser = new JSONParser();
private static final String TAG_MESSAGE = "message";
private static final String TAG_NAMA = "nama_user";
private static final String TAG_USERNAME = "username";
private static final String TAG_HAKAKSES = "role";
private static final String TAG_ERROR = "error";
private static final String LOGIN_URL = "http://192.168.1.101/mlls/getLoginNew.php";
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected JSONObject doInBackground(String... args) {
try {
HashMap<String, String> params = new HashMap<>();
params.put("username", args[0]);
params.put("password", args[1]);
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
String nama = "";
int iduser = 0;
String email = "";
String hakakses = "";
int error_message = 0;
if (json != null) {
//Toast.makeText(LoginActivity.this, json.toString(),
//Toast.LENGTH_LONG).show();
try {
nama = json.getString(TAG_NAMA);
email = json.getString(TAG_USERNAME);
hakakses = json.getString(TAG_HAKAKSES);
error_message = json.getInt(TAG_ERROR);
} catch (JSONException e) {
e.printStackTrace();
}
}
if(error_message == 1) {
pdLoading.dismiss();
session.setLogin(true);
session.setStatus(hakakses);
session.setNama(nama);
session.setUsername(email);
session.setId(iduser);
Toast.makeText(LoginNewActivity.this, hakakses,
Toast.LENGTH_LONG).show();
//Intent intent = new Intent(LoginNewActivity.this, LessonListActivity.class);
//intent.putExtra("nama", nama);
//intent.putExtra("email", email);
//intent.putExtra("hakakses", hakakses);
//startActivity(intent);
//LoginNewActivity.this.finish();
}else{
Toast.makeText(getApplicationContext(), "User ID atau Password anda salah.", Toast.LENGTH_LONG).show();
}
}
}}
and this is my sharedPreferences
public class SessionManager {
private static String TAG = SessionManager.class.getSimpleName();
SharedPreferences pref;
Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "Hlls";
private static final String KEY_IS_LOGGEDIN = "isLoggenIn";
private static final String KEY_IS_USER = "isStatus";
private static final String KEY_IS_NAMA = "isNama";
private static final String KEY_IS_USERNAME = "isUsername";
private static final String KEY_IS_IDUSER = "isIdUser";
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setLogin(boolean isLoggedIn){
editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);
editor.commit();
Log.d(TAG, "User login session modified");
}
public void setId(int isIdUser){
editor.putInt(KEY_IS_IDUSER, isIdUser);
editor.commit();
Log.d(TAG, "ID User akses session modified");
}
public void setStatus(String isStatus){
editor.putString(KEY_IS_USER, isStatus);
editor.commit();
Log.d(TAG, "User akses session modified");
}
public void setNama(String isNama){
editor.putString(KEY_IS_NAMA, isNama);
editor.commit();
Log.d(TAG, "Username session modified");
}
public void setUsername(String isUsername){
editor.putString(KEY_IS_USERNAME, isUsername);
editor.commit();
Log.d(TAG, "Username session modified");
}
public String isNama(){
return pref.getString(KEY_IS_NAMA, "");
}
public int isId(){
return pref.getInt(KEY_IS_IDUSER, 0);
}
public String isUsername(){
return pref.getString(KEY_IS_USERNAME, "");
}
public boolean isLoggedIn(){
return pref.getBoolean(KEY_IS_LOGGEDIN, false);
}
public String isStatus(){
return pref.getString(KEY_IS_USER, "");
}
}
help me for this error, sorry for bad english
NullPointerException is thrown when an application attempts to use an
object reference that has the null value .
You should call this in your ONCREATE section .
session=new SessionManager(LoginNewActivity.this);
Finally
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
session=new SessionManager(LoginNewActivity.this);
Use mode private instead of private mode
pref = _context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
It is flag provided by android itself you need not assign any other flag to it.
and you have not initialized session manager context is null.
I guess you are not initializing your Shared Preference class.
SessionManager session = new SessionManager(this);
In case its true
Please try and make it a singleton class as a general practise
Something like this
public final class PreferenceManager {
private static SharedPreferences preferences;
/**
* Private constructor to restrict the instantiation of class.
*/
private PreferenceManager() {
throw new AssertionError();
}
public static SharedPreferences getInstance(Context context) {
if (preferences == null && context != null) {
preferences = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
}
return preferences;
}
}
You need to do the following in your Activity:
session = new SessionManager(LoginNewActivity.this);
You have not created the object of your SessionManager class, so its constructor never gets called and you get NPE.

Android Login Activity

I have an application android with login activity. my application work perfectly but after I login and I close my application and than I open it again I always must login first. I don't know how to make my program just login once time.
My code like this
public class MainActivity extends Activity {
TextView btnForgot;
Button btnLogin;
EditText inputEmail;
EditText inputPassword;
private TextView loginErrorMsg;
private TextView macmac, macmac1;
private ProgressDialog pDialog;
private static String KEY_SUCCESS = "success";
private static String KEY_UID = "uid";
private static String KEY_USERNAME = "uname";
private static String KEY_FIRSTNAME = "fname";
private static String KEY_LASTNAME = "lname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private static String MAC = "mac_0";
JSONParser jParser = new JSONParser();
JSONArray products = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnForgot = (TextView) findViewById(R.id.textView);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
loginErrorMsg = (TextView) findViewById(R.id.loginErrorMsg);
TypedValue typedValueColorPrimaryDark = new TypedValue();
MainActivity.this.getTheme().resolveAttribute(R.attr.colorPrimary, typedValueColorPrimaryDark, true);
final int colorPrimaryDark = typedValueColorPrimaryDark.data;
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(colorPrimaryDark);
}
/** Button Forgot Password **/
btnForgot.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), PasswordResetActivity.class);
startActivityForResult(myIntent, 0);
finish();
}});
/** Button Login **/
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if ( ( !inputEmail.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) )
{
NetAsync(view);
}
else if ( ( !inputEmail.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(), "Password field empty", Toast.LENGTH_SHORT).show();
}
else if ( ( !inputPassword.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(), "Email field empty", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "Email and Password field are empty", Toast.LENGTH_SHORT).show();
}
}
});
}
private class NetCheck extends AsyncTask<String,String,Boolean>
{
private ProgressDialog nDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(MainActivity.this);
nDialog.setTitle("Checking Network");
nDialog.setMessage("Loading..");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
/** Gets current device state and checks for working internet connection by trying Google **/
#Override
protected Boolean doInBackground(String... args){
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessLogin().execute();
}
else{
nDialog.dismiss();
loginErrorMsg.setText("Error in Network Connection");
}
}
}
/** Async Task to get and send data to My Sql database through JSON respone **/
private class ProcessLogin extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
String email,password,mac1;
#Override
protected void onPreExecute() {
super.onPreExecute();
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
email = inputEmail.getText().toString();
password = inputPassword.getText().toString();
//mac1 = macmac.getText().toString();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Logging in ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
pDialog.setMessage("Loading User Space");
pDialog.setTitle("Getting Data");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
/** Clear all previous data in SQlite database **/
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
/** If JSON array details are stored in SQlite it launches the User Panel **/
Intent upanel = new Intent(getApplicationContext(), HomeActivity.class);
upanel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
new status_login().execute();
startActivity(upanel);
/** Close Login Screen **/
finish();
}else{
pDialog.dismiss();
loginErrorMsg.setText("Incorrect username or password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public void NetAsync(View view){
new NetCheck().execute();
}
}
anyone can help me to make my application just one time login?
thanks before
You must store the values within shared preference so that, untill the app data is cleared or no session destroyed by the user, user will be logged in within application, and the login screen will appear only once.
in you post execute, you know that your user has logged in successfully or not. so it would not so bad to set a preference to set that login is true, so in another activity you can check the value of that shared preference value and if it true then he was logged in successfully otherwise not. so write something the following way
// in this method where you find your user either to be logged in or failed
#Override
protected void onPostExecute(JSONObject json) {
try {
if (json.getString(KEY_SUCCESS) != null) {
if (login == true) {
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(getString(R.string.login), true);
editor.commit();
}
}
}
and your main activity check for it as shown below
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
boolean login = getResources().getBoolean(R.string.login);
if (login) {
// do what you want to do
} else {
// prompt for login again
}
know more about SharedPreference
This is Your Answer
public class MainActivity extends Activity {
TextView btnForgot;
Button btnLogin;
EditText inputEmail;
EditText inputPassword;
private TextView loginErrorMsg;
private TextView macmac, macmac1;
private ProgressDialog pDialog;
private static String KEY_SUCCESS = "success";
private static String KEY_UID = "uid";
private static String KEY_USERNAME = "uname";
private static String KEY_FIRSTNAME = "fname";
private static String KEY_LASTNAME = "lname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private static String MAC = "mac_0";
JSONParser jParser = new JSONParser();
JSONArray products = null;
SharedPreferences sharedPref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPref = getSharedPreferences("MysharePrefrence", MODE_PRIVATE);
editor = sharedPref.edit();
boolean login = sharedPref.getBoolean("isLogin",false);
if (login)
{
Intent upanel = new Intent(getApplicationContext(), HomeActivity.class);
upanel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(upanel);
finish();
}
btnForgot = (TextView) findViewById(R.id.textView);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
loginErrorMsg = (TextView) findViewById(R.id.loginErrorMsg);
TypedValue typedValueColorPrimaryDark = new TypedValue();
MainActivity.this.getTheme().resolveAttribute(R.attr.colorPrimary, typedValueColorPrimaryDark, true);
final int colorPrimaryDark = typedValueColorPrimaryDark.data;
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(colorPrimaryDark);
}
/** Button Forgot Password **/
btnForgot.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), PasswordResetActivity.class);
startActivityForResult(myIntent, 0);
finish();
}});
/** Button Login **/
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if ( ( !inputEmail.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) )
{
NetAsync(view);
}
else if ( ( !inputEmail.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(), "Password field empty", Toast.LENGTH_SHORT).show();
}
else if ( ( !inputPassword.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(), "Email field empty", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "Email and Password field are empty", Toast.LENGTH_SHORT).show();
}
}
});
}
private class NetCheck extends AsyncTask<String,String,Boolean>
{
private ProgressDialog nDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(MainActivity.this);
nDialog.setTitle("Checking Network");
nDialog.setMessage("Loading..");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
/** Gets current device state and checks for working internet connection by trying Google **/
#Override
protected Boolean doInBackground(String... args){
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessLogin().execute();
}
else{
nDialog.dismiss();
loginErrorMsg.setText("Error in Network Connection");
}
}
}
/** Async Task to get and send data to My Sql database through JSON respone **/
private class ProcessLogin extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
String email,password,mac1;
#Override
protected void onPreExecute() {
super.onPreExecute();
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
email = inputEmail.getText().toString();
password = inputPassword.getText().toString();
//mac1 = macmac.getText().toString();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Logging in ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
pDialog.setMessage("Loading User Space");
pDialog.setTitle("Getting Data");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
/** Clear all previous data in SQlite database **/
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
/** If JSON array details are stored in SQlite it launches the User Panel **/
editor.putBoolean("isLogin",true);
editor.commit();
Intent upanel = new Intent(getApplicationContext(), HomeActivity.class);
upanel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
new status_login().execute();
startActivity(upanel);
/** Close Login Screen **/
finish();
}else{
pDialog.dismiss();
loginErrorMsg.setText("Incorrect username or password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public void NetAsync(View view){
new NetCheck().execute();
}
}
You can use a SharedPreferences object to save the login status. Once a user is successfully login you store a boolean flag, for example:
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("signed_in", true);
editor.commit();
Next time you will just check this value.
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
if (sharedPref.getBoolean("signed_in", false) == true){
//user is login
}else{
//user not login
}

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.

Categories

Resources