how to avoid NPE with android activity [closed] - android

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);.

Related

Onetime login is not working and second time also showing LoginActivity in android

Hi in the below code I was implemented ontime login feature but it is not working with below code.If login is successful then it will redirecting to MainActivity.Next time want to skip login page directly it should show main activity.
SplashActivity.java:
final boolean needLogin = getIntent().getBooleanExtra("need login extra", true);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// This method will be executed once the timer is over
if(!needLogin) {
Intent i = new Intent(SplashActivity.this, MainActivity.class);
startActivity(i);
finish();
}else {
Intent i = new Intent(SplashActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
}
},
Once the login is successfull it will redirect to MAninactivity.java.Entire app I am using session.
LoginActivity.java:
if (response.isSuccessful()) {
Log.e("response", new Gson().toJson(response.body()));
LoginAndFetchModules loginAndFetchModules = response.body();
String success = loginAndFetchModules.getSuccess();
if (success.equals("true")) {
Results results = loginAndFetchModules.getResult();
//parse login details
GetLoginListDetails loginDetails = results.getLogin();
String userId = loginDetails.getUserid();
String sessionId = loginDetails.getSession();
String firstname = loginDetails.getFirst_name();
String lastname = loginDetails.getLast_name();
String mobile = loginDetails.getMobile();
String role = loginDetails.getRole();
String reportto = loginDetails.getReportto();
//parse modules
ArrayList<LoginListForModules> modules = results.getModules();
//parse module information
for (LoginListForModules module : modules) {
module_id = module.getId();
String name = module.getName();
String isEntity = module.getIsEntity();
String label = module.getLabel();
String singular = module.getSingular();
}
if (username.equals(username1.getText().toString()) && password.equals(password1.getText().toString())) {
// fetchUserJSON(sessionId,username);
Toast.makeText(getApplicationContext(), "Login Successfully", Toast.LENGTH_LONG).show();
i = new Intent(LoginActivity.this, MainActivity.class);
// loader.setVisibility(View.GONE);
progressDialog.dismiss();
// llProgressBar.setVisibility(View.GONE);
i.putExtra("sessionId", sessionId);
i.putExtra("module_id", module_id);
i.putExtra("username", username);
i.putExtra("firstname", firstname);
i.putExtra("lastname", lastname);
i.putExtra("mobile", mobile);
i.putExtra("role", role);
i.putExtra("reportto", reportto);
startActivity(i);
finish();
} else {
Toast.makeText(getApplicationContext(), "Invalid Username and Password", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), "Invalid Username and Password", Toast.LENGTH_LONG).show();
}
}
You can use SharedPreferences.
A SharedPreferences object points to a file containing key-value
pairs and provides simple methods to read and write them.
DEMO CODE
public class SharedPreferenceClass
{
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "Test";
public static final String KEY_SET_LOGIN_STATUS= "KEY_SET_LOGIN_STATUS";
public SharedPreferenceClass(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, 0);
editor = pref.edit();
}
public void setLoginStatus(String status)
{
editor.remove(KEY_SET_LOGIN_STATUS);
editor.putString(KEY_SET_LOGIN_STATUS, status);
editor.commit();
}
public String getLoginStatus()
{
String status= pref.getString(KEY_SET_LOGIN_STATUS, "");
return status;
}
}
Now you can store login status ( setLoginStatus("Login")) when ever login success And check your login status getLoginStatus(). If return "Login" then return to your desire activity.

unable to set a session

