I am implementing a horizontal gallery in my Fragment Activity
, but I can't get my images, therefore returning a NullPointerException
:
LinearLayout myGallery;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
myGallery = (LinearLayout) getActivity().findViewById(R.id.mygallery);
String targetPath = "assets/";
Toast.makeText(getActivity(), targetPath, Toast.LENGTH_LONG).show();
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
for (File file : files){ //NullPointerException here
myGallery.addView(insertPhoto(file.getAbsolutePath()));
}
}
And this is the path of my images:
The NullPointerException
points at the for loop for (File file ; files){ ...
What is the right way to reach my folder?
The right way is... Put your images in the assets
folder (or in raw
).
Not in res
.
Create the assets
folder, if not already existing.
At the same level of res
, not inside it.
To get your resource, then use something like this (in this case the file is under the gfx
folder, under assets
):
final InputStream is = getApplicationContext().getAssets().open("gfx/" + fileName);
final Drawable drw = Drawable.createFromStream(is, null);
And you have your drawable out of assets
If you want to put the resources directly into assets
rather than adding a folder, simply chang this
getApplicationContext().getAssets().open("gfx/" + fileName);
to
getApplicationContext().getAssets().open(fileName);