Skip to content Skip to sidebar Skip to footer

How To Fix Android Error "method Openfileinput In Class Context Cannot Be Applied To Given Types;2

Within my MainActivity.java I am trying to open a file according to the code given here. But when running the code public class MainActivity extends AppCompatActivity { @Overr

Solution 1:

As mentioned by @MuhammadKashifArif:

Instead of this

FileInputStreamfis= getBaseContext().openFileInput("hello.txt",Context.MODE_PRIVATE);

use this

FileInputStreamfis= openFileInput("hello.txt", MODE_PRIVATE);

It doesn't matter.

Context is context, and getBase context is still the same context as everything else, calling getBaseContext doesn't change the type of context compared to using this in an activity. There is no difference between accessing MODE_PRIVATE statically and using import static

I am not sure when exactly this changed (and I am not going to look through every version of android to check either), but it is openFileOutput that takes two arguments, a String an an Integer.

openFileInput now only takes one argument. So:

FileInputStreamfis=/*Some context here if you are outside an activity.*/openFileInput("hello.txt");

And to load:

FileOutputStreamfos=/*some context if outside activity.*/openFileOutput("hello.txt", Context.MODE_PRIVATE);

And I would once again like to clear up the fact that it doesn't make a difference whether or not you call getBaseContext, getApplicationContext, or call this/SomeActivity.this inside an activity. The context class itself doesn't change, the fields are the same. And writing MODE_PRIVATE without Context. in front of it is called a static import. The only difference between Context.MODE_PRIVATE and the static import MODE_PRIVATE is only you don't have to type those characters. The method doesn't exist no matter how you call it


As for the compile error, it basically says you are supplying more arguments than the method requires. You should also see a red warning over the call to the method as well, but what you see is the compile error as you tried to compile the build while there is a call to an unknown method.

Solution 2:

As @LunarWatcher said the openFileInput takes 1 parameter.So,

Instead of this

FileInputStreamfis= getBaseContext().openFileInput("hello.txt",Context.MODE_PRIVATE);

use this

FileInputStreamfis= openFileInput("hello.txt");

Post a Comment for "How To Fix Android Error "method Openfileinput In Class Context Cannot Be Applied To Given Types;2"