我正在尝试从测验应用程序的片段中的资产文件夹中加载.png文件,但它始终返回空。
在调用.getAssets()之前,我已经检查了该片段是否已附加到Activity上,并且在调用中包含了.getActivity()。错误消息本身是由于尝试从Assetmanager打开文件而引起的。
这是给我错误的代码段
private void loadNextSign() {
// get file name of the next sign and remove it from the list
String nextImage = quizSignList.remove(0);
correctAnswer = nextImage; // update the correct answer
answerTextView.setText(""); // clear answerTextView
// display current question number
questionNumberTextView.setText(getString(
R.string.question, (correctAnswers + 1), SIGNS_IN_QUIZ));
// extract the region from the next image's name
String region = nextImage.substring(0, nextImage.indexOf('-'));
// use AssetManager to load next image from assets folder
System.out.println(isAdded());
AssetManager assets = getActivity().getAssets();
// get an InputStream to the asset representing the next sign
// and try to use the InputStream
try (InputStream stream =
assets.open( region + "/" + nextImage + ".png")) {
// load the asset as a Drawable and display on the signImageView
Drawable sign = Drawable.createFromStream(stream, nextImage);
signImageView.setImageDrawable(sign);
animate(false); // animate the sign onto the screen
}
catch (IOException exception) {
Log.e(TAG, "Error loading " + nextImage, exception);
}
Logcat
05-14 16:48:01.386 18314-18314/com.example.signquiz E/SignQuiz Activity: Error loading RoadSigns-Slippery_Roads
java.io.FileNotFoundException: RoadSigns/RoadSigns-Slippery_Roads.png
at android.content.res.AssetManager.openAsset(Native Method)
at android.content.res.AssetManager.open(AssetManager.java:313)
at android.content.res.AssetManager.open(AssetManager.java:287)
at com.example.signquiz.MainFragment.loadNextSign(MainFragment.java:83)
at com.example.signquiz.MainFragment.resetQuiz(MainFragment.java:273)
at com.example.signquiz.MainActivity.onStart(MainActivity.java:70)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1237)
at android.app.Activity.performStart(Activity.java:6253)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
我是Java和android编程的新手,但据我了解,这应该可以正常工作。我在做什么错了?