1

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:

enter image description here

The NullPointerException points at the for loop for (File file ; files){ ...

What is the right way to reach my folder?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Cris
  • 2,002
  • 4
  • 30
  • 51
  • 1
    This is not how Android drawables work. Use `assets` or `raw`, not `drawable-gallery`. – shkschneider Jun 16 '15 at 13:51
  • where is the assets folder? – Cris Jun 16 '15 at 13:53
  • ok thanks, I've followed your observations, but it still produces a `NullPointerException` – Cris Jun 16 '15 at 14:11
  • My Logcat: http://pastie.org/private/bj7brxb8o61yutcex4mw – Cris Jun 16 '15 at 14:28
  • 1
    You cannot use the File and FileInputStream classes for 'files' in assets. You have to use the assets manager an let that open an input stream to your 'files'. Google for open or copy files from assets. You could have left your images in drawables too. But if you want to list them assets is the way to go. – greenapps Jun 16 '15 at 15:10
  • but I need a File, not an InputStream – Cris Jun 16 '15 at 15:24
  • I collected my comments into an answer, so you can accept it and remove it from the Unanswered Question Queue. – Phantômaxx Jun 17 '15 at 13:38

1 Answers1

2

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);
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115