1

I would like to call method1 from another class, but how can i use getActivity() in a static method? I only found examples for FragmentActivity or other types. I am sorry if this question already got answered somewhere else, but i could not find anything that i could implement in my code. Any help is appreciated.

public class Tab1 extends Fragment {

public static String readFromFileKurs(Context ctx) {

        ret = "";


        try {
            InputStream inputStream = ctx.openFileInput("configkurs.txt");

            if ( inputStream != null ) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String receiveString = "";
                StringBuilder stringBuilder = new StringBuilder();

                while ( (receiveString = bufferedReader.readLine()) != null ) {
                    stringBuilder.append(receiveString);
                }

                inputStream.close();
                ret = stringBuilder.toString();


            }
        }
        catch (FileNotFoundException e) {
            Log.e("login activity", "File not found: " + e.toString());
        } catch (IOException e) {
            Log.e("login activity", "Can not read file: " + e.toString());
        }

        return ret;

    }


public static void method1(){

temp = readFromFile(getActivity());

}
}
Fynn
  • 210
  • 1
  • 6
  • 28
  • You cannot call getActivity() from a static method, as getActivity() is itself not static. what are you trying to achieve? – emerssso Oct 22 '14 at 23:37

1 Answers1

1

You can't use getActivity(), since it's a static method and thus can't access activity/fragment's methods. You may want to pass the activity as a parameter (since method1 must get called from some non-static method).

However in your case, you don't need a specific Activity - just a context, any context - so an application context may suffice. Refer to This SO question for more info.

Community
  • 1
  • 1
Khanh Nguyen
  • 11,112
  • 10
  • 52
  • 65