【问题标题】:Save game info to file in android将游戏信息保存到android中的文件
【发布时间】:2013-11-29 16:50:59
【问题描述】:

我还是新手。我正在制作一个 android 应用程序来创作音乐。因此用户可以创建自己的音乐。如何保存用户在界面中选择的内容?示例:有 3 个按钮可供选择,按钮 1 用户选择“a”按钮 2 用户选择“c”,按钮 3 用户选择“f”。如何将其保存到 .txt 文件中,然后在用户想再次播放时加载?

抱歉,如果您不太了解我的语言。也许你能给我一些例子保存并加载到文件中吗?我在 stackoverflow 中读到了一些,但它太多了,我仍然没有找到我的答案。

【问题讨论】:

  • Google 关于 SharedPreferences。这是在应用程序会话之间保存和持久化数据的最简单方法。

标签: android file load save andengine


【解决方案1】:

你可以用来保存文件:

File newxmlfile1 = new File(Environment.getExternalStorageDirectory()+"/kadirGameLevels");
   newxmlfile1.mkdirs();


   int i = 1;
   File newxmlfile;
   do{
       String filename = i+".lvl";
       newxmlfile = new File(Environment.getExternalStorageDirectory()+"/kadirGameLevels/"+filename);
       i++;
   }while(newxmlfile.exists());

   try{
           newxmlfile.createNewFile();
   }catch(IOException e){
           Log.e("IOException", "exception in createNewFile() method");
   }
   //we have to bind the new file with a FileOutputStream
   FileOutputStream fileos = null;        
   try{
           fileos = new FileOutputStream(newxmlfile);
   }catch(FileNotFoundException e){
           Log.e("FileNotFoundException", "can't create FileOutputStream");
   }

并将文件获取到您的应用程序:

    File file = new File(Environment.getExternalStorageDirectory() + "/kadirGameLevels/1.lvl");
        DataInputStream stream = new DataInputStream(new FileInputStream(file));

【讨论】:

  • 还是不太明白。示例:字符串 file1 = "a";字符串文件 2 = "b";字符串文件 3 = "c";我想将它保存到一个文件中,让我们使用 .txt 可能所以在 txt 里面将是这 3 个变量。不知何故我想把它加载到我的应用程序中。所以应用程序会知道 file1 = "a" file2 = "b" file3 = "c"
【解决方案2】:

为什么要归档?为什么不共享偏好?

 private void saveCurrentScore(long currentScore) {
            try {
                android.content.SharedPreferences.Editor editor = prefs.edit();
                editor.putLong("currentscore", currentScore);
                editor.commit();

            } catch (Exception e) {
                e.printStackTrace();
            }

        }


        private String getCurrentScore() {
            try{prefs = PreferenceManager.getDefaultSharedPreferences(activity);
            return ""+  prefs.getLong("currentscore", 0);
            }catch(Exception e)
            {
                e.printStackTrace();
            }
            return "";
        }

注意:- 如果您正在使用 andengine 也请查看 SecureSharedPreferences

【讨论】:

  • 因为我希望用户可以在他们之间共享他们的数据。在这个应用程序中,我制作了一个应用程序来创作音乐。我的应用程序中没有分数。我想将我创作的音乐数据保存在 .txt 等文件中,然后在需要时将其加载到应用程序中。
  • 您可以将文件保存在您的存储中,并将该文件的路径保存在共享首选项中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多