2013-07-11 52 views
-3

我正在尝试制作应用程序,而且我需要保存字符串,就像AppInventor中的TinyDB一样。所以,我发现有http://developer.android.com/guide/topics/data/data-storage.html#filesInternal,我正在寻找的是将数据保存到内部存储,但我不知道如何读取它。他们说:Android - 读取内部数据

来读取内部存储文件:

  1. 呼叫openFileInput(),并通过它的文件的名称改为。这会返回一个FileInputStream。

  2. 使用read()从文件中读取字节。

  3. 然后关闭与关闭()流

但我不知道怎么回事,我的代码永远不会奏效。所以我搜索了如何从内部存储读取,没有代码工作。你能告诉我,如何从内部存储读取文本? :)

这是代码:

EditText tagbox = (EditText)findViewById(R.id.editText1); 
    String tag = tagbox.toString(); 
    Context context = getApplicationContext(); 


    FileInputStream fis = context.openFileInput(tag); 
    InputStreamReader in = new InputStreamReader(fis); 
    BufferedReader br = new BufferedReader(in); 
    String data = br.readLine(); 

     Toast.makeText(getApplicationContext(), data, Toast.LENGTH_LONG).show(); 

好了,我找到了解决办法。最简单的方法来存储数据,如TinyDB在AppInventor,使用SharedPreferences:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); 

Edtior editor = preferences.edit(); 

要存储数据:

editor.putString("key", "value"); 

读取数据:

String value = preferences.getString("key"); 
+0

发布您的代码,所以我们可以帮助你 - 但我们不打算编写你的代码。 –

+0

好的,代码在那里 – StfgMccx

回答

0

好,所以我找到了解决方案。到数据,如TinyDB存储在AppInventor最简单的方法,是使用SharedPreferences:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); 

Edtior editor = preferences.edit(); 

要存储数据:

editor.putString("key", "value"); 

读取数据:

String value = preferences.getString("key"); 
0
 File selectedFile = new File(path + "/" + selectedFromList + ".txt"); 

     FileInputStream fstream = null; 
     ArrayList sal = new ArrayList(); 
     try { 
      fstream = new FileInputStream(selectedFile); 

      BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); 
      String strLine; 
      //Read File Line By Line 

      while ((strLine = br.readLine()) != null) { 
       // Print the content on the console 
       sal.add(strLine); 
       } 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
      //Close the input stream 
      try { 
      in.close(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
+0

如何将其转换为字符串?我用:String note = sal.toString();它崩溃了,是不是转换错了? – StfgMccx

+0

sal是一个数组。所以你想确定你想要使用的数组中的什么条目。 所以你可以使用sal [0] .toString();或for(int i = 0; i PartTimeLegend

+0

Eclipse在sal [0]处给我一个错误,错误是:“表达式的类型必须是数组类型,但它解析为ArrayList” – StfgMccx