My EditTextPreference is this:
<EditTextPreference
android:title="Name"
android:summary="namepreferences"
android:inputType="text"
android:dialogTitle="name"
/>
in my PreferencesActivity:
namePref = (EditTextPreference)getPreferenceManager().findPreference("namepreferences");
well so far no problem.. now, i have a service with a notification. My goal is pass the namePref value in the Title of the notification.. I wrote this in the service:
SharedPreferences sp = PreferenceManager.getDefaultPreferences(this);
String name;
#Override
public void onCreate() {
name = sp.getText("namepreferences", "NA");
}
and i insert name in the title of notification but the app crashes sayng that name is null.. I can't solve..
Change to
SharedPreferences sp;
String name;
#Override
public void onCreate() {
super.onCreate();
sp = PreferenceManager.getDefaultPreferences(getApplicationContext());
name = sp.getText("namepreferences", "NA");
}
Related
I don't understand how preferences work.
I have a preferences activity and one field on it:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference
android:key = "#string/pr_rest_service_url"
android:title = "#string/rest_service_url"
android:summary = "%s"
android:shouldDisableView="false"
android:selectable="true"
android:enabled="true"
android:defaultValue="543543543"
/>
</PreferenceScreen>
In preference activity i use this code to edit it:
public class SettingsActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
String editTextPrefKey = getString(R.string.pr_rest_service_url);
EditTextPreference restUrlTExtEdit = (EditTextPreference) findPreference(editTextPrefKey);
restUrlTExtEdit.getEditText().setInputType(InputType.TYPE_CLASS_TEXT);
restUrlTExtEdit.setSummary(restUrlTExtEdit.getText());
restUrlTExtEdit.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
preference.setSummary(newValue.toString());
return true;
}
});
Preference saveButton = findPreference(getString(R.string.preference_save_button));
saveButton.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
finish();
return true;
}
});
}
}
And its works. Works nice.
Now i want to get preferense from another parts of application. I put this code in MainActivity:
String key = this.getString(R.string.pr_rest_service_url);
SharedPreferences mSharedPreferences = getSharedPreferences(key, Context.MODE_PRIVATE);
String g = mSharedPreferences.getString(key, null);
And got null.
So how gonna work with preferences?
Or i made mistake on ths start and should not use PreferenceActivity as settings screen? Or preferenses binded to activity?
So how can i get
UPDATE
I tried
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String name = sp.getString("myKey", "");
But got empty string.
Update: Use this then:
SharedPreferences yourOutputdata =
context.getSharedPreferences("YourKEY", MODE_PRIVATE); // Save as YourKEY in the Activity which you're passing data to this one ...
Because of this:
String key = this.getString(R.string.pr_rest_service_url);
You are actually getting string from resource file and saving it to preference which I believe this causes the null.
Try this:
To save:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("key","your text-data here");
editor.apply();
And to get:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("key", "");
🚩Get Android Shared Preferences from default shared preferences in java language:-
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
sharedPreferences.getString("your_key", null);
Hope this works...😊
i have successfully implemented a calculator with a history activity in which it will show old results in a list view
but i am facing a problem that the first line is always null
https://imgur.com/a/jvXms
i tried to make default string " Old Calculation "
> String w = "Old Calculation";
but this didn't work,
my app save the result in a multiline String in SharedPreferences and pass it to another activity through an intent
>SharedPreferences.Editor editor ; // saving shared preferences editor as MainAcitivty class attribute
under the onCreate i set the String value to sharedpref
> SharedPreferences prefs = getPreferences(MODE_PRIVATE);
w = prefs.getString("saved", null);
update method in which i update the result string value with the String s( String s is the calculated result)
> public void update(String s){
editor= getPreferences(MODE_PRIVATE).edit();
w = w
+ System.getProperty ("line.separator")
+ s
+ System.getProperty ("line.separator");
editor.putString("saved", w);
editor.apply();
}
Passing W value to the activity in which i will show the result in TextView list
> public void History(View v){
Intent myIntent = new Intent(MainActivity.this, History.class);
myIntent.putExtra("message", w);
startActivity(myIntent);
overridePendingTransition(R.anim.anim_slide_in_left,
R.anim.anim_slide_out_left);
}
History activity
public class History extends AppCompatActivity {
TextView tv1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
String w ="Old calculation is showed here";
tv1 = (TextView) findViewById(R.id.tv1);
print(w);
}
public void print(String w) {
Bundle bundle = getIntent().getExtras();
w = bundle.getString("message");
tv1.setMovementMethod(new ScrollingMovementMethod());
tv1.setText(w);
}
#Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.anim_slide_in_right, R.anim.anim_slide_out_right);
}
public void deleteAppData(View v) {
try {
// clearing app data
String packageName = getApplicationContext().getPackageName();
Runtime runtime = Runtime.getRuntime();
runtime.exec("pm clear "+packageName);
} catch (Exception e) {
e.printStackTrace();
}
}
}
when you store data from activity A and you want retrieve it from another activity, You must use SharedPreferences as below:
SharedPreferences prefs = getSharedPreferences(String, int);
String is FileName like "result"
int is Mode like MODE_PRIVATE
for example see this link
in addition i wrote a simple code for help you
I am making an app that uses twitter digits, and I was wondering if there is a way to use it without using the ugly twitter digits button that says "use my phone number"
You have to modify the button programmatically, using xml won't work. For example:
digitsButton.setText("Your text here");
digitsButton.setBackgroundColor(getResources().getColor(R.color.primary));
You can use your own button and just call Digits.authenticate()
final AuthCallback digitsCallback = new AuthCallback() {
#Override
public void success(DigitsSession session, String phoneNumber) {
// Do something on success
}
#Override
public void failure(DigitsException exception) {
// Do something on failure
}
};
findViewById(R.id.myButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Digits.authenticate(digitsCallback);
}
});
Try this the OnClickListener of your custom button:
AuthConfig.Builder builder = new AuthConfig.Builder();
builder.withAuthCallBack(new AuthCallback() {
#Override
public void success(DigitsSession session, String phoneNumber) {
Toast.makeText(getApplicationContext(), "Authentication successful for "
+ phoneNumber, Toast.LENGTH_LONG).show();
// Do something
}
#Override
public void failure(DigitsException error) {
// Do something
}
});
AuthConfig authConfig = builder.build();
Digits.authenticate(authConfig);
By now you even got an answer. But just in case, most easy way to customize the DigitsAuth Button would be following below:
Create a new background image and name it as dgts__digits_btn.png ==> this would replace the bg image of digiAuth button.
Change padding around the DigitsAuthButton button by adding tw__login_btn_drawable_padding attribute in dimens.xml
Change default DigitsAuthButton button text by adding string entry with name "dgts__login_digits_text" in strings.xml
Change text size by adding "tw__login_btn_text_size" in dimens.xml
DigitsAuthButton Button padding by adding "tw__login_btn_right_padding" and dimens.xml
Hope this helps.
using Android Data Binding library
XML file
<layout xmlns:android="http://schemas.android.com/apk/res/android" >
<data>
<variable
name="viewModel"
type="package.DigitsViewModel" />
</data>
...
<com.digits.sdk.android.DigitsAuthButton
...
android:text="#{viewModel.mDigitsButtonText}"
android:background="#{viewModel.mDigitsButtonDrawable}" />
</layout>
DigitsViewModel file
public final ObservableField<String> mDigitsButtonText = new ObservableField<>();
public final ObservableField<Drawable> mDigitsButtonDrawable = new ObservableField<>();
mDigitsButtonText.set("Your text here");
mDigitsButtonDrawable.set(ContextCompat.getDrawable(mContext, R.drawable.some_drawable));
I'm in the middle of making an app and I'm running into a road block.
Basically I have a checkbox... If the checkbox is checked, it is supposed enable the entry of text in an edit text preference, and use that value. But here's where the problem lies... If the box is unchecked it uses the value in the EditTextPreference. If the box is checked, it uses the hard coded value.
Part of my activity:
private void loadURI()
{
PreferenceManager.setDefaultValues(this, R.xml.settings, true);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
if (settings.getBoolean("default_uri", false)){
String defaultURI = getString(R.string.dream_uri);
this.mWebView.loadUrl(defaultURI);
}
else {
String customURI = settings.getString("custom_uri", "");
this.mWebView.loadUrl(customURI);
}
}
Settings.xml:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Backdrop Settings" >
<CheckBoxPreference
android:title="Use Custom Backdrop URL"
android:id="#id/checkBox1"
android:key="default_uri"
android:defaultValue="true"/>
<EditTextPreference
android:title="Custom Backdrop URL"
android:summary="Tap here to enter custom URL"
android:id="#id/editText1"
android:defaultValue="Enter Custom URL here"
android:key="custom_uri"
android:dependency="default_uri" />
<CheckBoxPreference
android:title="Use a Custom Slideshow Period?"
android:key="slide_duration"
android:defaultValue="false"/>
<ListPreference
android:title="Slideshow Duration"
android:summary="How long should each slide be displayed?"
android:key="list_duration"
android:dependency="slide_duration"/>
</PreferenceCategory>
<PreferenceCategory
android:title="Other">
<Preference
android:title="Test Dream"
android:summary="Tap here to test the dream"
android:key="testDream" />
<Preference
android:title="About"
android:key="AboutApp"
android:summary="About this app" />
</PreferenceCategory>
</PreferenceScreen>
And my Preferences activity:
public class mollySettings extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
Preference button = findPreference("testDream");
button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference arg0) {
final Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.android.systemui", "com.android.systemui.Somnambulator");
startActivity(intent);
return true;
}
});
Preference about = findPreference("AboutApp");
about.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference arg1) {
final Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.death2all110.flogging.molly", "com.death2all110.flogging.molly.About");
startActivity(intent);
return true;
}
});
}
}
Thanks in advance, and please let me know if there is anything else you need
Got it figured out.
I added an exclamation point to the if statement. So the loadURI method is now:
private void loadURI()
{
PreferenceManager.setDefaultValues(this, R.xml.settings, true);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
if (!settings.getBoolean("default_uri", false)){
String defaultURI = getString(R.string.dream_uri);
this.mWebView.loadUrl(defaultURI);
}
else {
String customURI = settings.getString("custom_uri", "");
this.mWebView.loadUrl(customURI);
}
}
Instead of:
private void loadURI()
{
PreferenceManager.setDefaultValues(this, R.xml.settings, true);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
if (settings.getBoolean("default_uri", false)){
String defaultURI = getString(R.string.dream_uri);
this.mWebView.loadUrl(defaultURI);
}
else {
String customURI = settings.getString("custom_uri", "");
this.mWebView.loadUrl(customURI);
}
}
I'm trying to store a user entry into an EditText field however when I exit the application it does not appear.
So for example a user types in his/her name and then exits the application. When the user returns and launches the Application the users name appears in the EditText field. However I can't get this to work. I believe its to do with sharedPreferences but I'm not sure where I'm going wrong.
I'm quite new to android and java so finding this quite difficult. Any help would be much appreciated.
public class MainActivity extends Activity {
public final static String EXTRA_FROM = "com.example.assignment1.FROM";
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
EditText emailFrom =(EditText) findViewById(R.id.editEmailFrom);
String from = emailFrom.getText().toString();
outState.putString(EXTRA_FROM, from);
}
#Override
protected void onRestoreInstanceState(Bundle savedState)
{
EditText emailFrom =(EditText) findViewById(R.id.editEmailFrom);
String from = savedState.getString(EXTRA_FROM);
emailFrom.setText(from);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void emailSend (View sendButton)
{
Intent intent = new Intent(this,DisplayEmailActivity.class);
EditText emailFrom =(EditText) findViewById(R.id.editEmailFrom);
String from = emailFrom.getText().toString();
intent.putExtra(EXTRA_FROM,from);
SharedPreferences saveFrom = getSharedPreferences(EXTRA_FROM, MODE_PRIVATE);
Editor editor = saveFrom.edit();
editor.putString(EXTRA_FROM, from);
editor.commit();
String storedfrom = saveFrom.getString(EXTRA_FROM, from);
emailFrom.setText(storedfrom);
startActivity(intent);
}
Second Activity
public class DisplayEmailActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_email);
Intent intent = getIntent();
String from = intent.getStringExtra(MainActivity.EXTRA_FROM);
TextView textFrom =(TextView)findViewById(R.id.displayEmailFrom);
textFrom.setText(from);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_display_email, menu);
return true;
}
Ok, so after you store value in your EditText emailFrom, you have to save it in SharedPreferences like this:
String from = emailFrom.getText().toString(); // Getting String value from EditText and storing it in "from" String
SharedPreferences settings = getSharedPreferences("MyPreferencesFile", 0); // Opening SharedPreferences
SharedPreferences.Editor editor = settings.edit(); // Opening editor for SharedPreferences
editor.putString("exampleName", from); // You are putting here a String "from" and give it a "exampleName" name. Later you will use this name to restore data.
And then when you launch your application, you need to load data from SharedPreferences:
SharedPreferences settings = getSharedPreferences("MyPreferencesFile", 0); // Again opening SharedPreferences
String from = settings.getString("exampleName", ""); // The second argument is the default value. The default value will be set if there wasn't saved any data with "exampleName" name
if(from != "") // If "from" is not empty, it means that the data was stored in SharedPreferences
emailFrom.setText(from); // Setting text in your EditText
You are using onSaveInstanceState() and onRestoreInstanceState() to save and restore the content of the EditText. However, this methods are called only when the application is being terminated by the OS to be immediatlly recreated (i.e. device rotation).
If you want to preserve values when the application is terminated by the user, you need to store it somewhere, a file, a database or in your case I would suggest SharedPreferences.
I've posted an answer to a similar question in: SharePreferences
Good luck.