Android: SharedPreference errors after force close - android

I'm getting some weird effects after I force close my app. When the app is closed with finish(), everything is fine. I have some variables saved in a sharedPreferences so when the app is loaded again, it can restore those variables into the UI. However, if I force close the app and THEN try to continue where it had left off, some variables start "acting funny". By that I mean (in onCreate) I check to see if a string, loaded from the sharedPreferences, equals a value (crunched down version):
String namec;
private static final String TAG = "MyActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//namec was set as "forest" in a previous activity
//which is bypassed if the user selects continue
//from the main menu
SharedPreferences pathtaken = getSharedPreferences("pathtakenpref", MODE_WORLD_READABLE);
namec = pathtaken.getString("namec", "Unknown");
ImageView v1 = (ImageView) findViewById(R.id.pathpic1);
RelativeLayout v2 = (RelativeLayout) findViewById(R.id.pathmain);
Log.i(TAG, "namec= " + namec);
if(namec == "forest"){
v1.setImageResource(R.drawable.forest);
v2.setBackgroundResource(R.drawable.forestrepeat);
}
}
What happens here is namec, does in fact, equal "forest". I send the value to the log and it shows the variable exactly as it should be ("forest"). Yet it won't run the code inside of the if{}. It's giving me nightmares. I've been stuck on this for a week!
In the same code, I load a different set of sharedPreferences (labeled as TRHprefs) and each one of those (6 integers and 3 strings) load up and display just fine. I even add an if{} to test 1 string and 1 integer from TRHprefs... they both came back true.
Q.1: Is there anything that can cause my sharedPreferences xml to become, somehow, corrupted on a force close?
Q.2: Is there a way for me to view the xml file before and after I use force close to help debug the situation. Thanks so much!

Its a String. Try this:
if("forest".equals(namec)){

If you want to compare two String you need to use this:
if(namec.equals("forest")){
v1.setImageResource(R.drawable.forest);
v2.setBackgroundResource(R.drawable.forestrepeat);
}

Related

Issue with preferences on my samsung tablet but not my phone, possibly context related?

I have an app that works fine on my phone (Huawei Mate 10 Pro) but I have issues on my tablet (Samsung Galaxy Tab S2). I have previously posted a different question regarding issues on one and not the other, but this issue is completely separate.
I use a preference screen to save some settings. One of these settings (a unique id) is only shown but can be copied by clicking it, otherwise it is only handled by the app itself. Everything works just as it should on my phone, but some parts of the code seems to not work on my tablet (the value is empty there). Since the code is identical something must be handled differently between the devices. I'm not sure, but could it be the context?
Several code snippets to follow.
From my PrefFregment, works on both devices:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.app_settings);
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
getPreferenceScreen().findPreference("UID").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Context context = preference.getContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String uid = prefs.getString("UID", "");
uid = uid.trim();
ClipboardManager clipboardManager = (android.content.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("UID",uid);
clipboardManager.setPrimaryClip(clip);
Toast.makeText(context,R.string.UIDtoast, Toast.LENGTH_LONG).show();
return true;
}
});
}
Another snippet from my PrefFragment, works on my phone but not the tablet:
private void updatePreference(Preference preference) {
preference.setSummary(PreferenceManager.getDefaultSharedPreferences(preference.getContext()).getString(preference.getKey(),""));
}
The last snippet, it's from my main activity. It works on my phone but uid is empty on my the tablet:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String uid = prefs.getString("UID", "");
uid = uid.trim();
I solved this issue. I had been wrong all along regarding the underlying problem. The context worked fine just as it was. The issue was that I at an earlier point had changed the preference in question from a editTextPreference to just a Preference, and thus its text couldn't just be edited. I had to enter the uid value through an editor instead. Then everything worked. The reason some of it worked anyway was that the previous value was still stored in the preference since before the change. I noticed this when I reinstalled the whole app and suddenly all values were empty. I still don't know why there was a difference between the devices. But now the issue itself is solved at least.

My Android App hangs on SharedPreferences, but only in Android 5

An odd one here. I've built an app in Android Studio which is working perfectly in Android 4 (4.4.2), but it just stopping on Android 5.0.2. It's not throwing up any errors, just stopping.
Going line by line, it seems to be focussed on the SharedPreferences file, which it's not loading.
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
final SharedPreferences sharedPreferences = this.getSharedPreferences("appname", MODE_PRIVATE );
currentlyTracking = sharedPreferences.getBoolean("currentlyTracking", false);
So, on Android 4, going line by line, when I get to the currentlytracking line, I can view the contents of the SharedPreferences file in the Variables window, and the app works. On Android 5, when I get to the currentlytracking line, none of the variables show up, and it just says 'Collecting data'. The app then stops if I try to continue on.
Interestingly, if I change the name of the Sharedpreferences file, it will create a new file but then fail to save to it.
This is only happening on Android 5, any thoughts would be appreciated.
Cheers

