How to pass a parameter through all activities? - android

I am developing a mobile application where I need the user object to be available through all the activities and I don't want to send it using the Intent from each activity to the other.
Can anyone help me please ?

If you could store it in:
SharedPreferences or
SQLite
I think the SharedPreferences would be much simpler to implement.
Here is an example, how you could create a static function, wich you can access from all your activities:
public class UserCreator
{
public static User getUser(Context context)
{
SharedPreferences prefs = context.getSharedPreferences("Name", Context.MODE_PRIVATE);
//Check if the user is already stored, if is, then simply get the data from
//your SharedPreference object.
boolean isValid = prefs.getBoolean("valid", false);
if(isValid)
{
String userName = prefs.getString("username", "");
String passWord = prefs.getString("password", "");
...
return new User(userName, passWord,...);
}
//If not, then store data
else
{
//for example show a dialog here, where the user can log in.
//when you have the data, then:
if(...login successful...)
{
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", "someusername");
editor.putString("password", "somepassword");
editor.putBoolean("valid", true);
...
editor.commit();
}
// Now, if the login was successful, then you can recall this function,
// and it will return a valid user object.
// if it was not, then it will show the login-dialog again.
return getUser(context);
}
}
}
And then from all your activites:
User user = UserCreator.getUser(this);

Just make that object 'public static'.
Then access it in other activities like:
PreviousActivity.userobj

Write a class which extends Application class. And put global parameters there. Those parameters will be valid in application context.

Related

How to manage Splash, Login and Main activity on android?

I'm new on android, I have 3 activities :
SplashActivity
LoginActivity
MainActivity
I need to navigate user to LoginActivity for first time then does the authenticate and go to MainActivity but For next time which has been authenticated already, I need to navigate the user to SplashActivity and then MainActivity.
Is it good practice if I remove the splash activity and set Login activity as luncher but hide all controls to display it as Splash Activity and show controls to display it as Login Activity?
thanks
You need to save user actions locally and manage your app behavior based on previous actions of your user. For saving data locally on user device, you can use either SharedPreferences or Database based on your needs. For using these I would suggest you read some tutorials on web.
Base on your needs I suggest you to use SharedPreferences.
You can use SharedPreferences for this purpose. During login keep the user name in SharedPreferences and check the status of SharedPreferences on next login onwards.
http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/
In your SplashScreen check if user is already authenticated using a flag in SharedPreferences
Use a worker thread to ensure some delay at splash-screen
in onCreate() of SplashScreen
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView("<Layout id>");
Thread navThread = new Thread() {
#Override
public void run() {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
navigateToHomeScreen();
}
};
navThread.start();
}
void navigateToHomeScreen(){
SharedPreferences preferences=c.getSharedPreferences("<Your pref name>", Context.MODE_PRIVATE);
if(preferences.contains("isAuthenticated")){
// Navigate to Main Activity
}else{
// Navigate to login Activity
}
finish();
}
In your login Activity once User is authenticated
SharedPreferences preferences=c.getSharedPreferences("<Your pref name>", Context.MODE_PRIVATE);
preferences.edit().putBoolean("isAuthenticated", true).apply();
// Navigate to Main Activity
Hints: Declare PrefName in some Constant file and access same wherever you want to access SharedPreferences.
my pscudo code:--- Once you do first time login please same userID and password
and next time you have to check it wheather all user id and password exit or not . In this way you can resolve it.
Save:--
SharedPreferences.Editor sqliteEditor= getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
sqliteEditor.putString("userID", "chay7an");
sqliteEditor.putInt("Password", sadasdas);
sqliteEditor.commit();
Retrive :--
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("userID", "");
int idName = prefs.getInt("Password", 0);
}

How to bypass intent extras in Android?

