Hello I am trying to call this function loadFiles()
which is located in fragmentB
and I want to call it from FragmentA
, so I can refresh my GridView
for my images and videos.
I get this error from the same method
FATAL EXCEPTION: main
java.lang.NullPointerException
my method in FragmentB
:
public void loadFiles(){
gridView = (GridView) this.v.findViewById(R.id.grid);
File f = new File(home);
if (f.exists()){
String [] media = f.list();
ArrayList<String> files = new ArrayList<>();
for (int i=0; i<media.length;i++){
if (media[i].endsWith(".jpg")||
media[i].endsWith(".png")||
media[i].endsWith(".JPEG")||
media[i].endsWith(".3gp")||
media[i].endsWith(".mp4")||
media[i].endsWith(".mov")){
files.add(media[i]);
}
if (i==media.length-1){
GridAdapter adapter = new GridAdapter(this.v.getContext(), files, gridView);
adapter.notifyDataSetChanged();
gridView.setAdapter(adapter);
}
}
}
}
How I do call it in FragmentA
:
FragmentB b = new FragmentB();
b.loadFiles();
I think the problem is because of this line but I have tried everything and there is no luck :(
GridAdapter adapter = new GridAdapter(this.v.getContext(), files, gridView);
I would suggest you to do like this:
public class Utils{
public static ArrayList<String> loadFiles(){
File f = new File(home);
if (f.exists()){
String [] media = f.list();
ArrayList<String> files = new ArrayList<>();
for (int i=0; i<media.length;i++){
if (media[i].endsWith(".jpg")||
media[i].endsWith(".png")||
media[i].endsWith(".JPEG")||
media[i].endsWith(".3gp")||
media[i].endsWith(".mp4")||
media[i].endsWith(".mov")){
files.add(media[i]);
}
}
return files;
}
}
}
Now in FragmentA and FragmentB etc. you can do
gridView = (GridView) this.v.findViewById(R.id.grid);
GridAdapter adapter = new GridAdapter(this.v.getContext(), Utils.loadFiles(), gridView);
gridView.setAdapter(adapter);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments