How to Skip LauncherActivity and call another Activity when application start - android

I have Splash Activity => Login Activity => Main Activity....
Once user Login My user Should redirect To the Main Activity Directly till LOGOUT.....
Give me a specific solution please...What to do in which Activity..
I am working with web services....suggest me if SQ Lite require or Shared-preference Or Session.Class.....
Please BE SPECIFIC ...what to do in which Activity/Class...
Before Login..
Splash Activity => Login Activity => Main Activity
I want flow after LOGIN like this..
Splash Activity =>Main Activity ....
Thank You in advance.....
SplashActivity.java
public class Splash extends Activity {
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
Thread timerThread = new Thread(){
public void run(){
try{
sleep(3000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
String sharedPrefId = "MyAppPreference";
SharedPreferences prefs = getSharedPreferences(sharedPrefId, 0);
boolean isLoggedIn = prefs.getBoolean("isLoggedIn", false);
if(isLoggedIn)
{
// Show Main Activity
Intent intent1= new Intent(Splash.this,SnetHome.class);
startActivity(intent1);
}
else
{
// Show Login activity
Intent intent2= new Intent(Splash.this,Login.class);
startActivity(intent2);
}
//if{
//if user redirect to LoginActivity
//Intent intent = new Intent(Splash.this,Login.class);
//startActivity(intent);
//}else{
//otherwise redirect to SnetHome activity
// }
}
}
};
timerThread.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
Login.java
public class Login extends AppCompatActivity implements OnClickListener {
private EditText user, pass;
private Button mSubmit, mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// php login script location:
// localhost :
// testing on your device
// put your local ip instead, on windows, run CMD > ipconfig
// or in mac's terminal type ifconfig and look for the ip under en0 or en1
// private static final String LOGIN_URL =
// "http://xxx.xxx.x.x:1234/webservice/login.php";
// testing on Emulator:
private static final String LOGIN_URL = "http://192.168.1.106/SnetWebservice/login.php";
// testing from a real server:
// private static final String LOGIN_URL =
// "http://www.mybringback.com/webservice/login.php";
// JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//toolbar
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
// setup input fields
user = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
// setup buttons
mSubmit = (Button) findViewById(R.id.login);
mRegister = (Button) findViewById(R.id.register);
// register listeners
mSubmit.setOnClickListener(this);
mRegister.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent inte = new Intent(Login.this, Register.class);
startActivity(inte);
}
});
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
break;
/* case R.id.register:
Intent i = new Intent(this, Register.class);
startActivity(i);
break;
*/
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
// save user data
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(Login.this);
Editor edit = prefs.edit();
edit.putString("username", username);
edit.commit();
prefs.edit().putBoolean("isLoggedIn", true).commit();
Intent i = new Intent(Login.this, SnetHome.class);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
} else if (success == 0) {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}

You can use SharedPreference for achieving this. You need to implement the logic in your SplashActivity. You need to check whether already logged in or not using the value stored in shared preference and show next activity based on that.
In your SplashActivity (Where you launch the login activity), add the logic like:
// Retrieving your app specific preference
String sharedPrefId = "MyAppPreference";
SharedPreferences prefs = getSharedPreferences(sharedPrefId, 0);
boolean isLoggedIn = prefs.getBoolean("isLoggedIn", false);
if(isLoggedIn)
{
// Show Main Activity
}
else
{
// Show Login activity
}
And in your LoginActivity, after successful login set the value to true:
prefs.edit().putBoolean("isLoggedIn", true).commit();

Like this
onCreate of Spalsh Activity
if(isLogin) //value comes from Shared Preference
{
Go to Main
}else
{
Go to Login
}

Use SharedPreference which will store a boolean variable as isUserLoggedIn if user has logged in then it will store true otherwise false and then check the value of SharedPreference at splash screen.

Related

after click back button in main activity it going to back to login ,HOW TO STOP TO GO LOGIN AGAIN

i am very new to android ,my login activity was working fine but my problem is after login in to my app sucessesfully go to main activity,after enter into my main activity when i press back button it will go to again login page please any one help me how to solve that
login.class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sharedpreferences = getSharedPreferences(mypreference, Context.MODE_PRIVATE);
String checkemail=sharedpreferences.getString("Email", "");
String checkuid =sharedpreferences.getString("Uid", "");
if (checkemail.length()>0 && checkuid.length()>0){
Intent main = new Intent(getApplicationContext(),MainActivity.class);
startActivity(main);
}
username =(EditText)findViewById(R.id.input_email);
password =(EditText)findViewById(R.id.input_password);
login =(Button)findViewById(R.id.btn_login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkvalid();
}
});
signup_link=(TextView)findViewById(R.id.link_signup);
signup_link.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent signup= new Intent(getApplicationContext(),SignUp.class);
startActivity(signup);
}
});
}
private void checkvalid()
{
uname =username.getText().toString();
upassword=password.getText().toString();
new AttemptLogin().execute();
if (username.length()==0 || password.length()==0)
{
Toast.makeText(getApplicationContext(), "Please enter all fields", Toast.LENGTH_LONG).show();
} else
{
uname =username.getText().toString();
upassword=password.getText().toString();
new AttemptLogin().execute();
}
}
class AttemptLogin extends AsyncTask<String, String, String>
{
/** * Before starting background thread Show Progress Dialog * */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args)
{
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("email",uname));
postParameters.add(new BasicNameValuePair("password",upassword));
System.out.println("?????????" + postParameters);
String response = null;
try
{
response = SimpleHttpClient.executeHttpPost(LOGIN_URL,postParameters).toString();
System.out.println("#################"+response);
}
catch (Exception e)
{
e.printStackTrace();
String errorMsg = e.getMessage();
}
return response;
} /** * Once the background process is done we need to Dismiss the progress dialog asap * **/
protected void onPostExecute(String response)
{
pDialog.dismiss();
try {
JSONObject jsonobject = new JSONObject(response);
status = jsonobject.getString("Status");
message = jsonobject.getString("Message");
if (message.equalsIgnoreCase("OK")){
JSONArray childArray = jsonobject.optJSONArray("Result");
if (childArray != null && childArray.length() > 0) {
for (int k = 0; k < childArray.length(); k++) {
JSONObject objj = childArray.optJSONObject(k);
uid = objj.getString("id");
user_name = objj.getString("user_name");
user_email = objj.getString("user_email");
user_status = objj.getString("status");
user_mobile = objj.getString("mobile_number");
System.out.println("AAAAAAAAAAAAAAAAAA"+user_name+user_email+user_mobile);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("Email", user_email);
editor.putString("Uid", uid);
editor.putString("Uname", user_name);
editor.putString("Status", user_status);
editor.putString("Mobile", user_mobile);
editor.commit();
Intent login= new Intent(getApplicationContext(),MainActivity.class);
startActivity(login);
}
}
else{
Toast.makeText(Login.this, "Registration Failed", Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
}
}
Whenever you don't want to load the previous activity on back press you should call finish() method after launching the new activity.
You need to finish() the login activity when login is successful.
Add
finish();
at the end of method startActivity();
You might have to add any condition as per your requirement.

How to pass a value through button to another activity in android code?

I have two class DashboardActivity.class and ProfileActivity.class,
In Dashboard class I would like to pass a value through button to ProfileActivity class. But it keep getting me error and the response JSON telling me that the 'Required field(s) is missing'. When I checked, the value from Dashboard didn't pass to ProfileActivity, that's why the response keep telling me 'Required filed(s) is missing'.
My, question is, How to pass a value through button to another activity. I already use this code :
btnLinkToProfile = (Button) findViewById(R.id.btnProfile);
btnLinkToProfile.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
//userFunctions.userProfil(INPUT_METHOD_SERVICE);
Intent i = new Intent(getApplicationContext(),ProfileActivity.class);
i.putExtra(KEY_NAME, name);
startActivityForResult(i,0);
}
But I get forced close when I try to run.
Here's the complete code of Dashboard Activity :
public class DashboardActivity extends Activity {
UserFunctions userFunctions;
Button btnLogout;
Button btnLinkToProfile;
private static final String KEY_NAME = "name";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Dashboard Screen for the application
* */
// Check login status di database
userFunctions = new UserFunctions();
if(userFunctions.isUserLoggedIn(getApplicationContext())){
// user already logged in show dashboard
setContentView(R.layout.dashboard);
//JSONObject json = jParserr.getJSONFromUrl(dashboardURL, "GET", params);
btnLinkToProfile = (Button) findViewById(R.id.btnProfile);
btnLinkToProfile.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
//userFunctions.userProfil(INPUT_METHOD_SERVICE);
Intent i = new Intent(getApplicationContext(),ProfileActivity.class);
i.putExtra(KEY_NAME, name);
startActivityForResult(i,0);
//startActivity(i);
//finish();
}
});
btnLogout = (Button) findViewById(R.id.btnLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
userFunctions.logoutUser(getApplicationContext());
Intent login = new Intent(getApplicationContext(), MainActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Keluar dari dashboard screen
finish();
}
});
}else{
// user is not logged in show login screen
Intent login = new Intent(getApplicationContext(), MainActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
}
}
And here's for ProfileActivity class :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
// Loading user Profile in Background Thread
new showUserProfile().execute();
}
///...
/**
* Background Async Task to Load user profile by making HTTP Request
* */
private class showUserProfile extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ProfileActivity.this);
pDialog.setMessage("Loading User Profile. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting user profile from url
* */
protected String doInBackground(String... args) {
//String name = name.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(profileURL, "GET", params);
/* UserFunctions userFunction = new UserFunctions();
if (params.length != 0)
return null;
JSONObject json = userFunction.userProfil(params[0]);
return json; */
// Check your log cat for JSON reponse
Log.d("User Profile: ", json.toString());
...
return null;
}
}
}
You are creating a new Intent in the Profile Activity.
You should actually use getIntent() to receive the intent the activity was called with.
That will return an intent object with your "name" extra.
EDIT: Actually, I can't tell precisely where you are trying to read the value sent from the Dashboard.
In ProfileActivity you should have
Intent intent = getIntent();
String name = intent.getStringExtra("name");
Then you can use the name from Dashboard in Profile.
Also look into implementing onNewIntent() for ProfileActivity.
EDIT: I edited your post to re-include where you call the AsyncTask. Notice your AsyncTask accepts a String parameter but you don't pass it one.
So do this in your ProfileActivity.onCreate():
Intent intent = getIntent();
String name = intent.getStringExtra("name");
new showUserProfile().execute(name);
Now in your doInBackground you should be able to get the name with args[0]
EDIT: Your AsyncTask should probably be:
private class showUserProfile extends AsyncTask<String, Void, Void>
Because you only accept the parameter, other don't use the progress or return values.
You are passing the extra properly, you just aren't retrieving it at all from your next activity.
Use Bundle var = getIntent().getExtras()
followed by
if(var != null){
myString = var.getString(KEY_NAME);
}

Android can not access web content even the login is successful

I have a problem loging in to our company webpage using my app that I coded. When I use the toast message it can tell if the login is successful or not. But when I insert the INTENT and moving to the next activity which will view the content of the webpage (after the successful login) I can only view the "LOGIN WEBPAGE" of the company, not the content. Correct code or addition to my code is highly appreciated. Thanks in advance.
Below are my codes:
This is our company's webpage: http://www.allianceinmotion.com/members.asp
LOGIN ACTIVITY:
package com.example.packagename;
imports ..... ;
public class LoginActivity extends Activity implements OnClickListener {
private ProgressDialog pDialog;
private static final String LOGIN_URL = "http://vo.aimglobalinc.com/control/con_login.asp";
JSONParser jsonParser = new JSONParser();
Boolean isInternetPresent = false;
private EditText user, pass;
private Button mSubmit, mRegister;
ConnectionDetector cd;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Intent i1 = getIntent();
i1.getExtras().getInt("login");
setResult(RESULT_OK, i1);
cd = new ConnectionDetector(getApplicationContext());
user = (EditText)findViewById(R.id.txt_username);
pass = (EditText)findViewById(R.id.txt_password);
mSubmit = (Button)findViewById(R.id.btn_login);
mRegister = (Button)findViewById(R.id.btn_register);
mSubmit.setOnClickListener(this);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
isInternetPresent = cd.isConnectingToInternet();
switch (v.getId()) {
case R.id.btn_login:
if (isInternetPresent) {
new AttemptLogin().execute();
}else {
Toast.makeText(LoginActivity.this, "This requires an internet connection.", Toast.LENGTH_LONG).show();
}
break;
case R.id.btn_register:
//Intent i = new Intent(this, RegisterActivity.class);
//startActivity(i);
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Attempting to login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
String username = user.getText().toString();
String password = pass.getText().toString();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uname", username));
params.add(new BasicNameValuePair("pword", password));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
Log.d("Login attempt", json.toString());
return json.getString("success");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
if (result.equals("true")) {
Toast.makeText(LoginActivity.this, "Login Successful!", Toast.LENGTH_LONG).show();
Intent i = new Intent(LoginActivity.this, MyAccounts.class);
finish();
startActivity(i);
} else {
Toast.makeText(LoginActivity.this, "Please enter the correct username and password.", Toast.LENGTH_LONG).show();
}
}
}
}
MYACCOUNTS ACTIVITY (where I suppose to access the content of the page after succeessful login)
package com.example.packagename;
imports ..... ;
public class MyAccounts extends Activity {
private WebView mWebView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
mWebView = new WebView(this);
mWebView.loadUrl("http://www.allianceinmotion.com/members.asp");
//mWebView.loadUrl("http://vo.aimglobalinc.com/r2bs.asp");
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
this.setContentView(mWebView);
}
#Override
public boolean onKeyDown(final int keyCode, final KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Using jsonlint.org, when i validate the URL from my LOGIN activity, here is the output:
{
"success": "failed",
"message": "Invalid username or password"
}

how to avoid NPE with android activity [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
i have my application where i am performing the log in functionality from the php site,i am able to getting login functionality done.
now to create user session i am using following code
sessionmanager.java
public class SessionManager {
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "dealnowsp";
// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_NAME = "name";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "email";
// Constructor
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
/**
* Create login session
* */
public void createLoginSession(String name, String userid){
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
// Storing email in pref
editor.putString(KEY_EMAIL, userid);
// commit changes
editor.commit();
}
/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything
* */
public void checkLogin(){
// Check login status
if(!this.isLoggedIn()){
Intent i = new Intent(_context, Login.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//Staring Login Activity
_context.startActivity(i);
}
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
// return user
return user;
}
/**
* Clear session details
* */
public void logoutUser(){
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
Intent i = new Intent(_context, MainActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
/**
* Quick check for login
* **/
// Get Login State
public boolean isLoggedIn(){
return pref.getBoolean(IS_LOGIN, false);
}
}
now my login activity is like
public class Login extends Activity {
Button home,login;
EditText uname,pword;
Context context;
SessionManager session;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getActionBar().setDisplayHomeAsUpEnabled(true);
uname = (EditText) findViewById(R.id.txtuserid);
pword = (EditText) findViewById(R.id.txtuserpass);
addListenerOnHome();
addListenerOnBtnlogin();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void addListenerOnHome() {
final Context context = this;
home = (Button)findViewById(R.id.btnhome);
home.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,MainActivity.class);
startActivity(intent);
}
});
}
public void addListenerOnBtnlogin() {
context = this;
login = (Button)findViewById(R.id.btnlogin);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final String username = uname.getText().toString();
final String password = pword.getText().toString();
if(username.trim().length() > 0 && password.trim().length() > 0){
Thread t = new Thread() {
public void run() {
postLoginData(username,password);
}
};
t.start();
}
else{
Toast.makeText(context, "username or password empty", Toast.LENGTH_SHORT).show();
}
}
});
}
private void postLoginData(String username,String password) {
try {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
Log.e("Response-->", "after httpclient");
HttpPost httppost = new HttpPost("http://10.0.2.2/dealnow/login.php");
Log.e("Response-->", "after httppost");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.e("Responce-->", "after using the list name pair");
// Execute HTTP Post Request
Log.w("SENCIDE", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
Log.e("Responce-->", "after execute the http response");
String str = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
if (str.toString().equalsIgnoreCase("true")) {
session.createLoginSession("dealnowsp", username); //here is where i am getting NPE even if i declare username variable at class level
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(context, "Login Successful...!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context,MainActivity.class);
startActivity(intent);
}
});
} else {
session.logoutUser();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(context, "Incorrect username or password", Toast.LENGTH_SHORT).show();
}
});
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
my question is that where to put the below line so that it works correctly
session.createLoginSession("dealnowsp", username)
You can put it anywhere after this.session = new SessionManager(this);.

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