How would one correctly import data from a file, inside a fragment, then use that data from global variables, in other classes/activities/fragments?
I currently have this:
AssetManager manager = getActivity().getAssets();
in the MyFragment class.
The fragment is instantiated inside an other Fragment:
MyFragment mf = new MyFragment();
in order to be able to get variables which contain data that is loaded from a file.
I had no issues whatsoever using the MyFragment class in Java, and load the files from whatever folder, but here, I need context, and get to the files from the assets folder.
Still, when I want to getAssets() in the MyFragment class, I get null (even though there are files inside the folder).
Here is the code of the MyFragment:
public class FileReader extends Fragment {
private AssetManager manager;
private InputStream is;
public void loadIDs(){
// try {
manager = getActivity().getAssets();
// } catch (NullPointerException e){
// e.printStackTrace();
// }
//File file = new File("IDs.txt");
try {
is = manager.open("IDs.txt");
Scanner in = new Scanner(is);
totalBuses = in.nextInt();
IDs = new String[totalBuses];
for(int i=0; i<totalBuses; i++){
IDs[i] = in.next();
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e){
e.printStackTrace();
}
}
}
And the class where the fragment is called:
public class NavigationDrawerFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
fr = new FileReader();
fr.loadIDs();
String[] list = {"this", "that"};
// String[] list = new String[fr.getTotalBuses()+1];
// list[0] = "Bun venit!";
// list[1] = "Whatever";
// list[2] = "Something";
// for(int i=1; i<=fr.getTotalBuses(); i++){
// list[i] = "Autobus " + fr.getSchedules()[i-1];
// }
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_1,
android.R.id.text1,
list));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
}