从另一个类的Andr​​oid上下文 [英] Android Context from another class

查看:170
本文介绍了从另一个类的Andr​​oid上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做的是以下...

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

但是,这只会在扩展中的Andr​​oid活动类的类工作。

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.

我最初使用的BufferedReader &安培; 的BufferedWriter ,但我无法将数据设置为私有,这意味着任何人都可以编辑该文件。随着 OutputStreamWriter 这是一个小更安全的至少

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

我如何得到我的摘除设置类(具有完全静态方法)能够访问上下文,所以我可能会使用的方法,如 openFileInput

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.

构造器:

 public Settings(Context cont)
{
     //do something with the context, e.g assign it to some private variable of type Context

}

在您的活动类:

Settings settings = new Settings(MyActivity.this);

这篇关于从另一个类的Andr​​oid上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