Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAdlight Sibanda
5,701 PointsWere is the Bug.......
Ack! There is an error regarding SharedPreferences in the code below. Fix it such that "MeaningOfLife" is properly stored and retrieved as an int value.
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
protected SharedPreferences mSharedPreferences;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
// Some code omitted!
}
public int getMeaningOfLife() {
return mSharedPreferences.getInt("MeaningOfLife", 42);
}
public void setMeaningOfLife() {
mSharedPreferences
.edit()
.putString("MeaningOfLife", "42") // 42 should be an int not a String
.commit();
}
}
2 Answers
Steve Hunter
57,712 PointsYep - this line of code needs to change in two places:
.putString("MeaningOfLife", "42")
The 42 is being a string, and the method is used for Strings too. It needs to be:
.putInt("MeaningOfLife", 42)
So, change the method and remove the double quotes.
Steve.
Steve Hunter
57,712 PointsI've added a comment showing where the problem is. ;-)
Steve.
Adlight Sibanda
5,701 Pointsis 42 not the int i still cant get it