I am very new in android.In my app I make a login page.I use Shared Preferences for session.it works fine but a problem when i close my app and again open then login page comes.I want when user press logout button only that time login page will come.
this is my SharedPreferences class
public class SharedPrefManager {
//the constants
private static final String SHARED_PREF_NAME = "dreamzsharedpref";
private static final String KEY_USERNAME = "keyusername";
private static final String KEY_PHONE = "keyphone";
private static final String KEY_ID = "keyid";
private static SharedPrefManager mInstance;
private static Context mCtx;
private SharedPrefManager(Context context) {
mCtx = context;
}
public static synchronized SharedPrefManager getInstance(Context context) {
if (mInstance == null) {
mInstance = new SharedPrefManager(context);
}
return mInstance;
}
//method to let the user login
//this method will store the user data in shared preferences
public void userLogin(User user) {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(KEY_ID, user.getUserid());
editor.putString(KEY_PHONE, user.getUserphno());
editor.putString(KEY_USERNAME, user.getUsername());
editor.apply();
}
//this method will checker whether user is already logged in or not
public boolean isLoggedIn() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_PHONE, null) != null;
}
//this method will give the logged in user
public User getUser() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return new User(
sharedPreferences.getString(KEY_USERNAME, null),
sharedPreferences.getString(KEY_PHONE, null),
sharedPreferences.getInt(KEY_ID, -1)
);
}
//this method will logout the user
public void logout() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
mCtx.startActivity(new Intent(mCtx, LoginActivity.class));
}
}
this is my login method in login class
private void userLogin() {
//first getting the values
final String username = UsernameEt.getText().toString();
final String password = PasswordEt.getText().toString();
//validating inputs
if (TextUtils.isEmpty(username)) {
UsernameEt.setError("Please enter your username");
UsernameEt.requestFocus();
return;
}
if (TextUtils.isEmpty(password)) {
PasswordEt.setError("Please enter your password");
PasswordEt.requestFocus();
return;
}
//if everything is fine
class UserLogin extends AsyncTask<Void, Void, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(Void... voids) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();
//creating request parameters
HashMap<String, String> params = new HashMap<>();
params.put("vuserphno", username);
params.put("votp", password);
//returing the response
return requestHandler.sendPostRequest(URLs.URL_LOGIN, params);//this URLs is a class where URL_LOGIN is login url
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressBar.setVisibility(View.GONE);
try {
JSONObject obj = new JSONObject(s);
JSONArray array = obj.getJSONArray("user");
for (int i = 0; i < array.length(); i++) {
//getting the user from the response
JSONObject userJson = array.getJSONObject(i);
//creating a new user object
User user = new User(
userJson.getString("username"),
userJson.getString("userphno"),
userJson.getInt("userid")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
}
//starting the profile activity
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
UserLogin ul = new UserLogin();
ul.execute();
}
please tell me where is the problem and how I can solve this problem.
Thanks.
In your LoginActivity, check for login state and change activity, finish itself so it's clear from the back stack.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if (SharedPrefManager.getInstance().isLoggedIn(this)) {
startActivity(this, MainActivity.class);
finish();
return;
}
// ...
}

I want to store Register and Login information in shared preferences in android

