boolean not evaluating to true although conditions are met - android

So I have a static variable called isSuccessful all the variable is supposed to do is, be true if someone was able to login successfully or be false if they couldn't. I have it set to false by default. The php script I wrote sends the message "loginsuccess" and stores it in the onProgressUpdate parameters. I debugged to see if that's what was being stored in the parameters, and the compile says it is. well then I can't figure out why isSuccessful isn't being switched to true. I set it to do that. once that happens, I have the login activity call the homeScreen activity.
LoginTask:
public class LogInTask extends AsyncTask<String, String,String> {
public Scanner reader;
Formatter writer;
Context mcontext;
//if Login was successful
public static boolean isSuccessful;
LogInTask(Context context)
{
mcontext = context;
}
URL url;
URLConnection con;
String output = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
isSuccessful=false;
try {
url = new URL("http://192.168.1.75:1234/login.php");
con = url.openConnection();
//allows to send information
con.setDoOutput(true);
//allows to receive information
con.setDoInput(true);
writer = new Formatter(con.getOutputStream());
//Sends login information to SQL table
writer.format("user_name="+params[0]+"&password="+params[1]);
writer.close();
//Reads input
reader = new Scanner(con.getInputStream());
while(reader.hasNext())
{
output+= reader.next();
}
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
publishProgress(output);
return output;
}
#Override
protected void onProgressUpdate(String... values) {
Toast.makeText(mcontext, values[0],Toast.LENGTH_LONG).show();
if(values[0]=="loginsuccess")
isSuccessful = true;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
LogInActivity:
public class LogInActivity extends Activity {
private Typeface fontRobo;
private TextView logoText;
private EditText userName;
private EditText passWord;
private TextView dontHave;
private TextView signUp;
private Button logIn;
Intent i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
i = new Intent(this, HomeActivity.class);
//Logo
logoText = (TextView)findViewById(R.id.Logo);
fontRobo = Typeface.createFromAsset(this.getAssets(),"fonts/ROBO.ttf");
logoText.setText("ArtSpace");
logoText.setTypeface(fontRobo);
//Don't have an account?
dontHave = (TextView) findViewById(R.id.Donthave);
dontHave.setTypeface(fontRobo);
//Sign Up
signUp = (TextView) findViewById(R.id.signUP);
signUp.setTypeface(fontRobo);
userName = (EditText) findViewById(R.id.userName);
passWord = (EditText) findViewById(R.id.passWord);
logIn = (Button) findViewById(R.id.LogIn);
}
//Log in button event
public void logInClick(View view)
{
final LogInTask task = new LogInTask(LogInActivity.this);
task.execute(userName.getText().toString(), passWord.getText().toString());
if(LogInTask.isSuccessful)
startActivity(i);
}
php:
<?php
require "conn.php";
$user_name = $_POST['user_name'];
$user_pass = $_POST['password'];
$mysql_qry = "SELECT * FROM login WHERE UserName LIKE '$user_name' AND Password LIKE '$user_pass';";
$result = mysqli_query($conn,$mysql_qry);
if(mysqli_num_rows($result) == true)
{
echo "login success";
}
else
{
echo "login not success";
}
?>

task.execute() is AsyncTask aka it takes time to execute. But you are checking right after you call it. You need to make the check for isSuccessful in onPostExecute() block.
Something like this:
final LogInTask task = new LogInTask(LogInActivity.this){
#Override
protected void onPostExecute(String s) {
if(LogInTask.isSuccessful)
startActivity(i);
}};
task.execute(userName.getText().toString(), passWord.getText().toString());
PS: Something else, do not compare Strings with == use .equals()
if(values[0].equals("loginsuccess"))

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 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
}

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.

Android Intent after onpostexecute fails to start

I have a registration system. The registration is working fine. My main problem is: I would like to start MainActivity.java after logging in. After sending the login data to the Server, the Server checks in Database if it matches and sends out an int (0 for unmatched) and (1 for success). This works great as well. But if i want to start the Intent after onPostExecute Method it gives out an Error:
FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.Activity.startActivityForResult
...
This is my StartPage which exectues my AsyncTask Class. And receives success or unmatched in the Method getLoginMessage().
public class LoginPage extends Activity {
String userName;
String password;
String sendProtocolToServer;
static String matched = null;
static String unmatched;
static Context myCtx;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loginpage);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Button login = (Button) findViewById(R.id.loginBtn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handleLogin();
}
});
Button register = (Button) findViewById(R.id.registerBtn);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent openMainActivityRegister = new Intent(
"com.example.fotosharing.REGISTERPAGE");
startActivity(openMainActivityRegister);
}
});
}
private void handleLogin() {
EditText editTextBox = (EditText) findViewById(R.id.EditTextUser);
EditText passwordTextBox = (EditText) findViewById(R.id.EditTextPassword);
userName = editTextBox.getText().toString();
password = passwordTextBox.getText().toString();
if (!userName.equals("") && !password.equals("")) {
sendProtocolToServer = "login" + "#" + userName + "#" + password;
ConnectToServer cts = new ConnectToServer(sendProtocolToServer);
cts.execute();
} else {
Toast.makeText(this, "Fill in Username and Password to login",
Toast.LENGTH_LONG).show();
}
}
public void getLoginMessage(String receivedMessage) {
if (receivedMessage.equals("success")) {
Intent openMainActivity = new Intent(
"com.example.fotosharing.TIMELINEACTIVITY");
openMainActivity.clone();
startActivity(openMainActivity);
}
if (receivedMessage.equals("unmatched")) {
Toast.makeText(this, "Password or username incorrect.", Toast.LENGTH_LONG).show();
}
}
}
This is my Async-Task class which receives Data from my Java-Server, and checks if it was an successful or an unmatched login. In onPostExecute im calling a Method in the LoginPage.class, which handles the Intent (here comes the Error).
public class ConnectToServer extends AsyncTask<Void, Void, String> {
public Context myCtx;
static Socket socket;
String sendStringToServer;
int protocolId = 0;
private static DataOutputStream DOS;
private static DataInputStream DIS;
StringBuffer line;
int j = 1;
String value;
static String res = null;
public ConnectToServer(String sendStringToServer) {
this.sendStringToServer = sendStringToServer;
}
public ConnectToServer(int i) {
this.protocolId = i;
}
public ConnectToServer() {
}
public ConnectToServer(Context ctx) {
this.myCtx = ctx;
}
protected String doInBackground(Void... arg0) {
try {
socket = new Socket("192.168.1.106", 25578);
DOS = new DataOutputStream(socket.getOutputStream());
if (protocolId == 1) {
DOS.writeUTF("pictureload");
protocolId = 0;
} else {
DOS.writeUTF(sendStringToServer);
}
res = receive();
// DOS.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("RES: " + res);
return res;
}
public String receive() {
String receiveResult = null;
if (socket.isConnected()) {
try {
BufferedReader input = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
DIS = new DataInputStream(socket.getInputStream());
int msg_received = DIS.readInt();
System.out.println("SERVER: " + msg_received);
if (msg_received == 1) {
receiveResult = "success";
System.out.println("IF (success): " + receiveResult);
}
if (msg_received == 0) {
receiveResult = "unmatched";
System.out.println("ELSE IF (unmatched): "
+ receiveResult);
}
} catch (IOException e) {
e.printStackTrace();
}
}
// ***** return your accumulated StringBuffer as string, not current
// line.toString();
return receiveResult;
}
protected void onPostExecute(String result1) {
if (result1 != null) {
if (result1.equals("success") || result1.equals("unmatched")) {
sendToLoginPage(result1);
}
}
}
private void sendToLoginPage(String result1) {
System.out.println("sendtologi " + result1);
LoginPage lp = new LoginPage();
lp.getLoginMessage(result1);
}
}
This is the class I want to start when it was a successful login.
What am I doing wrong?
public class MainActivity extends SherlockFragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
ActionBar actionbar = getSupportActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionbar.setBackgroundDrawable(new ColorDrawable(Color.BLACK));
actionbar.setStackedBackgroundDrawable(new ColorDrawable(Color.parseColor("#91d100")));
ActionBar.Tab Frag1Tab = actionbar.newTab().setText("Home");
ActionBar.Tab Frag2Tab = actionbar.newTab().setText("Share Photo");
Fragment Fragment1 = new TimelineActivity();
Fragment Fragment2 = new CameraActivity();
Frag1Tab.setTabListener(new MyTabsListener(Fragment1));
Frag2Tab.setTabListener(new MyTabsListener(Fragment2));
actionbar.addTab(Frag1Tab);
actionbar.addTab(Frag2Tab);
}
}
You cannot just create instance of your activity with new keyword, like this:
private void sendToLoginPage(String result1) {
System.out.println("sendtologi " + result1);
LoginPage lp = new LoginPage();
lp.getLoginMessage(result1);
}
This is wrong and it is probably why you are getting error. Code you posted is quite complex, so i am not sure if there are any other problems.
This is how it should be done:
So... Since you probably have ConnectToServer asyncTask in separate file, you need pass events or data to your LoginPage activity. For this purpose, you should use event listener, like this:
First, create interface that will represent communication between your ConnectToServer and your LoginPage.
public interface LoginResultListener {
public void getLoginMessage(String receivedMessage);
}
Now, make your LoginPage activity implement this interface:
public class LoginPage extends Activity implements LoginResultListener {
...
}
Now, update your ConnectToServer asyncTask, so that it uses LoginResultListener to communicate login result to your activity, like this:
public class ConnectToServer extends AsyncTask<Void, Void, String> {
private LoginResultListener listener;
...
public void setListener(LoginResultListener listener) {
this.listener = listener;
}
...
private void sendToLoginPage(String result1) {
System.out.println("sendtologi " + result1);
//THIS IS WHERE YOU DID WRONG
listener.getLoginMessage(result1);
}
...
}
Now finally, when you create new ConnectToServer async task from your activity, you need to set listener that will handle events when user logs in. Since you implemented this interface in your activity, you will send your activity object as listener parameter, see below:
ConnectToServer cts = new ConnectToServer(sendProtocolToServer);
// THIS IS IMPORTANT PART - 'this' refers to your LoginPage activity, that implements LoginResultListener interface
cts.setListener(this);
cts.execute();

