Home > Software design >  Tab Swipe View - Can't load data from a text file in the fragment
Tab Swipe View - Can't load data from a text file in the fragment

Time:11-03

Here, TabView is the class which adds this particular fragment. Search is the MainActivity which gets the file name from the user. There are some text files in the assets folder. When the user enters the name , for eg, hello, It's concatenated to hello.txt and stored as variable in Search activity. I get this value using the return func. So, here comes the main problem. When i try to get data from hello.txt, The app closes abruptly when it comes to this part.. I've searched everywhere!Found Nothing!Please help..

    public class fg1 extends Fragment {

        LinearLayout layout;
        private String file;
        private Search obj;
        private Context mX;
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            if (container == null) {
                return null;
            }


        layout = (LinearLayout)inflater.inflate(R.layout.fg_code, container, false);
        TextView snippet = (TextView)layout.findViewById(R.id.codeView);

        mX = TabView.getContext();
        AssetManager assetManager = mX.getAssets();
        file = obj.getFileName();
                InputStream input;
            try {
                 input = assetManager.open(file);

                 int size = input.available();
                 byte[] buffer = new byte[size];
                 input.read(buffer);
                 input.close();
                 // byte buffer into a string
                 String text = new String(buffer);
                 snippet.setText(text);

         } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
         }  
        return layout;
    }
}

CodePudding user response:

Found the answer myself. For any future references, Instead of getting data from activity, pass the data to the fragment (fragment's constructor is advisable) from the parent activity that hosts the particular fragment and use it.

  • Related