1

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;
    }
}

enter image description here

Wilhelm Sorban
  • 1,012
  • 1
  • 17
  • 37

1 Answers1

0

It's usually not a good practice to instantiate a Fragment using it constructor directly. Preferred option is to use a newInstance() static method. More info: http://developer.android.com/reference/android/app/Fragment.html

But since you are not using the Fragment as a view, but as a helper class, what about passing a Context as dependency on FileReader constructor?

fr = new FileReader(getActivity());

lgvalle
  • 3,712
  • 1
  • 19
  • 14
  • Yes you **must** have [parameterless constructor](http://stackoverflow.com/a/10450535/360211) and so a static factory method that bundles the required data is a good alternative. – weston Jul 27 '15 at 12:27
  • 1
    PLEASE PLEASE: avoid any kind of parameter when you're constructing a Fragment. It doesn't matter if the Fragment has a UI or not, the system will have to rebuild your Fragment if needed and will use the default empty constructor, not the one that you're providing! – Mimmo Grottoli Jul 27 '15 at 12:38
  • Well, is not completely true you need to avoid parameters when constructing fragments. What you need to avoid is passing parameters directly to the constructor. Instead you should use a static method that will bundle whatever parameters you pass to it and set them up inside a bundle when constructing the fragment. That way Android can rebuild that fragment safely. But anyway, in this case it doesn't matter because the use case is very limited – lgvalle Jul 27 '15 at 14:09