I want to know if there is a way to pass all the extras to the new intent.
Is it possible? And is it a good idea?
The reason is that I want to save the login state as a json string, and pass it in between Activities. I don't want to store data with SQLite or anything. Can I bypass all the intent extras to the new intent ?
please consider Shared Preference :
// Declaration
public static String KEY = "SESSION";
public static void saveUserName(String username, Context context) {
Editor editor = context
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
editor.putString("username", username);
editor.commit();
}
public static String getUserName(Context context) {
SharedPreferences savedSession = context.getSharedPreferences(KEY,
Activity.MODE_PRIVATE);
return savedSession.getString("username", "");
}
You can store the login credentials to preference and retrieve them as well in any of your activity.
SaveUsername("Your text to save", Your_activity.this);
And to retrieve the value
String mUserName = getUserName(YourActivity.this);
It is recommended to have all your preference methods in your utils class to keep the code organized.
You can read more here
yes you can use Shared Preference to save the Login session of user here is handy example of managing session using shared preference http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/ I used it earlier and suggest you to have a look at it.
Any of the two may help you.
Saving it in the sharedPreference file.
If you want them to be accessable throught the application you can use the applicationClass, like a global singleton.

how to store a text in one activity and retrieve it in another activity.?

I have created an app for alarm service..such that a person can set a alarm to a specific time and the alarm will pop up as a notification..Now i want to create that alarm service app to a task reminder app such a way that at the time of creating or setting the task , user input the message in the edit text and save it and then when the alarm pops up , and if the user taps the notification , a new activity comes up and the message that he typed earlier is printed in front of him..(i mean the message is show as a text view to him) So Please tell me how could i do that using shared preferences..
In simple way just tell how could a load the stored string from the activity where the string was created and save with the help of a button and to load that same string and pass it in a text view to some other activity..
You can use shared-preferences to store data in one activity. and these data will be available in any activity with in same application.
http://developer.android.com/reference/android/content/SharedPreferences.html
example is available at http://developer.android.com/guide/topics/data/data-storage.html
Good Luck.......
I would like to suggest you to do all your preference tasks in your Application Utils.clas
// Declaration
public static String KEY = "SESSION";
// Method declaration :
public static void saveUserName(String userid, Context context) {
Editor editor = context
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
editor.putString("username", userid);
editor.commit();
}
public static String getUserName(Context context) {
SharedPreferences savedSession = context.getSharedPreferences(KEY,
Activity.MODE_PRIVATE);
return savedSession.getString("username", "");
}
// You can save the values in preference by calling the below :
Utils.saveUserName("12345",YourActivity.this);
// Finally you can retrieve the stored value by calling this code snippet :
String myUserName = Utils.getUserName(YourActivity.this);
Hope it helps
You can use SharedPreferences.
Using setSetting, you can set the text at caller class. Similarly, you can get the text which was set in the caller class using getSetting in the called class.
Method to set the Preference-
public void setSetting(String key, String value) {
if(getActivity() != null)
{
SharedPreferences settings = getActivity().getSharedPreferences("UserPref", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
// Commit the edits!
editor.commit();
}
}
Method to get the preference-
public String getSetting(String key, String def) {
try
{
SharedPreferences settings = getActivity().getSharedPreferences("UserPref", 0);
return settings.getString(key, def);
}
catch(Exception e)
{
e.printStackTrace();
}
return "";
}
Here,
public abstract SharedPreferences getSharedPreferences (String name, int mode)
Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values. Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they will see each other's edits as soon as they are made.
More on Android developer reference.

How to keep information about an app in Android?

I want to know if its possible to keep information about an app in a while for example.
I have an app that access this file and get information about the choices that the user have made. For example:
I have a button for many events (event is a model), and i want to know if the user clicked in the button even after the application restarts.
I know that it is possible to keep information about login and password. Is possible to do something like this with other information?
Use Shared Preferences. Like so:
Create these methods for use, or just use the content inside of the methods whenever you want:
public String getPrefValue()
{
SharedPreferences sp = getSharedPreferences("preferenceName", 0);
String str = sp.getString("myStore","TheDefaultValueIfNoValueFoundOfThisKey");
return str;
}
public void writeToPref(String thePreference)
{
SharedPreferences.Editor pref =getSharedPreferences("preferenceName",0).edit();
pref.putString("myStore", thePreference);
pref.commit();
}
You could call them like this:
// when they click the button:
writeToPref("theyClickedTheButton");
if (getPrefValue().equals("theyClickedTheButton"))
{
// they have clicked the button
}
else if (getPrefValue().equals("TheDefaultValueIfNoValueFoundOfThisKey"))
{
// this preference has not been created (have not clicked the button)
}
else
{
// this preference has been created, but they have not clicked the button
}
Explanation of the code:
"preferenceName" is the name of the preference you're referring to and therefore has to be the same every time you access that specific preference. eg: "password", "theirSettings"
"myStore" refers to a specific String stored in that preference and their can be multiple.
eg: you have preference "theirSettings", well then "myStore" could be "soundPrefs", "colourPrefs", "language", etc.
Note: you can do this with boolean, integer, etc.
All you have to do is change the String storing and reading to boolean, or whatever type you want.
You can use SharedPreference to save your data in Android.
To write your information
SharedPreferences preferences = getSharedPreferences("PREF", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_Id",userid.getText().toString());
editor.putString("user_Password",password.getText().toString());
editor.commit();
To read above information
SharedPreferences prfs = getSharedPreferences("PREF", Context.MODE_PRIVATE);
String username = prfs.getString("user_Id", "");
In iOS NSUserDefaults is used to do the same
//For saving
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:your_username forKey:#"user_Id"];
[defaults synchronize];
//For retrieving
NSString *username = [defaults objectForKey:#"user_Id"];
Hope it helps.

Saving information after closing the app

I've been trying to create a user profile section for my app where the user enters his information (Name, DoB, height, weight etc) and clicks submit. After this he's taken to the main menu of the app.
The problem I have is that if I close the app and run it again, this will obviously result in the app displaying the user profile section again and asks the user to enter his information.
I've been trying to look for a way in which the app saves the information that the user enters and remembers it. So for example when the user first uses the app, he gets the user profile section and enters his information. When the user closes the app and opens it again it should take him straight away to the main menu.
I know I could achieve this slightly with Preferences, but I'd rather use a normal layout(LinearLayout) so that it gives me more options such as TextView etc.
Is there a way where I could achieve this using just LinearLayout instead of Preferences?
I've also been looking at creating custom Preferences, but none of the things I found was particularly useful.
Thanks in advance.
Use SharedPreferences.
Check the application for First Run and display layout which you want to enter user's profile.
After store boolean flag for first Run in shared Preference which will prevent your Profile Screen to display again.
Look at Check if application is on its first run
Update:
Put this FirstRun() code in your onCreate() of Main Activity.
private void FirstRun()
{
SharedPreferences settings = this.getSharedPreferences(MainActivity.PREFS_NAME, 0);
boolean firstrun = settings.getBoolean("firstrun", true);
if (firstrun)
{
// Checks to see if we've ran the application b4
SharedPreferences.Editor e = settings.edit();
e.putBoolean("firstrun", false);
e.commit();
// Display User Profile Screen
}
}
use sharedPreference to store information by this way..
final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
SharedPreferences.Editor editor = pref1.edit();
editor.putString("userid", "success");
editor.commit();
and to get the value from it use below code..
final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
String str1= pref2.getString("userid", null);
or try to use SqliteDatabase or may be Application Class..this will store the information as you want.
#Override
public boolean saveUserData(UserModel userModel, Context context) {
email = userModel.getEmail();
firstName = userModel.getFirstName();
lastName = userModel.getLastName();
twitterId = userModel.getTwitterId();
SharedPreferences userData = context.getSharedPreferences(APP_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor setUserDataPreference = userData.edit();
setUserDataPreference.putString(EMAIL, email);
setUserDataPreference.putString(FIRST_NAME, firstName);
setUserDataPreference.putString(LAST_NAME, lastName);
setUserDataPreference.putString(TWITTER_ID, twitterId);
setUserDataPreference.commit();
return true;
}
#Override
public UserModel getUserData(Context context) {
UserModel userModel = new UserModel();
SharedPreferences userData = context.getSharedPreferences(APP_NAME,
Context.MODE_PRIVATE);
email = userData.getString(EMAIL, "");
firstName = userData.getString(FIRST_NAME, "");
lastName = userData.getString(LAST_NAME, "");
twitterId = userData.getString(TWITTER_ID, "");
userModel.setEmail(email);
userModel.setFirstName(firstName);
userModel.setLastName(lastName);
userModel.setTwitterId(twitterId);
return userModel;
}

Categories

Resources