I know there are n number of examples in android for shared preferences but I want to Register and store the info in shared preferences and in database using JSON. And then fetch data from JSON and Login with those credentials. If user is already logged in open Main Activity,else go to Splash screen and then open Login Activity. Please go through my detailed code :
RegisterActivity :
public class RegisterActivity extends AppCompatActivity implements ServerRequests.Registereponse {
private EditText password, phone, email;
public static EditText name;
ServerRequests serverRequests;
JSONParser jsonParser;
private Button registerButton;
TextView alreadyMember;
Editor editor;
UserSession session;
SharedPreferences sharedPreferences;
public static final String MyPREFERENCES = "MyPrefs";
public static final String Name1 = "nameKey";
public static final String Phone1 = "phoneKey";
public static final String Email1 = "emailKey";
public static final String Password1 = "passwordKey";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
jsonParser = new JSONParser();
serverRequests = new ServerRequests(getApplicationContext());
serverRequests.setRegistereponse(this);
alreadyMember = (TextView) findViewById(R.id.alreadyMember);
name = (EditText) findViewById(R.id.FName);
phone = (EditText) findViewById(R.id.PhoneNum);
email = (EditText) findViewById(R.id.mail);
password = (EditText) findViewById(R.id.password);
registerButton = (Button) findViewById(R.id.email_sign_in_button);
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CharSequence temp_emailID = email.getText().toString();
if (name.getText().toString().length() == 0) {
name.setError("Please enter your name");
name.requestFocus();
} else if (phone.getText().toString().length() == 0) {
phone.setError("Please enter your phone number");
phone.requestFocus();
} else if (!isValidEmail(temp_emailID)) {
email.setError("Please enter valid email");
email.requestFocus();
} else if (password.getText().toString().length() == 0) {
password.setError("Please enter password");
password.requestFocus();
} else {
try {
String Name = name.getText().toString();
String Email = email.getText().toString();
String Password = password.getText().toString();
String Phone = phone.getText().toString();
JSONObject obj = jsonParser.makeRegisterJson(Name, Email, Password, Long.parseLong(Phone));
Log.e("final Json", obj.toString());
serverRequests.register(obj);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Name1, Name);
editor.putString(Email1, Email);
editor.putString(Password1, Password);
editor.putString(Phone1, Phone);
editor.commit();
// Toast.makeText(RegisterActivity.this, "Registered Successfully!", Toast.LENGTH_LONG).show();
} catch (Exception e) {
}
}
// startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
}
});
alreadyMember.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
finish();
}
});
}
#Override
public void onRegsiterReposne(JSONObject object) {
Toast.makeText(RegisterActivity.this, "hiii" + object.toString(), Toast.LENGTH_SHORT).show();
}
public final static boolean isValidEmail(CharSequence target) {
if (TextUtils.isEmpty(target)) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
}
LoginActivity :
public class LoginActivity extends AppCompatActivity implements ServerRequests.Loginreponse {
private static final String PREFER_NAME = "Reg";
private Button email_sign_in_button;
private EditText email, password;
private TextView notMember, forgotPass;
UserSession session;
private SharedPreferences sharedPreferences;
ServerRequests serverRequests;
JSONParser jsonParser;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
jsonParser = new JSONParser();
serverRequests = new ServerRequests(getApplicationContext());
serverRequests.setLoginreponse(this);
notMember = (TextView) findViewById(R.id.notMember);
forgotPass = (TextView) findViewById(R.id.forgotPass);
notMember.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
finish();
}
});
forgotPass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ForgotPassword.class));
}
});
// get Email, Password input text
email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.pass);
// User Login button
email_sign_in_button = (Button) findViewById(R.id.login);
sharedPreferences = getSharedPreferences(PREFER_NAME, MODE_PRIVATE);
// Login button click event
email_sign_in_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
String Email = email.getText().toString();
String Password = password.getText().toString();
JSONObject obj = jsonParser.makeLoginJson(Email, Password);
Log.e("final Json", obj.toString());
serverRequests.login(obj);
} catch (Exception e) {
}
// startActivity(new Intent(LoginActivity.this, MainActivity.class));
// finish();
}
});
}
#Override
public void onLoginReposne(JSONObject object) {
Toast.makeText(LoginActivity.this, "helloo" + object.toString(), Toast.LENGTH_SHORT).show();
if (object.toString().contains("true")) {
Toast.makeText(LoginActivity.this, "Logged in..", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
}
}
SplashScreen :
public class SplashScreen extends Activity {
Thread splashTread;
SharedPreferences preferences;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
StartAnimations();
}
public void onAttachedToWindow() {
super.onAttachedToWindow();
Window window = getWindow();
window.setFormat(PixelFormat.RGBA_8888);
}
private void StartAnimations() {
Animation anim = AnimationUtils.loadAnimation(this, R.anim.alpha);
anim.reset();
LinearLayout l = (LinearLayout) findViewById(R.id.lin_lay);
l.clearAnimation();
l.startAnimation(anim);
anim = AnimationUtils.loadAnimation(this, R.anim.translate);
anim.reset();
ImageView iv = (ImageView) findViewById(R.id.splashImage);
iv.clearAnimation();
iv.startAnimation(anim);
/* TextView tv = (TextView) findViewById(R.id.splashText);
tv.clearAnimation();
tv.startAnimation(anim);*/
splashTread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
// Splash screen pause time
while (waited < 3500) {
sleep(100);
waited += 100;
}
startNextScreen();
} catch (InterruptedException e) {
// do nothing
} finally {
SplashScreen.this.finish();
}
}
};
splashTread.start();
}
private void startNextScreen() {
preferences = getSharedPreferences("TrainingApp", MODE_PRIVATE);
String userLoginStatus = preferences.getString("userLoginStatus", "no");
if (userLoginStatus.equals("no")) {
Intent intent = new Intent(SplashScreen.this,
LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
SplashScreen.this.finish();
} else {
Intent intent = new Intent(SplashScreen.this,
MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
SplashScreen.this.finish();
}
}
}
JSONParser class :
public class JSONParser {
//----------For Register
public JSONObject makeRegisterJson(String name, String email, String password, long phone) throws JSONException {
JSONObject object = new JSONObject();
object.put("name", name);
object.put("email", email);
object.put("password", password);
object.put("phone", phone);
// if its in array------
/*JSONObject finalObject=new JSONObject();
finalObject.put("request",object);
return finalObject;*/
return object;
}
//--------For Login--------------------------------------------------------
public JSONObject makeLoginJson(String Name, String password) throws JSONException {
JSONObject object = new JSONObject();
object.put("userName", Name);
object.put("password", password);
/*JSONObject finalObject=new JSONObject();
finalObject.put("request",object);
return finalObject;*/
return object;
}
}
ServerRequests class :
// ---------------- for register------------------------------------------------------------------------------
public void setRegistereponse(Registereponse registereponse) {
this.registereponse = registereponse;
}
private Registereponse registereponse;
public interface Registereponse {
void onRegsiterReposne(JSONObject object);
}
public void register(JSONObject jsonObject) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.REGISTER_URL, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.e("Json response", "" + response);
boolean b = response.getBoolean("success");
if (registereponse != null) {
registereponse.onRegsiterReposne(response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error ", "" + error);
}
}
);
queue.add(jsonObjectRequest);
}
// --------------For Login ---------------------------------------------------------------------------
public void setLoginreponse(Loginreponse loginreponse) {
this.loginreponse = loginreponse;
}
private Loginreponse loginreponse;
public interface Loginreponse {
void onLoginReposne(JSONObject object);
}
public void login(JSONObject jsonObject) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.LOGIN_URL, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.e("Json response", "" + response);
boolean b = response.getBoolean("success");
if (loginreponse != null) {
loginreponse.onLoginReposne(response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error ", "" + error);
}
}
);
queue.add(jsonObjectRequest);
}
UserSession class :
public class UserSession {
// Shared Preferences reference
SharedPreferences pref;
// Editor reference for Shared preferences
Editor editor;
// Context
Context _context;
// Shared preferences mode
int PRIVATE_MODE = 0;
// Shared preferences file name
public static final String PREFER_NAME = "Reg";
// All Shared Preferences Keys
public static final String IS_USER_LOGIN = "IsUserLoggedIn";
// 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";
// password
public static final String KEY_PASSWORD = "Password";
public static final String KEY_PHONE = "PhoneNumber";
public static final String KEY_QUALIFICATION = "Qualification";
// Constructor
public UserSession(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
editor = pref.edit();
}
//Create login session
public void createUserLoginSession(String uEmail, String uPassword) {
// Storing login value as TRUE
editor.putBoolean(IS_USER_LOGIN, true);
// Storing name in preferences
editor.putString(KEY_EMAIL, uEmail);
// Storing email in preferences
editor.putString(KEY_PASSWORD, uPassword);
// commit changes
editor.commit();
}
/**
* Check login method will check user login status
* If false it will redirect user to login page
* Else do anything
*/
public boolean checkLogin() {
// Check login status
if (!this.isUserLoggedIn()) {
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities from stack
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);
return true;
}
return false;
}
/**
* Get stored session data
*/
public HashMap<String, String> getUserDetails() {
//Use hashmap to store user credentials
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));
user.put(KEY_PASSWORD, pref.getString(KEY_PASSWORD, null));
user.put(KEY_PHONE, pref.getString(KEY_PHONE, null));
user.put(KEY_QUALIFICATION, pref.getString(KEY_QUALIFICATION, null));
// return user
return user;
}
/**
* Clear session details
*/
public void logoutUser() {
// Clearing all user data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to MainActivity
Intent i = new Intent(_context, LoginActivity.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);
}
// Check for login
public boolean isUserLoggedIn() {
return pref.getBoolean(IS_USER_LOGIN, false);
}
}
At the time of login successfull put this code:
prefs = getSharedPreferences("logindetail", 0);
SharedPreferences.Editor edit = prefs.edit();
edit.putString("userLoginStatus", "yes");
edit.commit();
At the time of logout use this:
prefs = getSharedPreferences("logindetail", 0);
SharedPreferences.Editor edit = prefs.edit();
edit.clear();
edit.commit();
And at the time of checking if user is login or not use below code:
Loginprefs = getApplicationContext().getSharedPreferences("logindetail", 0);
userLoginStatus = Loginprefs.getString("userLoginStatus", null);
if(userLoginStatus.tostring().equals("yes")){
//the user is login
}else{
//user is logout
}
Hope this helps you

