2013-03-23 63 views
0

我知道我可以在活动和文件名中使用getFilesDir()来保存/读取文件。但是,当我尝试从窗口小部件中调用getFilesDir()时,出现错误。我希望能够从小部件和活动中访问相同的文本文件。如何在小部件和活动之间共享私人文件?

实现该目标的最简单方法是什么?

+1

什么是错误? – 2013-03-23 17:33:23

+0

显示你的代码,以及你的堆栈... – duggu 2013-03-23 17:37:35

回答

1

您可以使用AssetManager用于此目的。这里有一个简单的例子:

AssetManager assetManager = getAssets(); 
String[] files = assetManager.list("Files"); 
InputStream input = assetManager.open("helloworld.txt"); 
int size = input.available(); 
byte[] buffer = new byte[size]; 
input.read(buffer); 
input.close(); 
String text = new String(buffer); 

更新:对不起,忘了,你想过要在窗口小部件使用。你可以从this answer试试这个代码:

InputStream is = mContext.getAssets().open(someFile); 
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8")); 

警告:不要因为是使用此代码。你应该使用正确的代码来捕捉错误和边缘情况。

+0

傻我!我刚刚意识到onUpdate通过了一个Context ...你的回答让我意识到,当我想到“好吧,我从哪里获取mContext?”谢谢!!!现在工作得很好。 – PawelP 2013-03-23 18:12:12

2

您可以使用getFilesDir()从任何Context因此,您可以保存\从Application读取您的文件。

编辑:

你必须从Application扩展类,并使用它的上下文:

public class App extends Application{ 

    private static Context mContext; 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     mContext = this; 
    } 

    public static Context getContext(){ 
     return mContext; 
    } 
} 

然后在你的应用程序的manifest,设置Application标签的name属性与类名,例如:

android:name="App" 

注意:应用程序是名称延伸为Application

现在你可以使用它的上下文做保存\读:

App.getContext().getFilesDir(); 
+0

我刚刚尝试过......当使用“上下文环境= getApplicationContext();”时,我得到“...未定义类型小部件”。我错过了什么? – PawelP 2013-03-23 18:02:07

+0

@PawełParadowski请参阅我的编辑。 – hasanghaforian 2013-03-23 18:13:11