Functionality Description:
Image Button(calls on a secondary application) that allow users to enter and input text, handwritten as well as keyboard input. User will then have the option to save the text. When, user exit the secondary application, the image button is supposed to displayed the saved text.
Genuine Issue:
Have intended to use shared preferences method but the saved text is still not displayed. Can anyone please help. Following is the code used.
Code:
//EDITED VERSION TO CALL OUT THE SECONDARY APPLICATION FOR USER TO INPUT TEXTandr
private void addListenerOnButtonMyScript() {
// TODO Auto-generated method stub
imageButton = (ImageButton) findViewById(R.id.imageButton_myscript);
imageButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Log.i("SingleViewActivity:onCreate:addListenerOnButtonMyScript" + ":onKey" , "Initiate myScript:");
final Intent intent = new Intent();
intent.setClassName("com.visionobjects.textwidget.sample", "com.visionobjects.textwidget.sample.SampleActivity");
startActivity(intent);
SharedPreferences pref = getSharedPreferences(getString(R.string.pref_text),MODE_PRIVATE);
Log.i("Calling on Shared Preferences" , "Shared Preferences to pref_text:" + getString(R.string.pref_text) );
SharedPreferences.Editor editor = pref.edit();
editor.putString(getString(R.string.pref_text),"");
editor.commit();
}
});
}
//EDITED VERSION TO CALL ON SHARED PREFERENCES FUNCTION TO DISPLAY EDITED TEXT FROM MY_SCRIPT-20/10/2014
private void loadSavedPreferences(){
SharedPreferences pref = getSharedPreferences(getString(R.string.pref_text),MODE_PRIVATE);
SharedPreferences.Editor editor= pref.edit();
editor.commit();
}
Strings.xml
<resources>
<string name="app_name">SalesBase</string>
<string name ="pref_text">StandardPreferences</string>
<string name="contacts_default">Contacts Details\n名字:HARRY\n公司:BARTENDER\n路名:123, Road Name\nZip:Zip\nState:State\nMobile:012-345-6789\nOffice:12-345-678\n</string>
</resources>
You are using wrong code to load the data. If loadSavedPreferences() is your final code to get data then you will not get any data. Try this
private void loadSavedPreferences(){
SharedPreferences pref = getSharedPreferences(getString(R.string.pref_text),MODE_PRIVATE);
String data = prefs.getString(getString(R.string.pref_text), "");
}
However, I would suggest you to use different keys for preference name and the data you are trying to save.
SharedPreferences pref = getSharedPreferences(getString(R.string.pref_text),MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
Use a different key where you are saving the data in this line and obviously value is the data you want to save. Use something like this.
editor.putString(key,value);
editor.commit();
And when you want to show the data then use the same key to get the data.
String data = prefs.getString(key, "");
Have a look at this as well.
Android Shared preferences example
Related
I've been having issues understanding how to save and read SharedPreferences. I'm trying to save four separate SharedPreferences but as I couldn't figure out how to do it, I decided to try with a simple String.
In this code I'm trying to create and save a string in SharedPreferences
Button enrollNewStudent = (Button) findViewById(R.id.enrollStudentButton) ;
enrollNewStudent.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
SharedPreferences prefs = getSharedPreferences(getString(R.string.testing), MODE_PRIVATE);
SharedPreferences.Editor editor = getSharedPreferences(getString(R.string.testing), MODE_PRIVATE).edit();
editor.putString("name", "Dave");
editor.commit();
startActivity(new Intent(MainActivity.this, AddNewStudent.class));
}
});
And in this next part I'm trying to read the SharedPreferences and have a TextView set to it in a second activity.
Context context = this;
SharedPreferences sharedPref = getSharedPreferences(getString(R.string.testing),MODE_PRIVATE);
String toPutInTextView = sharedPref.getString(getString(R.string.testing), null);
TextView textView = findViewById(R.id.exampleTextView);
textView.setText(toPutInTextView);
When I run this app and click the button to switch to the second activity the TextView on the second activity is blank.
Does anybody see a problem with this? I've been trying to piece together what I need to do from the android developers website and from other questions here but I just cannot get this working. This is for a university project.
The problem is: sharedPref.getString(getString(R.string.testing), null) is pulling using the string getString(R.string.testing) as the key. However, the key you used when you called "putString()" was "name". So you need to use "name" as your key for your getString() call.
Try:
String toPutInTextView = sharedPref.getString("name", "<default_value>");
I need to send data Date Display to next Activity and keep that data
private void updateDisplay()
{
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(ShowdatanameActivity.this);
SharedPreferences.Editor editor = app_preferences.edit();
mDateDisplay.setText(new StringBuilder().append(mMonth + 1).append("-").append(mDay).append("-").append(mYear).append(" "));
editor.putString("key1", mDateDisplay);
editor.commit();
Intent myIntent = new Intent(ShowdatanameActivity.this,Showdata_result_resume.class);
startActivity(myIntent);
}
Well that's true you can acces to Data/Calendar object from every place of your application. But if you insist:
You've put your string to SharedPreferences under "key1" so in other activity you have to call:
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences("KEY_FOR_YOUR_DATA",ShowdatanameActivity.this);
String data = app_preferences.getString("key1","");
So when you call SharedPreferences you also need key for them. It's some kind of "database version", you can write anything there (i use for example PREFS-KEYv1, and when I need new one I'm incrementing to v2). And don't use same key everywhere it's bad practice.
The other method you could use to send your String to other activity is via intent.
intent.putExtra("key1",yourStringVariable);
and Showdata_result_resume in onCreate after setContent you can get it by:
String data = intent.getExtras().getString("key1");
Using code like this to make preferences code portable between various apps and classes.
from a fragment I get the sharedpref like this. Notice how I have the preferences named in a resource and I use getActivity to get to the preferences.
sharedPref = getActivity().getSharedPreferences(
getString(R.string.preferences), Context.MODE_PRIVATE);
From the main activity I get the sharedpref like this. Notice how I have the preferences named in a resource.
sharedPref = getSharedPreferences(getString(R.string.preferences),
Context.MODE_PRIVATE);
the resource which is shared by all classes in the app.
<string name="preferences">com.gosylvester.hilbilyfashliegt.prefrences</string>
<string name="about_firstrun">com.gosylvester.hilbilyfashliegt.firstrunabout</string>
now to get the data from any class I referer to it with an R string resource.
_Checked = sharedPref.getBoolean(getString(R.string.about_firstrun),
false);
Good Luck
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.
I have 27 characters that I want a player to unlock by beating scores, e.g. if his score is greater than 200 he unlocks character #1. I have a hard time trying to do that.
I have a class for characters that contains its number, the score required to unlock it, and a boolean to check if he is unlocked. But when it comes down to saving, I can't do that.
The main game loop is in file GameScreen. It has a value points counting the score.
When GameState changes to PlayerDead I want to check if any new character has been unlocked, and whether the high score has been beaten to save points.
Please help, I'm struggling with it for over a week and I can't find a good tutorial for SharedPrefs because all of them apply to GUI based activity that saves the name and surname you entered.
if you need sharedPrefs I can help you.
I can give some some example code.
or you can send your code and error if you get one, we update it.
but sharedPrefs is a good idea for that ? if user goes to application settings and clears data of your app, all data will be lost.
why dont you try create a sqlite databade, save it into assets directory and use it?
It's actually pretty simple, you use SharedPreferences to store key-value pairs. You can either call
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
From the GameScreen and then define a constant:
public static final String KEY_SCORE = "score";
To use as the key for the saving.
In order to actually save, you need an Editor:
SharedPreferences.Editor mEditor = mPrefs.edit();
//save data now, mPlayerScore is the score you keep track of
//if it's another type call putString(), etc
mEditor.putInt(KEY_SCORE, mPlayerScore);
//if that is the only thing you want for noe
//close and commit
mEditor.commit();
And in order to retrieve the saved score, during your onCreate() you can do:
public void getUserProgress() {
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
//no need for an editor when retrieving
mPlayerScore = mPrefs.getInt(KEY_SCORE, 0);
//second value passed was the default score
//if no score was found
}
In order to check for new character s being unlocked, you can call the following code after every game:
private void checkForUserUnlocks() {
if (mPlayerScore >= MyUnlockableCharacter.SCORE_NEEDED_TO_UNLOCK)
MyUnlockableCharacter.isUnlocked = true;
//and same for other unlockabld characters
}
There are other ways to access SharedPreferences, let me know if you need more info.
Use the below code to store and retrieve Score from SharedPreference.
public static void saveScore(Context context, int score){
SharedPreferences sharedPreferences = context.getSharedPreferences("YOUR_PACKAGE_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("SCORE", value);
editor.commit();
}
public static int loadScore(Context context){
SharedPreferences sharedPreferences = context.getSharedPreferences("YOUR_PACKAGE_NAME", Context.MODE_PRIVATE);
int score = sharedPreferences.getInt("SCORE", 0);
return score;
}
Read Sample;
public int Read() {
SharedPreferences mSharedPrefs = getSharedPreferences("FileName",
MODE_PRIVATE);
SharedPreferences.Editor mPrefsEditor = mSharedPrefs.edit();
int mCounter = mSharedPrefs.getInt("Counter", 0);
return mCounter;
}
Write Sample;
public void Write() {
SharedPreferences mSharedPrefs = getSharedPreferences("FileName",
MODE_PRIVATE);
SharedPreferences.Editor mPrefsEditor = mSharedPrefs.edit();
mPrefsEditor.putInt("Counter", 15);
mPrefsEditor.commit();
}
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;
}