How to Skip LauncherActivity and call another Activity when application start

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.

activity does not work as expected when it calls from an input method service

i have a activity about login twitter which works fine when i run it directly but when i call it from a input method service it does not work ...why? below is my activity code :
public class PostTwitter extends Activity {
private Button btnLogin;
/**
* Register your here app https://dev.twitter.com/apps/new and get your
* consumer key and secret
* */
static String TWITTER_CONSUMER_KEY = "CfyZdyVYFeZ34nlHkjjYmHiVk";
static String TWITTER_CONSUMER_SECRET = "QolQok2bKohLBwvctQHn1cvECQbrwWNjgrUxyoi6XgtSzHj1Gu";
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
private static final String PREF_USER_NAME = "twitter_user_name";
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample_3";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
// Shared Preferences
private static SharedPreferences mSharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post_twitter);
btnLogin = (Button) findViewById(R.id.btnLogoutTwitter);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
/**
* Twitter login button click event will call loginToTwitter() function
* */
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (isTwitterLoggedInAlready()) {
logoutFromTwitter();
} else {
new LoginNewUser().execute();
}
}
});
}
/**
* Function to update status
* */
class LoginNewUser extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try {
// Tell twitter4j that we want to use it with our app
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setDebugEnabled(true);
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
PostTwitter.this.startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(requestToken.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
return null;
}
}
#Override
protected void onResume() {
super.onResume();
Log.i("TAG", "Arrived at onResume");
dealWithTwitterResponse();
}
/**
* Twitter has sent us back into our app</br> Within the intent it set back
* we have a 'key' we can use to authenticate the user
*
* #param intent
*/
private void dealWithTwitterResponse() {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
// If the// user// has// just// logged// in
String oauthVerifier = uri.getQueryParameter("oauth_verifier");
Log.d("DEBUG", "loggged in");
new SaveTokenAfterLogin().execute(oauthVerifier);
// authoriseNewUser(oauthVerifier);
}
else
{
Log.d("DEBUG", "Not logged in");
}
}
/**
* Create an access token for this new user</br> Fill out the Twitter4j
* helper</br> And save these credentials so we can log the user straight in
* next time
*
* #param oauthVerifier
*/
class SaveTokenAfterLogin extends AsyncTask<String, Void, AccessToken> {
#Override
protected AccessToken doInBackground(String... oauthVerifier) {
// TODO Auto-generated method stub
// Log.d("DEBUG",oauthVerifier[0]);
try {
AccessToken at = twitter.getOAuthAccessToken(requestToken,
oauthVerifier[0]);
twitter.setOAuthAccessToken(at);
return at;
} catch (TwitterException e) {
// Toast.makeText(this,
// "Twitter auth error x01, try again later",
// Toast.LENGTH_SHORT).show();
}
return null;
}
protected void onPostExecute(AccessToken at) {
Log.d("DEBUG", "in post");
String token = at.getToken();
String secret = at.getTokenSecret();
Editor editor = mSharedPreferences.edit();
// editor.putString(PREF_ACCESS_TOKEN, token);
// editor.putString(PREF_ACCESS_TOKEN_SECRET, secret);
// editor.commit();
editor.putString(PREF_KEY_OAUTH_TOKEN, token);
editor.putString(PREF_KEY_OAUTH_SECRET, secret);
editor.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
// e.putString(PREF_USER_NAME, username);
editor.commit();
}
}
/**
* Check user already logged in your application using twitter Login flag is
* fetched from Shared Preferences
* */
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
/**
* Function to logout from twitter It will just clear the application shared
* preferences
* */
private void logoutFromTwitter() {
// Clear the shared preferences
Editor e = mSharedPreferences.edit();
e.remove(PREF_KEY_OAUTH_TOKEN);
e.remove(PREF_KEY_OAUTH_SECRET);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();
btnLogin.setText("Login");
Toast.makeText(getApplicationContext(), "Successfully LogOut",
Toast.LENGTH_SHORT).show();
}
//
}
and in my input method service i called it like this
twitter_post.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// Redirect to dashboard / home screen.
oneTouchPopupDialog.dismiss();
// make_twitter_post();
Intent i = new Intent(getBaseContext(), PostTwitter.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
activity is open but login does not work....any one know is there any additional code nedded which is called from service? thanks in advance

Categories

Resources