android - 数据持久化 openFileOutput 和 openFileInput

标签 android

我正在尝试让我的 rss 阅读器保存 URL 地址,以便在重新打开时保存它。但出于同样的原因,openFileOutput 和 openFileInput 是红色的,它表示它无法解析方法。

我们的教授让我们在线观看视频,我按照他和他正在工作的方式编写了视频。他的视频https://www.youtube.com/watch?v=RlIHJNCKpkw

 private void saveArticles(){

        try{
                                       //is in red cannot resolve method
            FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
            fos.write(urlAddress.getText().toString().getBytes());
            fos.close();
        }
        catch (Exception e){
            Log.d("exception", e.getMessage());

        }
    }

        private String getSavedArticles(){
            String contexts = "";

            try{
                                     //is in red cannot resolve method
                FileInputStream fin = openFileInput(FILENAME);
                int c ;

                while((c = fin.read()) != -1){
                    contexts = contexts + (char)c;
                }
                fin.close();
                return contexts;
            }

            catch(Exception e){
                Log.d("exception", e.getMessage());
            }

            return "";

        }

最佳答案

openFileInput 和 openFileOutput 是 Context 类的成员。 Activity 继承自 Context,因此您可以在 Activity 类中使​​用这些方法。否则,您需要将该 Activity (或上下文)传递给其他类。

将您的 Activity 实例传递给实现 saveArticles 的类。

private void saveArticles(Context context)
{
    ...
     FileInputStream fit = context.openFileInput(FILENAME);
}

关于android - 数据持久化 openFileOutput 和 openFileInput,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33305071/

相关文章:

java - 在有多个 Activity 的同时加载一项 Activity

java - 保存并读取整数 Firestore Android

java - 绘制数千个粒子的更高效方法(Java/Android)

安卓 IAB : Billing service unavailable on device

android - 确定用户字体大小选择

android - gradle,无法展开 ZIP appcompat-v7 :19. 0.1

android - 将 Android 操作栏与菜单选项卡合并

java - RecyclerView 的 SearchView 不起作用

android - 模拟器内存​​大小自动更改为 384MB

android - 当其他首选项被禁用时,如何在我的 android 应用程序中启用首选项?