Android Context from another class

天大地大妈咪最大 提交于 2019-12-25 02:23:55

问题


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 the 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


回答1:


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



回答2:


Instead of passing context, it would be more appropriate to use Fileclass. 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);



回答3:


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



来源:https://stackoverflow.com/questions/7371514/android-context-from-another-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!