Okay, check this source code:
public void checkSession() {
SharedPreferences session = getSharedPreferences(PREFS_NAME, 1);
String getSession = session.getString("SESSION", null);
Toast.makeText(this, getSession, Toast.LENGTH_SHORT).show();
if(getSession.length() > 30) {
Intent menu = new Intent(this, menu.class);
startActivity(menu);
finish();
}
else
{
}
}
The problem is that "first time users" get crush.
When I disable the function, run the app and login the code creates session. After that when I logout, and restart the app - there's no problem. Any ideas?
First time the app runs and you don't have a value stored in the SharedPreference "SESSION" you return null as your default value. The getSession().length will then result in a NullPointerException.
You should do like this instead:
String getSession = session.getString("SESSION", "");
If getSession is null, I think Toast.makeText will fall over.* You might want to change the default return to "" from null. getSession.length() won't work if getSession is null either.
*Apparently that isn't true -- see TofferJ's comment.
Related
I am developing my first networking application and have a small problem which I am unable to find a solution for.
On my startscreen, which is my main activity, there is the option to login. If you login, my login class passes data per intent to my main activity so I can update my UI. This is my main acitivity :
// Just to make sure Loginstatus is false on first run
loginstatus = false;
//Get saved data from SharedPreferences
loginstatus = PreferenceData.getUserLoggedInStatus(this);
Log.d("Loginstatus",""+loginstatus);
if (extras != null) {
login = extras.getString("loginy");
idt = extras.getString("id");
name = extras.getString("name");
vorname = extras.getString("vorname");
email = extras.getString("login");
zsm = vorname + " " + name;
}
else {
// Take saved Data instead the Bundle Data form first Login
idt = PreferenceData.getUSERID(this);
name = PreferenceData.getNachname(this);
vorname = PreferenceData.getVorname(this);
email = PreferenceData.getLoggedInEmailUser(this);
}
Obviously extra is NULL on Startup. If login was successful, my login class passes Data and my main activity is called again, so extras is NOT NULL and I can update my UI with that information.In addition, I save my Data in SharedPrefernces if login was true.
The Problem is, I want to save my login state after completley closing my app. So i reopen my App and I want to use my SharedPrefernces data, but somehow extras is still NOT NULL and I cant find a way to fix that.
This is how I handle login. Hope this is helpfully.
Login Activity
Keep one shared preferences value to check login status which default value set to false;
#Override
protected void onResume() {
super.onResume();
if (sharedpreferences.getBoolean("firstRun", true)) {
initializeDatabase();
sharedpreferences.edit().putBoolean("firstRun", false).apply();
sharedpreferences.edit().putBoolean("attendance", false).apply();
sharedpreferences.edit().putBoolean("loginStatus", false).apply();
}
loginCheck();
}
inside loginCheck() check method redirect to menu activity based on login status.
public void loginCheck(){
if(sharedpreferences.getBoolean("loginStatus", true)){
Intent i = new Intent(this, MainMenuActivity.class);
startActivity(i);
this.finish();
}
}
In case of User haven't log previously, after authenticate user successfully add needed data in to shared preference and change login status shared preference value to true so above explained redirect will happen.
if (message.equals("Login successful")) {
String employeeId = responseBody.getString("employee_id");
int userId = responseBody.getInt("user_id");
String employeeName = responseBody.getString("employee_name");
SharedPreferencesReference.get().edit().putString("employee_id", employeeId).apply();
SharedPreferencesReference.get().edit().putInt("user_id", userId).apply();
SharedPreferencesReference.get().edit().putString("employee_name", employeeName).apply();
SharedPreferencesReference.get().edit().putBoolean("loginStatus", true).apply();
Toasty.success(ActivityWeakReference.get(), message, Toast.LENGTH_SHORT, true).show();
Intent i = new Intent(ActivityWeakReference.get(), MainMenuActivity.class);
ActivityWeakReference.get().startActivity(i);
ActivityWeakReference.get().finish();
}
Menu Activity
In menu activity you should have a logout button which allow users to logout by changing shared preference login status value. In My case I had it as a Menu Item.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.logout:
sharedpreferences.edit().putBoolean("loginStatus", false).apply();
Intent intent = new Intent(this,MainActivity.class);
startActivity(intent);
break;
}
return true;
}
ive been trying to run this code, but the condition result never going to the else ,even when the value of my slat is 0.0
public void keLogin(){
if(slat.equals("0.0")) {
Toast.makeText(getBaseContext(),"pls wait until we know your location",Toast.LENGTH_LONG).show();
} else {
Intent keLogin = new Intent(getApplicationContext(), Login_Activity.class);
keLogin.putExtra("slat", slat);
keLogin.putExtra("slong", slong);
startActivity(keLogin);
}
}
public void keLogin(){
if(!slat.equals("0.0")) {
Toast.makeText(getBaseContext(),"pls wait until we know your location",Toast.LENGTH_LONG).show();
} else {
Intent keLogin = new Intent(getApplicationContext(), Login_Activity.class);
keLogin.putExtra("slat", slat);
keLogin.putExtra("slong", slong);
startActivity(keLogin);
}
}
If the salt is NOT a String variable: so you should convert it
and If it's a String variable:
Maybe your app don't change that variable
or that variable didn't achieve to "0.0"
In 1st option you must add some code for changing that value
In 2nd option you can must change "0.0" to an accessible value
Try using
if(slat.equalsIgnoreCase("0.0") { }
Might work.
I am attempting to verify if a user is logged in or not, and if not sending them to a log in page. I am using the log in page template from Android Dev. and trying to use an Intent to send either a Boolean or a value ( 1 for logged in 0 for not). Here is the part of the code in LoginActivity with the Intent:
for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
final boolean logged_in = true;
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("log", logged_in);
startActivity(intent);
}
here I am trying as a Boolean and I am getting the error Unreachable code for the line with final boolean Logged_in = true. When I try as an int
int logged_in =1;
I get the same error. All the questions asked on SO state that I needed to use the current class, LoginActivity.this, instead of just this. When I did use just this, I got another error entirely.
How do I send a value to my MainActivity class to show whether they are logged in or not?
return pieces[1].equals(mPassword);
return ends the method routine so everything after is not reachable.
I have a strange scenario here.
I have this code:
// For checking if the person is logged in.
first_time_check();
setContentView(R.layout.main);
// ...next lines of code
and the first_time_check() function checks if the user is logged in for the first time. If their user_id is not in the SharedPreferences, I redirect them to log in:
public void first_time_check()
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( ProblemioActivity.this);
String user_id = prefs.getString( "user_id", null ); // First arg is name and second is if not found.
String first_time_cookie = prefs.getString( "first_time_cookie" , null );
// About setting cookie. Check for first time cookie
if ( first_time_cookie == null )
{
// This user is a first-time visitor, 1) Create a cookie for them
first_time_cookie = "1";
// 2) Set it in the application session.
prefs.edit().putString("first_time_cookie", first_time_cookie ).commit();
// Make a remote call to the database to increment downloads number
// AND send me an email that it was a new user.
}
else
{
// If not first time, get their id.
// If user_id is empty, make them an account.
// If id not empty, call the update login date and be done.
if ( user_id == null )
{
// User id is null so they must have logged out.
Intent myIntent = new Intent(ProblemioActivity.this, LoginActivity.class);
ProblemioActivity.this.startActivity(myIntent);
}
else
{
// Make a remote call to the database to increment downloads number
}
}
return;
}
So after the code executes the
Intent myIntent = new Intent(ProblemioActivity.this, LoginActivity.class);
ProblemioActivity.this.startActivity(myIntent);
it still executes below the original code that calls this functions.
Any idea how that can happen?
Thanks!!
This is excerpted from the Dev Guide
Shutting Down an Activity
You can shut down an activity by calling its finish() method.
You can also shut down a separate activity that you previously
started by calling finishActivity().
Note: In most cases, you should not explicitly finish an activity
using these methods. As discussed in the following section about the
activity lifecycle, the Android system manages the life of an
activity for you, so you do not need to finish your own activities.
Calling these methods could adversely affect the expected user
experience and should only be used when you absolutely do not want
the user to return to this instance of the activity.
Calling finish() on the activity seems appropriate here as you do not want the user to return to this activity.
I'm trying to set up a dialog that will popup after the users updates or installs the application for the first time. I can't figure out how to exactly do this. Currently I have tried to use the package manager to get the users version and compare it to see if its the most recent. I'm uncertain if this will work as its hard to test for something that relies on a package update. Here is my code:
public void firstrun() {
String version = "";
String currenver = "3.9";
// update function
try {
PackageInfo manager = getPackageManager().getPackageInfo(
getPackageName(), 0);
version = manager.versionName;
} catch (NameNotFoundException e) {
// Handle exception
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putString(version, version).commit();
boolean firstrun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("firstrun", true);
if (version.matches(currenver)) {
// Save the state
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("firstrun", false).commit();
} else {
// Save the state
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("firstrun", true).commit();
}
if (firstrun == true) {
new AlertDialog.Builder(this)
.setTitle("Welcome!")
.setIcon(R.drawable.icondialog)
.setMessage("UpdateText")
.setNeutralButton("OK", null).show();
}
}
I think you are on the right track, there are many solutions here and here that may give you ideas.
In addition you could create a database table that contains a flag to prompt or not. By default it would be set to a value to prompt, and then once the user launches and acknowledges the dialog you could change the flag. Then in your onUpgrade() method of your SQLiteOpenHelper you could flip the flag again, and thus your application would prompt on installation of a new version.