2

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

0

3 Answers 3

4

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);
Sign up to request clarification or add additional context in comments.

1 Comment

His Settings class has only static methods.
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);

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.