I have a class to help me with handling back end requests; in this class I have a line to resolve my user object and also store the username locally:
public class BackEndHelper {
....
public static void Post_Login_async(user_username_pass_obj obj, final Context context) {
...
user_obj userObj = utilsJson.getUser_when_SignInUp(response.body().string(), context);
}
....
}
In the utilsJson.getUser_when_SignInUp I have the line to save the username:
public static void Write2SharedPref(Context context, user_obj userObj) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putString("username", userObj.getUsername())
.apply();
}
the above method breaks even if username is not null. My plan is to read this then in my MainActivity:
PreferenceManager.getDefaultSharedPreferences(context)
.getString("token", null);
Would you please let me know if my local read/write is ok to store some variables?
Thanks
Related
Is it possible to set a tenant id when the process definition itself is shared between multiple tenants?
I call this method where I get both id's from the http request which in turn I pass to the embedded process-engine
public void startInstance(String processDefinitionId, String tenantId) {
this.runtimeService.startProcessInstanceById(processDefinitionId);
}
But using this method I am not able to pass a tenant id to the process instance. How do I achieve this?
I found this reading: https://docs.camunda.org/manual/7.5/user-guide/process-engine/multi-tenancy/#instantiate-a-shared-definition but it does not really solve my problem since I get the tenant id from an http-header.
Thanks to the comment of Jan I figured out that one could add the tenant id as a variable to the started instance and retrieve it in the TenantProvider.
The code looks like this
runtimeService.createProcessInstanceById(processDefinitionId).setVariable("tenantId", tenantId).execute();
And on your TenantProvider simply get this variable like so
public class TenantProvider implements TenantIdProvider {
#Override
public String provideTenantIdForProcessInstance(TenantIdProviderProcessInstanceContext ctx) {
return (String) ctx.getVariables().get("tenantId");
}
#Override
public String provideTenantIdForCaseInstance(TenantIdProviderCaseInstanceContext ctx) {
return (String) ctx.getVariables().get("tenantId");
}
#Override
public String provideTenantIdForHistoricDecisionInstance(TenantIdProviderHistoricDecisionInstanceContext ctx) {
return (String) ctx.getExecution().getVariable("tenantId");
}
}
To enable the use of a TenantProvider, start your engine like so
ProcessEngine engine = new StandaloneProcessEngineConfiguration()
.setTenantIdProvider(new TenantProvider())
...
.buildProcessEngine();
I have an application with login screen, after the user is authenticated some "data" is retrieved from a database (username and privileges), until here everything is well.
After the login process I need to access to the privileges to generate some menus across different JavaFX scenes, this all throughout the entire application in any moment, but I donĀ“t know how to do it.
What I am looking for is a behavior such as SESSION variable in PHP (yep, I come from web development), which keeps information alive and accesible during a certain period of time (usually while user is logged in).
The information I have found about this topic is unclear and outdated, I mean, solutions that do not apply for JavaFX 2 or solutions with old design patterns.
I have created an image because in other forums I have found the same question but that is misunderstood, so I hope this could help.
Thanks to everyone.
You can use singleton design patter. For example:
public final class UserSession {
private static UserSession instance;
private String userName;
private Set<String> privileges;
private UserSession(String userName, Set<String> privileges) {
this.userName = userName;
this.privileges = privileges;
}
public static UserSession getInstace(String userName, Set<String> privileges) {
if(instance == null) {
instance = new UserSession(userName, privileges);
}
return instance;
}
public String getUserName() {
return userName;
}
public Set<String> getPrivileges() {
return privileges;
}
public void cleanUserSession() {
userName = "";// or null
privileges = new HashSet<>();// or null
}
#Override
public String toString() {
return "UserSession{" +
"userName='" + userName + '\'' +
", privileges=" + privileges +
'}';
}
}
and use the UserSession whenever you need. When you do login you just call: UserSession.getInstace(userName, privileges) and when you do log out: UserSession.cleanUserSession()
You can use the Java Preferences. At the first successful authentication, you need to write information about user in the Preferences like this:
Preferences userPreferences = Preferences.userRoot();
userPreferences.put(key,value);
And then take the data from the Preferences:
Preferences userPreferences = Preferences.userRoot();
String info = userPreferences.get(key,value);
you can put the user data into a local cache, such as Guava Cache.
for example, we use HashMap to store the user data:
class Session{ private HashMap<String,Object> store = new HashMap(); public static final Session INSTANCE = Session(); public void put(String key, Object value){ this.store.put(key,value); } public Object get(String key) { return this.store.get(key); } } in your controller: // call server side API to retrieve user User user = userApi.login(username,password); if(user != null){ Session.INSTANCE.put("USER",user); } // in other class User user = Session.INSTANCE.get("USER");
I have a basic understanding of java and android but am still new and am struggling to find the correct way to save a variable and be able to access it/read it from other classes/activities. I have seen singletons but I am confused if it is the right way and how it would look, also do I need to make sure its thread safe?
Is there a better way that I am unaware of?
Basically I have a login that gets a username and some info about that user. How can I save that to a class/singleton and access it later?
EDIT
after some more searching I found this example:
public class Drivers {
private static Array drivers;
public static void setDrivers(Array c){
drivers = c;
}
public static Array getDrivers(){
return drivers;
}
}
and get and set like this:
public class AnyClass {
{
int clicks = ActionClass.getDrivers();
ActionClass.setDrivers(0);
}
Would this work/be correct?
Create a Constant Class like :
public class Constant {
public static String USERNAME = "";
public static String PASSWORD = "";
}
Now, you can set this value in Activity1 like
Constant.USERNAME = "uname";
Constant.PASSWORD= "password";
Now, get this value in Activity2 like:
String u_name = Constant.USERNAME;
String pass = Constant.PASSWORD;
You can access this variables any where in your app.
And/or for Preference go to my this answer:Android. How to save user name and password after the app is closed?
You could use SharedPreferences (kind of a persistence layer). Or you could pass data through Intent.
You can use sharedPreferences
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("PASSWORD_KEY", mPassword);
editor.commit();
String s = sharedPreferences.getString("PASSWORD_KEY", ""); // get the saved string
I have two classes, one loggedIn, and a User class. In the loggedIn class I want to show the shared preferences that I made when the user logs in.
loginPrefs = getSharedPreferences("loginpreferences",Context.MODE_PRIVATE);
SharedPreferences.Editor loginEditor = loginPrefs.edit();
loginEditor.putString("userID", userIDCrypt);
loginEditor.commit();
Now i want to make in the user class a getID() method, that I can call the method from every class with User.getID();. How can I do this?
I need the userID in multiple classes, so I want one activity (called getID e.g.) that gives me the user ID.
try this in one Activity :
SharedPreferences sp;
SharedPreferences.Editor edit;
sp = getSharedPreferences("enter", MODE_PRIVATE);
edit = sp.edit();
edit.putString("name", username);
edit.putString("pwd", password);
edit.commit();
in next activity :
SharedPreferences sp = getSharedPreferences("enter", MODE_PRIVATE);
sp.getString("name", "default value"));
sp.getString("pwd", "default value"));
do like this make one class for your sharedpreference
public class Session {
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
public void setusename(String usename) {
prefs.edit().putString("usename", usename).commit();
prefsCommit();
}
public String getusename() {
String usename = prefs.getString("usename","");
return usename;
}
}
now after making this class when u want to use this use like this
make object og this class like
private Session session;//global variable
session = new Session(cntx); //in oncreate
and now we set sharedpreference then use this like
session.setusename("USERNAME");
now when ever u want to get username then same work for session object and call this
session.getusename();
best of luck :) same for password
Sorry if there is any syntax or compilation issues, just typing out of my head, and might make some mistakes. So in essence this is an approach that you can use to expose your prefs from one simple class and access it from any where.
public class MySharedPrefs {
public SharedPreferences sp;
public MySharedPrefs()
{
this.sp = c.getSharedPreferences("prefs", Context.MODE_PRIVATE);
}
public static String getStringFieldValue(Context c, String fieldName)
{
MySharedPrefs p = new MySharedPrefs(c);
return p.sp.getString(fieldName, "default value");
}
public static void setStringValue(Context c, String fieldName, String value)
{
MySharedPrefs p = new MySharedPrefs(c);
SharedPreferences.Editor edit;
edit = p.sp.edit();
edit.putString(fieldName, value);
edit.commit();
}
}
Then use it like this in your activity:
MySharedPrefs.getStringFieldValue(this, "name");
You can the also expand on this class and add additional helper methods such as a getUserName or etc.
UPDATE:
When calling this from another static class, that class needs to have a reference to your applications context, you then need to provide that context to this function instead of using this.
MySharedPrefs.getStringFieldValue(context, "name"); //if your other static class has a property called context that contains your applications context
I tried from this example
https://stackoverflow.com/a/9472019/485978
I have a service, this service just connects to the database directly and I put all data in a bean which is located inside this class.
public class ServiceApplication extends Application {
private static ServiceApplication mInstance;
public ServiceApplication() {
super();
}
public static ServiceApplication getInstance() {
return mInstance;
}
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
private Person personalData;
public Person getPersonalData() {
return personalData;
}
public void setPersonalData(Person personalData) {
this.personalData = personalData;
}
}
When retrieving a data from the database I used an AsyncTask where in doBackground() this is the code
ServiceApplication.getInstance().setPersonalData(personalData);
Log.d("AndroidService", "First name: "+ ServiceApplication.getInstance().getPersonalData().getFirstName());
So far it can retrieved the First Name.
However when I try to access those data from another activity all I get is null.
I tried two ways but it produces null
First implementation:
ServiceApplication app = (ServiceApplication) getApplication();
String name = (app.getPersonalData() != null) ? app.getPersonalData().getFirstName().trim() : "user";
Second implementation:
String name = (ServiceApplication.getInstance().getPersonalData() != null) ? ServiceApplication.getInstance().getPersonalData().getFirstName().trim() : "user";
Do you guys no how to persist the data and how to retrieve it from other activities?
If you are trying to pass data between a service and an activity you have to use another approach, as described here. If you just want to load Person data from a database into a singleton then you don't need to a Service. Just open a connection to the db, read the data and store it. Something like:
...
public Person getPersonalData() {
if(personalData == null) {
... open the db and load the data here ...
}
return personalData;
}
...
Note that only mInstance is static. It does not guarantee that you will receive the same personalData object. personalData could be and is definitely null in your case.
You might want to declare personalData as static as well.
private static Person personalData;
But in this case, you will reset the data on your next call to setPersonalData.
I would recommend you create a static structure as
private static ArrayList<Person> pList = new ArrayList<Person>();
Then in your setPersonalData() you can add objects to your pList.
You can replace your getPersonalData to return the pList. Hence you can use the same singleton instance from you activity to add data to the list and use the same to retrieve