Minimize application android - java

I wrote an application with login/logout logic.
After login(set user and pass as vars) the user can minimize the application.
Minimize code:
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
When user clicks on the app icon in first activity I check is have set user and pass as vars, if they are app go to activity 2(next activity).
if they are not set go to login interface.
Everything is working fine but sometimes the app forgets the user and pass after minimizing and I go to the login interface....
Is like clearing cache I don't know... help

In Android, you cannot assume that your application will be kept in memory when it goes to the background, and you cannot assume it stays on the foreground (people may press the Home key or popups may come up). You should implement the onPause and onResume events and store the details of the logged in user there. These methods are guaranteed to be called by Android whenever your application goes into the background and is re-activated, respectively. You can use the SavedBundle object that you get in these methods to store your data. Also read about the app lifecycle here: http://developer.android.com/reference/android/app/Activity.html

you should use sharedPreferance to store login user and password.
below is code
private void storeUserPreferences(String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putString("username", "xyz");
editor.putString("pass", "123");
editor.commit();
}
private void loadUserPreferences() {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
String pass =sharedPreferences.getString("pass","");
String username=sharedPreferences.getString("username","");
if(!TextUtils.isEmpty(pass)&&!TextUtils.isEmpty(username))
{
login.....success
}
else
{
redirect to login screen
}
}
this is ref doc http://developer.android.com/reference/android/content/SharedPreferences.html

Related

How to change starting activity in android studio?

Hello I am developing a simple project with android studio and I wanted to know how can I change the starting activity of the application via Java Code. I know how to do it with the androidmanifest.xml but I want the user to insert some data in the starting activity and then the next time the user loads the application the main activity pops up directly and not the starting activity again.
Thank you.
Use shared preference, with this you can save limited information. depending on what your user has selected you can save it and start an activity from it. the information remains even after the application is closed.
e.g. so you create a start activity that checks what settings have been selected and depending on that it starts the required activity with an intent.
search for shared preference and intent.
You should save a flag in Shared preference. For example in a first activity that launch save this:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "isNew");
editor.apply();
And when you want to Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String name = prefs.getString("name", "default value");//"default value defined" is the default value.
Then Check if (name == isNew) then start your MainActivity class

Android storing user ID after login

I was wondering what the best way is to store an user ID after logging the user in? I have just started Android Development, and have read about the Shared Preferences, but this does not seem to work?
This is happening in my LoginActivity:
User user = dbHelper.findUser(email);
SharedPreferences preferences = getSharedPreferences("preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_id", user.getId());
editor.commit();
Intent mainIntent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(mainIntent);
In my MainActivity I would like to obtain the logged in user's ID as follows:
SharedPreferences preferences = getSharedPreferences("preferences",
MODE_PRIVATE);
String user_id = prefs.getString("user_id", "0");
Now, I need this user id in order to build lists based on the user, so I do database queries with this ID. What's the best way to do pass on this ID? I could just pass it on with intents, but storing it somewhere central is preferable. I do need this ID in multiple activities.
Solved. Like user CommonsWare pointed out here, the value did not return the one I intended, therefore always choosing the default value from my SharedPreferences.

How to open not main activity when restart my application in android

I made an app worked in background using background service when the user clicked specific button (start button) , the user can stop the application task by restart this application and open it again .. then the user can stop the app by clicking on the stop button.
I use this code snippet to let the app close its UI and return to home screen and before that set the start button on disable mode ...
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Unfortunately, when I open my app again I start from the main activity which is not contains the start button and stop button and when I swipe to the second activity that contains the buttons I find the start button enabled i.e. the previous task of the background service is lost ??!!
could any one provide me by the solution.
Every time you open your app the buttons are enabled by default(excepting those which are disabled from the start).
So you need to saved this state to retain it's state.
Here
is how to retain and restore the state.
You have to take a look at Android application lifecycles, when your app goes to the background it will get to the state onPause() and later to onStop(), what you want is saving your application state for later use, take a look at this thread: Saving Activity state in Android I think the top answer is what you want to do.
You have to save the status of your button, and then load the status later.
You could use SharedPreferences to store your wanted activity.
Then check it right after MainActivity start, to decide change to new activity or not
//check when start app
public class MainActivity extends Activity{
public static SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
sharedpreferences = getSharedPreferences("WantedActivity", Context.MODE_PRIVATE);
if (sharedPreferences.contains("SavedActivityName"))
{
if(sharedPreferences.getString("SavedActivityName","").equals( "ActivityName"))
{
Intent intent = new Intent(getApplicationContext(), ActivityName.class);
startActivity(intent);
}
}
}
}
//save wanted activity
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("SavedActivityName", "ActivityName");
editor.commit();

