Android Context from another class
What I'm trying to do is the following...
FileInputStream fIn;
try {
fIn = openFileInput("samplefile.txt");
InputStreamReader isr = new InputStreamReader(fIn);
BufferedReader br = new BufferedReader(isr);
isTrue = Boolean.parseBoolean(br.readLine());
Log.i("IN", "isTrue = " + isTrue);
}
But this is only going to work in the class that extends t开发者_JAVA百科he Activity class within Android.
I have a "Settings" class which writes and reads the current games settings from a file, but this file has a lot of data I dont really want manipulated.
I was initially using a BufferedReader
& BufferedWriter
but I cannot set the data to Private which means anyone can just edit the file. With a OutputStreamWriter
it is a little more secure at least
How do I get my excising "Settings" class (which has entirely static methods) to have access to the Context so I may use methods such as openFileInput
Create constructor for your Settings class that has Context argument. Then when you instantiate the object from that class, just pass the your application context, thats it.
Constructor:
public Settings(Context cont)
{
//do something with the context, e.g assign it to some private variable of type Context
}
In your activity class:
Settings settings = new Settings(MyActivity.this);
Instead of passing context, it would be more appropriate to use File
class. You should avoid passing context to other classes whenever possible.
File file = new File("sample.txt");
InputStream is = new FileInputStream(file);
Another alternative could be to pass the context to the method.
boolean isTrue = Settings.readBoolean(MyClass.this);
If you are using multiple fragments with multiple activities than there is a shortcut method for getting the context. create a static class. define the context. whenever you are changing activity change the context. get the context in fragment using that static class. I know you can get the context in a fragment by getactivity() but if you are using some adapter or noncontext class this will be really helpful
精彩评论