Storing Preferences on a multi user app - android

I am developing an android application. It has two types of users, a teacher and a student. I was hoping to use Shared Preferences to communicate between the two users.
Basically, I have a teach screen which has four TextViews on it with different messages. The TextView text is set to "" when the toggle value is 1 (which is the default value).
On the student screen, they have 4 Buttons. Upon hitting each button, the toggle value is changed to 0 and then the message is displayed on the teacher's view. This works when I log in as a student, click the button, then log in as a teacher. However, I want it to work on two different devices, so that when the student clicks the button the teacher sees the message.
Here are some code snippets:
Firstly, the student activity:
Assistance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toggleAssistance(view);
}
});
public void toggleAssistance(View view){
SharedPreferences sharedPreferences = getSharedPreferences("requestToggles", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("assistanceToggle", 0);
editor.apply();
}
Secondly, the teacher activity:
asstToggle = sharedPreferences.getInt("assistanceToggle", 1);
if(asstToggle==1){
Assistance.setText("");
clearAssistance.setVisibility(View.GONE);
}
Clear assistance is just a button that basically does the reverse of toggleAssistance (it sets the value to 1). No need for this button to be displayed when the message isn't.
Can anyone provide assistance or advice in to how I can make this work between devices? Thanks!

No, you cannot use shared preferences to communicate between devices, your preferences values are stored locally on the device. You should use a remote data storage system like Firebase to implement a solution where two different devices are interacting with each other.

In the real professional world, What you develop in the android environment is considered a Front End.
To create a communication between 2 users(2 different android environments/machines), you need a back-end environment.
If you want to store data that can be accessed by 2 or more android users of different machines, you need the data stored in The "Back End". The most popular database system at the moment is MySQL.

Related

How to save Setting for next time?

I am working on my application and I want to change the color of their UI with the click of button.....Like this....
Button change=findViewById(R.id.change_UI);
change.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//My code to change the color of UI
//like blue to green-red-black etc (randomly)
}
The above things are working fine but when I again restart my application all things were same as I open it first time...with blue color UI.
I am new for development and i know this question is not so much interested but please help to solve this problem.
You should use SharedPreferences for this case. There is no problem for using it when you have more than 1 variable so don't worry.
Here is link to another answer how to use it properly: Android Shared preferences example
Another option could be creating one object which will hold all settings data and save it to a file and read it with every app run but for your case it would be overkill.
EDIT:
SharedPreferences data are stored in an XML file, a good practice would be not to store there more than 100kb. If you want to store something bigger you SQL database like Room or save yout data to file.
More information you can find here: Shared Preferences "limit" or in this answer https://stackoverflow.com/a/30638736/6329985
You can setup a preference activity as in here.

Saving texture with Preferences

So what Im trying to achive is: When the user purchases a new item (a texture) they can click a button to replace the old Item(texture) with the new one.
What got in my mind first was Objectmaps. So I created this:
ObjectMap<Integer, Texture> screenMap = new ObjectMap<Integer, Texture>();
Im only using two items at the moment just to get a hang of it:
screenMap.put(prefs.getInteger("stoneOne", 0), sdStone);
screenMap.put(prefs.getInteger("stoneTwo", 1), stone_3);
Here´s the methods I use to change the texture:
public void setStone1() {
stoneImage = new Image(screenMap.get(0));
}
public void setStone(int screenId) {
stoneImage = new Image(screenMap.get(screenId));
}
And now to the part I can figure out:
Preferences prefs = Gdx.app.getPreferences("preferences");
prefs.putString("textField", textField.getText());
prefs.putString("textArea", textArea.getText());
prefs.getInteger("stone", );
prefs.putInteger("stone", );
prefs.flush();
I have no Idea what Integer to put in there as you can see I even left it out right now. I tried the screenId integer but it´s not reachable since it is in a void? P.S never mind the weird names I got for things. I took some code from an old project.
Try to walk for another way.
Save Texture to sdcard.
Save path to file into preferences.
Preferences prefs = Gdx.app.getPreferences("preferences");
prefs.putString("texture_one_path", "/sdcard/tex1.jpeg");
prefs.putString("texture_two_path", "/sdcard/tex2.jpeg");
Sergey is right. Textures are heavy and big, and you could potentially have tons of them. That's meant for the SD card.
Preferences are lightweight, secure configuration files used on mobile devices. They're usually encrypted, too, so accessing them always has a cost. They're used usually for user settings, login information, etc. The Android extrapolation of Preferences is called SharedPreferences. Here's the doc: http://developer.android.com/reference/android/content/SharedPreferences.html
The iOS concept of "SharedPreferences" is called NSUserDefaults, and here's its page: https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/index.html
Bottom line: you shouldn't be saving much information to the preferences. Use it for strings, global values, user settings (volume level, user credentials, turn off gore, etc.) For large string data, use raws. For large media, use SD card.
Hope that helps.

How do I differentiate between 2 users using shared preferences?

I am trying to differentiate between 2 user id's using sharedpreferences so preferences saved by one should not be seen by the other logging on the same device.
I plan on doing something liek this:
Sharedpreferences.java
public boolean isDifferentUser() {
return mSharedPreferences.getBoolean(ISDIFFERENTUSER, false);
}
I want to see if I can apply some sort of logic such that
if(isdifferentuser){
dont save preferences
}
but I dont know how to differentiate between 2 users. They have 2 different user id's stored in database, how do I go about it?
Any pointers?
Thanks!

