How to get the current userID on fragments, after you logged in - android

userLogin.class
try {
JSONObject obj = new JSONObject(response);
if(!obj.getBoolean("error")){
SharedPrefManager.getInstance(getApplicationContext())
.userLogin(
obj.getInt("id"),
obj.getString("firstname"),
obj.getString("lastname"),
obj.getString("s_id")
);
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
}else{
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"ERROR",Toast.LENGTH_LONG).show();
}
This is the code when you are trying to login.
How to put the current s_id to other activity like "FragmentActivity".
It should be like this. after you logged in, it will go to FragmentActivity also its should get the current user which the s_id.
I already put the code
Intent intentMainActivity = new Intent(LoginActivity.this, MainActivity.class);
intentMainActivity.putExtra("s_id", username);
startActivity(intentMainActivity);
But I don't know how to get in FragmentActivity, I tried
final String userID = getActivity().getIntent().getStringExtra("s_id");
I put in below the
private void fetchNewsFeedData() {
but still it doesn't work.
please help me solve this problem.
thank you.

In the login activity before going to main save the userid to shared pref
SharedPreferences prefs = this.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
//set value to pref
preferences.edit().putString("s_id", username.toString()).apply();
and get the data whenever you want
SharedPreferences preferences = this.getActivity().getSharedPreferences("MyPrefs", MODE_PRIVATE);
String id = preferences.getString("s_id", "default value");

Related

Skip past Android Activity if it was already seen [duplicate]

I have an activity that i only want to run when the application is ran for the first time.
And never again. It is a facebook login activity. I only want to launch it once when the app is initially opened for the first time.
How do i go about doing this?
What I've generally done is add a check for a specific shared preference in the Main Activity : if that shared preference is missing then launch the single-run Activity, otherwise continue with the main activity . When you launch the single run Activity create the shared preference so it gets skipped next time.
EDIT : In my onResume for the default Activity I do this:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean previouslyStarted = prefs.getBoolean(getString(R.string.pref_previously_started), false);
if(!previouslyStarted) {
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean(getString(R.string.pref_previously_started), Boolean.TRUE);
edit.commit();
showHelp();
}
Basically I load the default shared preferences and look for the previously_started boolean preference. If it hasn't been set I set it and then launch the help file. I use this to automatically show the help the first time the app is installed.
Post the following code within your onCreate statement
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
//show start activity
startActivity(new Intent(MainActivity.this, FirstLaunch.class));
Toast.makeText(MainActivity.this, "First Run", Toast.LENGTH_LONG)
.show();
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
Replace FirstLaunch.class with the class that you would like to launch
something like this might work.
public class MyPreferences {
private static final String MY_PREFERENCES = "my_preferences";
public static boolean isFirst(Context context){
final SharedPreferences reader = context.getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
final boolean first = reader.getBoolean("is_first", true);
if(first){
final SharedPreferences.Editor editor = reader.edit();
editor.putBoolean("is_first", false);
editor.commit();
}
return first;
}
}
usage
boolean isFirstTime = MyPreferences.isFirst(CurrentActivity.this);
if (isFirstTime) {
NewActivity.show(CurrentActivity.this);
}
...
public class NewActivity extends Activity {
public static void show(Context context) {
final Intent intent = new Intent(context, NewActivity.class);
context.startActivity(intent);
}
}
SharedPreferences dataSave = getSharedPreferences("firstLog", 0);
if(dataSave.getString("firstTime", "").toString().equals("no")){ // first run is happened
}
else{ // this is the first run of application
SharedPreferences.Editor editor = dataSave.edit();
editor.putString("firstTime", "no");
editor.commit();
}
I had done this without Shared Prefrence...as I know shared prefrence consumes some memory so I used public static boolean variable in global class....First I made Global Class Appconfig...and then I made boolean static variable like this :
public class Appconfig {
public static boolean activity = false;
}
then I used this public static boolean variable into my welcome Activity class. I am Using License agreement page. which I have to use only at once in my application then never display further whenever i run the application. so i had put condtion in welcome activity...if the welcome class run first time so the static boolean variable is false...
if (Appconfig.activity == false) {
Intent intent = new Intent();
intent.setClass(WelcomeActivity.this,LicesnceActivity.class);
startActivity(intent);
WelcomeActivity.this.finish();
}
if (Appconfig.activity == true) {
Intent intent = new Intent();
intent.setClass(WelcomeActivity.this, MainActivity.class);
startActivity(intent);
}
Now at Licesnce Activity class I made :
Appconfig.activity=true;
So whenever I run the Application the second activity "Main activity" run after Welcome activity not License Activity....
Declared in the globally
public int count=0
int tempInt = 0;
in your onCreate function past this code at first.
count = readSharedPreferenceInt("cntSP","cntKey");
if(count==0){
Intent intent = new Intent();
intent.setClass(MainActivity.this, TemporaryActivity.class);
startActivity(intent);
count++;
writeSharedPreference(count,"cntSP","cntKey");
}
Past these two method outside of onCreate
//Read from Shared Preferance
public int readSharedPreferenceInt(String spName,String key){
SharedPreferences sharedPreferences = getSharedPreferences(spName,Context.MODE_PRIVATE);
return tempInt = sharedPreferences.getInt(key, 0);
}
//write shared preferences in integer
public void writeSharedPreference(int ammount,String spName,String key ){
SharedPreferences sharedPreferences = getSharedPreferences(spName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, ammount);
editor.commit();
}
This is my code to bring the OnBoarding Activity for the first time. If it's not the first time then go directly to the Home Activity.
private void checkFirstOpen(){
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (!isFirstRun) {
Intent intent = new Intent(OnBoardingScreen.this, Home.class);
startActivity(intent);
finish();
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putBoolean("isFirstRun",
false).apply();
}

SharedPreferences returning null

I've created a class to save some username and password using the Android SharedPreferences, its seems that the methods for set both username and password are ok.
But everytime i try to get these, from within another activity or by just trying to print out the value i receiver nothing (if trying to print the value) or null (if trying to get on i activity).
Here is my code:
public class AuthPreferences {
private static final String KEY_USER = "userid";
private static final String KEY_PASSWORD = "mypassword";
private SharedPreferences preferences;
public AuthPreferences(Context context) {
preferences = context.getSharedPreferences("authoris", Context.MODE_PRIVATE);
}
public void setUser(String user) {
Editor editor = preferences.edit();
editor.putString(KEY_USER, user);
Log.v("MailApp", "User is " + user);
editor.apply();
if(editor.commit() == true) {
System.out.println("The user was set!");
}else{
System.out.println("The user was not set!");
}
}
public void setPassword(String pass) {
Editor editor = preferences.edit();
editor.putString(KEY_PASSWORD, pass);
Log.v("MailApp", "Password is " + pass);
editor.apply();
if(editor.commit() == true) {
System.out.println("The password was set!");
String mainUser = preferences.getString(KEY_PASSWORD, "456");
System.out.println(mainUser);
}else{
System.out.println("The password was not set!");
}
}
public String getUser() {
return preferences.getString(KEY_USER, "456");
}
public String getPassword() {
return preferences.getString(KEY_PASSWORD, "456");
}
Here is how i'm trying to get it:
preferences = new AuthPreferences(getActivity());
try {
String mainUser = preferences.getUser();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.v("App", "Could not get the user");
}
It is all because you use Activity as a context (you use result of getActivity() method as context). Since you got different activities you got different contexts so in result you are accessing different shared preferences files (XMLs). In other words you are writing to file A in activity A, and then read in activity B using file B as your source. This obviously is not going to work. To have this all work as you expect you shall always use the same context for data that you want to be accessed across many activities, in this case I recommend to use Application context. Technically, instead of calling getActivity() to get context in your fragment, you call getActivity().getApplicationContext() to get your application context, so you will be accessing the same shared preferences storage file, not matter what activity or fragment is doing that write or read.
Aside from this there's no need to call apply() and commit() as these two is kinda equivalent and do the same. Please check docs for more information.
Try replacing:
Editor editor = preferences.edit();
with
SharedPreferences.Editor editor = preferences.edit();
Then replace editor.apply(); with editor.commit();.
Instead of doing:
editor.apply();
do this:
editor.commit();
Also you need to commit your edits by using the methods somewhere:
AuthPreferences preferences = new AuthPreferences(getActivity());
preferences.setUser("USER_NAME");
preferences.setPassword("PASSWORD_VALUE");

How to do one time registration in android?

In my android application, I want to show the registration page only at the time of registration after that it will directly go to the main activity, doesn't go for registration page again if I open.
I did like this,It works but.
if I open my app and close it suddenly before registration process, the registration page didn't appear for the next time, without registration.
how can I avoid that.
How to write a condition to disappear the activity after the registration process.
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
if(pref.getBoolean("activity_executed", false)){
Intent intent = new Intent(this, Track.class);
startActivity(intent);
finish();
} else {
Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
}
Guys please help!
SharedPreferences _RegPref;
boolean _UserType = "";
You have to check shref pref before setcontentview method Like:
_RegPref = getApplicationContext().getSharedPreferences("LoginPref", 0);
_UserType = _RegPref.getString("REGISTERD", _UserType);
if (_UserType==true) {
try {
startActivity(new Intent(_ctx, YourActivity.class));
finish();
overridePendingTransition(R.anim.enter_new_screen, R.anim.exit_old_screen);
} catch (Exception e) {
e.printStackTrace();
}
}else {
set contentview("your register activity view");
}
after the registration is succesful, save the values in shred pref like:
Editor prefsEditor = _RegPref.edit();
_UserType = false;
prefsEditor.putString("REGISTERD", _UserType);
prefsEditor.commit();
you are in currect way, save sharedpreferences for this.
When user successfull register in your app, at that time save sharepreferences.
In onCreate method, if no sharepreferences found then forward to registration page.
Hi you can save sharedpreferences using bellow code.
This is the standard method for write shared preferences.
/**
* write SharedPreferences
* #param context
* #param name, name of preferences
* #param value, value of preferences
*/
public static void writePreferences(Context context,String name,String value)
{
SharedPreferences setting= context.getSharedPreferences("Give_your_filename", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=setting.edit();
editor.putString(name, value);
editor.commit();
}
Save your preferences.
Follow this link click here

shared preference is not created by the program

in the following program, what i am trying to do is:
i want to store a list of names in shared preference
when the app starts for the first time, it should create a shared preference by name "profile_names"
and subsequently , when the app starts for next times, it should check if the sharedprefernces is there or not
if it is present is should fetch the list from the preference and give it to the listview.
But it is not working ..... where have i gone wrong?
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.profilespage);
File f= new File("/data/data/neeraj.cardXchange.Basic/shared_prefs/profile_names");
if(f.exists()){
Toast.makeText(this, "prefernce already created", Toast.LENGTH_LONG).show();
profile_names= getSharedPreferences("profile_names", MODE_WORLD_READABLE);
try {
myarraylist = getArrayList(mycontext, key);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
Toast.makeText(this, "prefernce created now", Toast.LENGTH_LONG).show();
profile_names= getSharedPreferences("profile_names", MODE_WORLD_READABLE);
}
String [] name_list = myarraylist.toArray(new String[myarraylist.size()]);
ArrayAdapter adapter = new ArrayAdapter <String>(this, R.layout.textview, name_list);
setListAdapter(adapter);
}
here , i have used toast messages to keep a check on how things proceed
every time the toast message from my "else" gets executed and the shared preference is not created
i have checked it using DDMS.
You have to commit the created shared preference, first you have store values in shared preferences and then commit it so that I can retain values that can be used in other activities. here is small example to create and access shared preferences
To create:
SharedPreferences prefs = getSharedPreferences("UMSPreferences",MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("UserId", login);
editor.putString("password", password);
editor.commit();
to access
String userid = getSharedPreferences("UMSPreferences",MODE_PRIVATE).getString("UserId", login);
String paswrd = getSharedPreferences("UMSPreferences",MODE_PRIVATE).getString("password", password);

close previous Activity and open new activity on Item click

Hi everyone,
I have created a listview which is available on left side. On each item click opens new activity opens but when I traverse among listitems the new activity does not open after first attempt. I have closed the present activity in each case with finish() method. but it does not seems to work. here is code snippet ..let me know if anybody could help..appreciated
if (listname.equalsIgnoreCase("Time Table")) {
intent = new Intent(getApplicationContext(), TimeTable.class);
startActivity(intent);
Attendance.this.finish();
} else if (listname.equalsIgnoreCase("Announcements")) {
intent = new Intent(getApplicationContext(), Announcement.class);
startActivity(intent);
Attendance.this.finish();
}
I found the solution for my own problem, the issue was that I was not forwarding the some needed values to next activity such as userid, password etc. So I used SharedPreferences to pass the needed values on other activities. Here is example ..I hope it can be useful for others.
This is now created and committed shared preference
SharedPreferences prefs = getSharedPreferences("ABCPreferences",MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("UserId", login);
editor.putString("password", password);
editor.putString("IsInside", Inside);
editor.putString("UserType", "S");
editor.commit();
To access values through shared preference, It is simple
String listname = ((TextView)view).getText().toString();
String userid = getSharedPreferences("UMSPreferences",MODE_PRIVATE).getString("UserId", login);
String paswrd = getSharedPreferences("UMSPreferences",MODE_PRIVATE).getString("password", password);

Categories

Resources