Optimization of my soundboard code

I think the best is to first say, that I recently started Android programming. Despite the fact of me getting better now, I can't seem to find good ways to optimize my piece of code.
I've written this piece of code. It's a soundboard. And when you long click a button you're able to save it as a ringtone, as a alarm, as a notification or share it with your friends. For every method I've made a string.
This string is set by the corresponding button to "btn1" till "btn20". After this I open the method (in the example below showSelectedSaveDialog(). And in that method I've made a if or if else statement to open the correct sound.
This way of coding makes a very long code. Because for every button I have to make an if else statement. Is there a better way to code kind codes? Is there a good tutorial, or something like that? Or someone who can post an example?
Setting the string:
ringToneManager = "btn1";
showSelectSaveDialog();
Setting the correct sound:
if (str.equals("btn1")) {
fIn = getSherlockActivity().getBaseContext().getResources()
.openRawResource(R.raw.sound01);
Starting the method to share the sound file
shareButton("btn14");
Getting the corresponding sound file
private void shareButton(String str) {
// SAVE THE FILE
byte[] buffer = null;
if (str.equals("btn1")) {
fIn = getSherlockActivity().getBaseContext().getResources()
.openRawResource(R.raw.sound01);
[...] etc
Thanks in advance! :)
You can simplify your code by using the "tag" property, available on all Views and widgets. The tag property is a general purpose container.
Load the tag property for each button with the id of the sound file associated with the button, this can be done on an activities onCreate:
findViewById(R.id.btn1).setTag(R.raw.sound01);
findViewById(R.id.btn2).setTag(R.raw.sound02);
//etc.
findViewById(R.id.btn20).setTag(R.raw.sound20);
Each button can now share the same onClick handler and all run the same piece of code, no ifs required:
public void onClick(View arg0) {
fIn = getSherlockActivity().getBaseContext().getResources().openRawResource((Integer)arg0.getTag());
}
Likewise change the shareButton method to take an integer instead of a string:
shareButton((Integer)arg0.getTag());
private void shareButton(int soundID) {
// SAVE THE FILE
byte[] buffer = null;
fIn = getSherlockActivity().getBaseContext().getResources().openRawResource(soundID);
[...] etc

Android: How to obtain an overlay on top of acitivity

when my application is installed for the first time by the user , i want to explain him what each activity does (like a quick tip) , it should look like the below picture
it should have the cancel button , and should not repeat after the first install,
I need suggestion or any useful links ,how to implement it, Any help is appreciated.
You could use SharePreference to store the state whether or not user have viewed your instruction. Just add a boolean value named as 'instructionViewed' to SharePreference. Every time your application launched, check the value. If true, don't show instruction. If false, show instruction. When user click the cancel button, set the value to true.
SharePreference is a very easy-using class to help store some information.You could google how use it.
Hope this helpful.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testpage);
//Check SharePreference
boolean instructionViewed = checkInstrunctionState();
//If the instruction is not viewed, show instruction.
if(!instructionViewed){
RelativeLayout yourLayout = createYourOwnUi();
FrameLayout contentView = (FrameLayout)(getWindow().getDecorView().findViewById(android.R.id.content));
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(MATCH_PARENT,MATCH_PARENT);
contentView.addView(yourLayout, lp);
}
}

LoadUrl in PhoneGap and Android

I am working on an app for android using phonegap and unity.
I wrote a plugin for phonegap that starts a new activity from phonegap that loads the unity player. When i hit the back button in the unity activity i want to go back to the phonegap activity and load my webcontainer again, but with a different url.
Whatever i try, it still loads the URL i loaded the first time. Is there any way to fix that?
Here is the Activity:
public class PhonegapCallsActivity extends DroidGap {
private static Boolean backButton;
private static String url;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras == null) {
Log.d("false","ERROR");
//load index.html when i enter first time
super.loadUrl("file:///android_asset/www/index.html");
return;
}
else{
backButton = extras.getBoolean("backButton");
//load #two when i come back
Log.d("true","ERROR");
super.loadUrl("file:///android_asset/www/index.html#two");
}
}
Note that logcat is tracing true and false correctly, so my variables are set properly.
I always get the index.html loaded, never index.html#two. Is it stored somewhere?
You are doing it right but you are running into an Android bug. Go star:
https://code.google.com/p/android/issues/detail?id=17535
https://code.google.com/p/android/issues/detail?id=17327
In the mean time the best way to work around this issue is to store a flag in localStorage to check if you should be loading page one or page two in the JavaScript.

Categories

Resources