When to use getSharedPreferences vs savedInstanceState?

I'm trying to figure out when to use a saved instance state versus loading information from a shared preferences file. I have two variables that I wish to save, time and score. I want to make sure that if the user returns to the game screen that their score and time is saved and restored regardless if it's from onPause state or onStop.
I have three keys:
public static final String ARG_SCORE = "score";
public static final String ARG_TIME = "time";
public static final String SHARED_PREFS = "shared_preferences";
If the game is paused and a dialog is shown, when the user returns should I do
public void onRestoreInstanceState(Bundle savedInstanceState){
int score = savedInstanceState.getInt(ARG_SCORE);
}
or should I do something like:
protected void onResume(){
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int score = sharedPref.getInt(getString(R.string.saved_high_score));
}
Overall, I need help understanding the lifecycle and when to store vital information such as time and score of the game. I simply need to avoid the user having to restart in cases they weren't able to finish the game.
Lastly, I'm assumed that the sharedPrefs saves to an xml file. Is this correct? Does anyone have a sample xml for how my sharedPrefs should appear? Do keys which are saved to bundles of savedInstanceState get stored in xml files as well? If so, any examples? If not, where is the information stored?
THANKS!
edits:
ok cool beans. Thanks! One more question, when defining a key for a key-value pair stored into sharedPreferences such as
public static final String ARG_SCORE = "score";
why is the "score" string stored? When would this ever be used? I've always placed a value into the key_value pair using something like
args.putInt(ARG_TIMER, timerINT);
and retrieved using
scoreINT=savedInstanceState.getInt(ARG_SCORE);
Why is a name needed for the key ARG_SCORE? When would I need the name? Does it have to stay type String?
use saveInstanceState when you are frequently moving back and forth between activities and use SharedPreferences when you want to keep information for long time and yes sharedpreferences stored in an xml file. you can view using DDMS in eclipse.
Remeber, in saveInstanceState, when you close app mean it get removes from memory, information will also lost. And in SharedPreferences, information will remain there if you close your app.
It will depend on how you want to manage the data. Both options (and more) are feasible:
If you want to fill once and keep the data even if the app gets
killed, use SharedPreferences.
If it's volatile data that will have to be reentered differently some
other time (i.e., days later), then use onSavedInstanceState.
If you want to keep multiple datasets on the same device, then use a
SQLiteDatabase
You usually want to use SharedPreferences when you want to persist some information between different app session. Imagine you want to store information that you want to retrieve also after the user closes the app.
SavedInstanceState is used to keep some information while user is using the app and allow you to track temporary state of your activity or fragments.
Hope it helps.
when you press home button then still your activity remains in background. since there is some memory constraints in android , there is always chance some other application can take your memory. so to resume application from same point where we have left we use saveInstanceState.
we use sharedprefrence when we have to save small info(normally primitive type) like game high score in any game.
In the Android documentation says how to relate SharedPreferences to XML but there's no need to use SharedPreferences if you don't want the data to be stored forever, you can store the game's state using the Activitys lifecycle methods with no problem, but for example, if the user turns off it's phone or presses the back button to finish your Activity, then the savedInstanceState won't work and you will lose your data.
It's your call, if you want the game to be saved even if the user turns off his phone (I think this would be kinda radical, but if it's your requirement go ahead) then use SharedPreferences or a DB if it's complex data. If you want the game to be saved only when the user navigates in and out to your app, then it's safe to use the savedInstanceState.

How to Know the user has ever used the app

How can I know if the user has ever used my Android app on this device
before?
You can create these methods to manipulate SharedPreferences:
Keep in mind, there is no way to stop the user from clearing the app data and therefore deleting the SharedPreference.
public boolean hasUsed()
{
SharedPreferences sp = getSharedPreferences("hasUsed",0);
boolean b = sp.getBoolean("hasUsed",false); // default value is false
return b;
}
public void writeUsed(boolean b)
{
SharedPreferences.Editor editor = getSharedPreferences("hasUsed",0).edit();
editor.putBoolean("hasUsed", b).commit();
}
Call them like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// if user hasn't used the app, write to the preference that they have.
if (!hasUsed()) writeUsed(true);
// later in code:
if (hasUsed()) // if the user has used the app
{
// do something
}
}
Links for explanation of code:
How to store User name and password details in strings.xml
How to save app settings?
How to keep information about an app in Android?
If you store anything regarding it in your app,user is Owner of his device . he can clear it anytime.
Kindly store this information on either your server or use some analytics integration.
But I would prefer to store on server because in your case,analytics might be overhead for you as you just want to identify the existing users.
Explaination:
When your app starts, send device's unique id to your server, so that when user starts the app for next time,it will again send unique id and at that time your server can perform check in database for existance of recently received unique id.
In such a manner you can identify that the user has already used your app or not and then you can modify your business logic accordingly.
I hope it will be helpful !!
Check this : The Google Analytics SDK for Android makes it easy for native Android developers to collect user engagement data from their applications.
You can do things like :
The number of active users are using their applications.
From where in the world the application is being used.
Adoption and usage of specific features.
Crashes and exceptions.
In-app purchases and transactions.
https://developers.google.com/analytics/devguides/collection/android/
You can create a shared preference and can update a count value every time the user opens the app, like
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("Count",Integer.valueof(myPrefs.getString("Count", null))+1) );
the code may have errors but the logic is right

Categories

Resources