Starting intent after Async task gets over

I created a login activity for my Android app. After the user enters the correct credentials, the login activity will switch over to the homepage but I don't know why my code won't switch and there is no error shown in my logcat. The manifest was also properly defined.
This is my login activity:
public class LoginEmployerActivity extends Activity {
Button btnLoginEmployer;
Button btnLinkToEmployerRegisterScreen;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
TextView forgotPassword;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_CNAME = "cname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private ProgressDialog pDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_employer);
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmployerEmail);
inputPassword = (EditText) findViewById(R.id.loginEmployerPassword);
btnLoginEmployer = (Button) findViewById(R.id.btnLoginEmployer);
btnLinkToEmployerRegisterScreen = (Button) findViewById(R.id.btnLinkToEmployerRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
forgotPassword = (TextView) findViewById(R.id.link_to_forgetPassword);
// Login button Click Event
btnLoginEmployer.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Checking for server respond
new LoginEmployer().execute();
}
}
});
// Link to Register Screen
btnLinkToEmployerRegisterScreen
.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterEmployerActivity.class);
startActivity(i);
finish();
}
});
// Link to forgot password link
forgotPassword.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Switching to forgot password screen
Intent i = new Intent(getApplicationContext(),
ForgotPasswordEmployerActivity.class);
startActivity(i);
}
});
}
// Background ASYNC Task to login by making HTTP Request
class LoginEmployer extends AsyncTask<String, String, String> {
// Before starting background thread Show Progress Dialog
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginEmployerActivity.this);
pDialog.setMessage("Authenticating...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
// Checking login in background
protected String doInBackground(String... params) {
runOnUiThread(new Runnable() {
public void run() {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
EmployerFunctions employerFunctions = new EmployerFunctions();
JSONObject json = employerFunctions.loginUser(email,
password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if (Integer.parseInt(res) == 1) {
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandlerEmployer dbe = new DatabaseHandlerEmployer(
getApplicationContext());
JSONObject json_user = json
.getJSONObject("user");
// Clear all previous data in database
employerFunctions
.logoutUser(getApplicationContext());
dbe.addUser(
json_user.getString(KEY_NAME),
//json_user.getString(KEY_CNAME),
json_user.getString(KEY_EMAIL),
json.getString(KEY_UID),
json_user.getString(KEY_CREATED_AT));
// Launch Employer homePage Screen
Intent homepage = new Intent(
getApplicationContext(),
HomepageEmployerActivity.class);
// Close all views before launching Employer
// homePage
homepage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homepage);
// Close Login Screen
finish();
} else {
// Error in login
loginErrorMsg
.setText("Invalid username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
// After completing background task Dismiss the progress dialog
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
EDITED CODE AFTER MOVING INTENT STATEMENT TO onPostExecute METHOD
public class LoginEmployerActivity extends Activity {
Button btnLoginEmployer;
Button btnLinkToEmployerRegisterScreen;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
TextView forgotPassword;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_CNAME = "cname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private ProgressDialog pDialog;
boolean loginVerify= false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_employer);
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmployerEmail);
inputPassword = (EditText) findViewById(R.id.loginEmployerPassword);
btnLoginEmployer = (Button) findViewById(R.id.btnLoginEmployer);
btnLinkToEmployerRegisterScreen = (Button) findViewById(R.id.btnLinkToEmployerRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
forgotPassword = (TextView) findViewById(R.id.link_to_forgetPassword);
// Login button Click Event
btnLoginEmployer.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Checking for server respond
new LoginEmployer().execute();
}
}
});
// Link to Register Screen
btnLinkToEmployerRegisterScreen
.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterEmployerActivity.class);
startActivity(i);
finish();
}
});
// Link to forgot password link
forgotPassword.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Switching to forgot password screen
Intent i = new Intent(getApplicationContext(),
ForgotPasswordEmployerActivity.class);
startActivity(i);
}
});
}
// Background ASYNC Task to login by making HTTP Request
class LoginEmployer extends AsyncTask<String, String, String> {
// Before starting background thread Show Progress Dialog
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginEmployerActivity.this);
pDialog.setMessage("Authenticating...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
// Checking login in background
protected String doInBackground(String... params) {
runOnUiThread(new Runnable() {
public void run() {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
EmployerFunctions employerFunctions = new EmployerFunctions();
JSONObject json = employerFunctions.loginUser(email,
password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if (Integer.parseInt(res) == 1) {
loginVerify = true;
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandlerEmployer dbe = new DatabaseHandlerEmployer(
getApplicationContext());
JSONObject json_user = json
.getJSONObject("user");
// Clear all previous data in database
employerFunctions
.logoutUser(getApplicationContext());
dbe.addUser(
json_user.getString(KEY_NAME),
json_user.getString(KEY_CNAME),
json_user.getString(KEY_EMAIL),
json.getString(KEY_UID),
json_user.getString(KEY_CREATED_AT));
} else {
// Error in login
loginErrorMsg
.setText("Invalid username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
// After completing background task Dismiss the progress dialog
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
if ( loginVerify == true )
{
// Launch Employer homePage Screen
Intent homepage = new Intent(getApplicationContext(),
HomepageEmployerActivity.class);
// Close all views before launching Employer
// homePage
homepage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homepage);
// Close Login Screen
finish();
}
}
}
}
You are calling the intent to start a new activity inside the doInBackgorund() which runs on a non-UI thread and the Activity needs to be run on a UI thread. That is why your Login activity is never stopped.
Put the code to go to the new activity inside onPostExecute() or onProgressUpdate().
Here is something you can do.
Declare a global variable loginVerfied = false;
When your doInBackground verifies that the authenticity of the user, make loginVerified = true , otherwise keep it false.
Then inside onPostExecute()
if(loginVerifed == true)
{
Intent homepage = new Intent(getApplicationContext(),HomepageEmployerActivity.class
homepage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homepage);
finish();
}
EDIT :
Also, you have declared class LoginEmployer extends AsyncTask<String, String, String>, so to call it you need to use new LoginEmployer.execute(""); (you are missing the double quotes and not passing any String to the Task so it does not match it's parameters).
The first parameter in the definition of the AsyncTask is the datatype of the value being passed to it when execute() function is called. The second parameter is the datatype related to displaying progress during the time when the background thread runs. And the third parameter specifies the return value of the result.
More about AsyncTask here.
So, here is what you need to do now.
Declare the Async Task like this.
class LoginEmployer extends AsyncTask<String, Void, String> and make a call to it by using new LoginEmployer.execute(""). Make sure to return null from your doInBackground().
Hope this solves your problem now!
Add a checker to your AsyncTask such as
// Background ASYNC Task to login by making HTTP Request
class LoginEmployer extends AsyncTask<String, String, String> {
boolean validUser = false;
Then once the user is validated inside your background task set the value to true
if (Integer.parseInt(res) == 1) {
// user successfully logged in
// Store user details in SQLite Database
validUser = true; //set valid to true
Now in postExecute check if the user is valid
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
if ( validUser )
{
Intent homepage = new Intent( LoginEmployerActivity.this,
HomepageEmployerActivity.class);
// Close all views before launching Employer
// homePage
homepage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homepage);
}
I don't think you have added the Intent code here that will help you switch to another Activity.
protected void onPostExecute(String file_url) {
// dismiss the dialog once done // Intent Code Missing.
pDialog.dismiss();
You should do a UI work in UI thread and Non-UI work in Non-UI thread, thats a rule from the arrival of HoneyComb version of android.
You have added the below code in doInBackground(), That should be in onPostExcute()
Intent homepage = new Intent( getApplicationContext(), HomepageEmployerActivity.class);
homepage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homepage);

Categories

Resources