giroxasmnl
giroxasmnl

Reputation: 131

Android - How to cast Object [] to File []

I'm creating an app in android! I'm trying to pass File[] from my Main Activity class using this line of code:

File[] listFile;
File file = new File(android.os.Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Eye Spy");
   if (file.isDirectory()) {
       listFile = (File[]) file.listFiles();
   }
Intent i = new Intent();
i.putExtra("images", listFile);

to my MapsActivity using this line of code:

listFile = (File[]) getIntent().getExtras().get("images");

But when I run the app, it displays an error message saying:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.pathnrdo.eyespy1/com.example.pathnrdo.eyespy1.MapsActivity}: java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.io.File[]

What seems to be the problem? And how can i fix it? Thanks for your reply :)

Upvotes: 1

Views: 1442

Answers (3)

t00manysecrets
t00manysecrets

Reputation: 3

The Problem is that getIntent().getExtras().get("*KEY*"); returns an Object and you cannot simply cast an Object[] to a File[].

So what you want do is to cast every single Object in the the Object-Array to File.

As an example you can do something like this:

final Object[] potentialFiles = (Object[]) getIntent().getExtras().getSerializable("*KEY*");
List<File> list = new LinkedList<>();

Objects.requireNonNull(potentialFiles);
for (final Object o : potentialFiles) {
    if (o instanceof File) {
        list.add((File) o);
    }
}

File[] files = list.toArray(new File[]{});

Or you can simply put the parentFile (the directory of all files) into the Extras. Then you can extract all files via:

//First Activity
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("*KEY*", parentFile);
startActivity(intent);

//Second Actitiy
File parentFile = (File) getIntent().getExtras().getSerializable("*KEY*");
File[] files = parentFile.listFiles();

Upvotes: 0

giroxasmnl
giroxasmnl

Reputation: 131

Okay! I already solved my problem! I just implemented these codes to my MapsActivity so that I don't have to pass it from activity to activity:

File[] listFile;
File file = new File(android.os.Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Eye Spy");
   if (file.isDirectory()) {
       listFile = (File[]) file.listFiles();
   }

Upvotes: 2

Josh.M
Josh.M

Reputation: 103

file.listFiles() already return a File[],you don't need to cast again.

Upvotes: 3

Related Questions