openFileOutput工作不正常单身类中 - 的想法/解决方法? [英] openFileOutput not working properly inside a singleton class - ideas/workarounds?

查看:95
本文介绍了openFileOutput工作不正常单身类中 - 的想法/解决方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为新手的Andr​​oid开发者,我遇到了一点奇怪的问题。我想创建一个类,哪些方法等课程,活动,任何可以用来与文件以某种特殊的方式工作。 Let`s说,为了简单起见,我们会记录一些东西。如果我在活动中下(在的OnClick监听器为例),一切工作就好了:

As a novice Android developer, I've faced a bit strange problem. I want to create a class, which methods other classes-activities-whatever could use for working with files in some special way. Let`s say for simplicity we would be logging some stuff. If I do following within an activity (in OnClick listener for example), everything works just fine:

FileOutputStream fOut = openFileOutput("somefile", MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write("Very important foobar");
osw.flush();
osw.close();

但是,当我尝试附上该到了一些类,并创造单这样的:

But when I try to enclose that into some class and create singleton like that:

public class Logger extends BaseActivity {
//BaseActivity is the "init" class which extends Activity

public static final Logger INSTANCE = new Logger();
private Logger() { 
// singleton
}

public boolean doLog (String whatToLog) {
 try {
     FileOutputStream fOut = openFileOutput("somefile", MODE_PRIVATE);
 OutputStreamWriter osw = new OutputStreamWriter(fOut);
 osw.write(whatToLog);
 osw.flush();
 osw.close(); }
     catch (IOException ioe) { ioe.printStackTrace(); }  
     return true; }

和其他活动调用它像

Logger.INSTANCE.doLog("foobar");  

应用chrashes与NullPointerException异常(在符合openFileOutput)。我想是因为使用不当,这里单/活动,现在重写code作为服务运行它单曲。但也许有一些更好的思路来解决问题?或者一些解决方法?

app chrashes with NullPointerException (at line with openFileOutput). I suppose it`s because of improper use of singleton/activity here and now rewriting the code to run as a service. But maybe there are some better ideas to solve an issue? Or some workarounds?

感谢提前你的贡献!

推荐答案

您根据您单上的活动,你没有启动的一个活动。因此,它不具有有效的背景信息,这是必要的IO调用。见布伦德尔的<一个href="http://stackoverflow.com/questions/6538955/openfileoutput-not-working-properly-inside-a-singleton-class-ideas-workarounds/6539080#6539080">answer为更好的单身,有一个变化:根据android.app.Application的javadoc,你的单身应该从给定的情况下,通过Context.getApplicationContext应用程序上下文()。请参见为什么AndroidTestCase.getContext()。getApplicationContext()返回null 的另一个例子。

You based your singleton on an Activity that you didn't start as an Activity. Therefore, it doesn't have a valid Context, which is necessary for the IO calls. See Blundell's answer for better singleton, with one change: As per android.app.Application javadoc, your singleton should get the application context from the given context via Context.getApplicationContext(). See why does AndroidTestCase.getContext().getApplicationContext() return null for another example.

这篇关于openFileOutput工作不正常单身类中 - 的想法/解决方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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