Issue
I am just starting to learn testing on Android and this is driving me crazy. The feature works fine but I cannot get my tests to run. I am trying to read a value from SharedPreferences
and compare it to the content of a TextView. I am using Espresso on Android Studio 2.3.3.
This line String player1Name = sharedPreferences.getString(context.getString(R.string.KEYplayerOneDefaultNameSetting), context.getString(R.string.playerOne));
causes this android.content.res.Resources$NotFoundException: String resource ID #0x7f09004d
exception. This is essentially the same code that I use in my Fragments to access shared preferences.
I could not find anything referencing this same problem. I feel like I just have a simple configuration error but I can't figure it out. Thanks in advance.
Here is my entire test:
@Test
public void setsPlayerNamesFromSettings(){
Context context = getInstrumentation().getContext();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
String player1Name = sharedPreferences.getString(context.getString(R.string.KEYplayerOneDefaultNameSetting), context.getString(R.string.playerOne));
onView(withId(R.id.LpCalculatorTextPlayer1Name)).check(matches(withText(player1Name)));
String player2Name = sharedPreferences.getString(context.getString(R.string.KEYplayerTwoDefaultNameSetting), context.getString(R.string.playerTwo));
onView(withId(R.id.LpCalculatorTextPlayer2Name)).check(matches(withText(player2Name)));
}
If it's any assistance, here's code from my Fragment that access SharedPreferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getContext());
mLpCalculatorModel.setLpDefault(Integer.parseInt(preferences.getString(getString(R.string.KEYdefaultLpSetting), "8000")));
mLpCalculatorModel.setPlayer1Name(preferences.getString(getString(R.string.KEYplayerOneDefaultNameSetting), getString(R.string.playerOne)));
mLpCalculatorModel.setPlayer2Name(preferences.getString(getString(R.string.KEYplayerTwoDefaultNameSetting), getString(R.string.playerTwo)));
mLpCalculatorModel.setAllowsNegativeLp(preferences.getBoolean(getString(R.string.KEYallowNegativeLp), false));
tvPlayer1Lp.setText(Integer.toString(mLpCalculatorModel.getLpDefault()));
tvPlayer2Lp.setText(Integer.toString(mLpCalculatorModel.getLpDefault()));
Solution
getInstrumentation().getContext()
This returns a Context
representing your androidTest
source set. If your resources are elsewhere (e.g., main
), use:
getInstrumentation().getTargetContext()
Answered By - CommonsWare
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.