Android save details screen

I am working on a small project that requires a details screen where the user inputs his details and they are permanently stored. The user must have the option to change the details as well if he needs to do so. I looked into the saved preferences library however it does not seem to offer such functionality.
To give a visual idea of what is required, something like this screen should be fine:
http://www.google.com.mt/imgres?start=97&num=10&hl=en&tbo=d&biw=1366&bih=643&tbm=isch&tbnid=aQSZz782gIfOeM:&imgrefurl=http://andrejusb.blogspot.com/2011/10/iphone-web-application-development-with.html&docid=YpPF3-T8zLGOAM&imgurl=http://2.bp.blogspot.com/-YRISJXXajD0/Tq2KTpcqWiI/AAAAAAAAFiE/-aJen8IuVRM/s1600/7.png&w=365&h=712&ei=rbX6ULTDCOfV4gTroIDoCg&zoom=1&iact=hc&vpx=834&vpy=218&dur=2075&hovh=314&hovw=161&tx=80&ty=216&sig=108811856681773622351&page=4&tbnh=155&tbnw=79&ndsp=35&ved=1t:429,r:4,s:100,i:16
Any help is much appreciated. Thanks in advance
You could easily use Shared Preferences to store user's details. Everytime the Preference screen is opened the stored data can then be extracted from the Shared Preferences and presented to the user for edit. ONce the edit is done the new data can be updated back in the the Shared Preferences.
Also look at this thread to see how this can be done.
Using SharedPreferences would be perfect for this kind of small amount of data which you want to store persistently.
// 'this' is simply your Application Context, so you can access this nearly anywhere
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
To obtain from the preferences:
// You can equally use KEY_LAST_NAME to get the last name, etc. They are just key/value pairs
// Note that the 2nd arg is simply the default value if there is no key/value mapping
String firstName = prefs.getString(KEY_FIRST_NAME_CONSTANT, "");
Or to save:
Editor editor = prefs.edit();
// firstName being the text they entered in the EditText
editor.putString(KEY_FIRST_NAME_CONSTANT, firstName);
editor.commit();
You can achieve such functionality using SharedPreferences Class in android.
public void onCreate(Bundle object){
super.onCreate(object);
// Initialize UI and link xml data to java view objects
......
SharedPreferences myPref = getPreferences(MODE_PRIVATE);
nameView.setText(myPref.getString("USER_NAME", null));
passView.setText(myPref.getString("PASSWORD", null));
}
public void onStop(){
super.onStop();
if (isFinishing()) {
getPreferences(MODE_PRIVATE).edit()
.putString("USER_NAME", nameView.getText().toString())
.putString("PASSWORD", passView.getText().toString())
.commit()
}
}

Save variable to use over classes

I want to pass strings to all pages in my android app. When the user logs in I save userName and others to strings. I want to send the strings over multiple pages. How can I do that?
I have tried to send it through Intent
Intent myIntent = new Intent(view.getContext(), Help.class);
myIntent.putExtra("userName", userNameString);
startActivityForResult(myIntent, 0);
But when I go to another page I dont want to keep sending the data through Intent every time.
I have tried to get it from the class where I parse and put them in strings
HomeScreen home = new HomeScreen();
String userName= home.userNameString;
But since i am creating a new instance of the HomeScreen then userNameString is null
Any help will be greatly appreciated
Beware of using a static or instance variable to hold this state as the memory state of an Android application can be in flux. Data only stored in memory can be destroyed without your knowledge if your application process is killed while in the background.
The simplest mechanism would be to persist your data into SharedPreferences that you can access from any place in the application. So, first you save the string that you get from login (this is called inside an Activity, FYI):
//Write the username string to preferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putString("userName", userNameString).commit();
Then elsewhere in your application (i.e. other Activity instances) can read that string:
//Read the username string
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String userName = prefs.getString("userName", "");
With SharedPreferences, your values are actually persisted, meaning they will live forever on disk and won't go away just because your application's memory is reset (this is usually an advantage, especially for login information). Because of this, you will also need to remove the string when your user "logs out" like so:
//Remove the username string from preferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().remove("userName").commit();
There are also methods like contains() to allow you to check if the value is currently saved (is the user logged in?), etc.
The calling Activity is not guaranteed to remain in memory... the Android system may destroy it at any time.
If the child Activity depends on the user name, then the correct means of passing the information is with an Intent.
Declare a static variable and use it from everywhere:
public class SomeClass
{
public static String userNameString;
}
Use it like:
Strign s = SomeClass.userNameString;
Change its value as:
SomeClass.userNameString = "new string";

Categories