2012-03-04 99 views
-1

我想制作一个每天都会做某事的应用程序。我设法保存了一天,并在接下来的几天里,我希望与当天相比。写入并读取到SDcard

例如: 天= 5; aux = 5;

明天:

天= 6; aux = 5;

如果(天!=​​ AUX)做一些别的 不采取行动

我想保存上的SD卡文件中的辅助的状态,但它是很难找到工作的代码。我希望有人会看看并回答它,明天我会需要它。

public class Castle extends Activity { 
/** Called when the activity is first created. */ 

@Override  
public void onCreate(Bundle savedInstanceState) { 
    requestWindowFeature(Window.FEATURE_NO_TITLE); 
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
          WindowManager.LayoutParams.FLAG_FULLSCREEN); 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.castle); 


    Calendar calendar = Calendar.getInstance();  
    int day = calendar.get(Calendar.DAY_OF_WEEK); 

    int aux=Reading(); 

    if(day==aux) 
    { 
     Intent intent = new Intent(Castle.this, Hug.class); 
     startActivity(intent); 
    } 
    else 
    { 
     Intent intent = new Intent(Castle.this, Hug_Accepted.class); 
     startActivity(intent); 

    try { 
     File root = Environment.getExternalStorageDirectory(); 
     if (root.canWrite()){ 
      File file = new File(root, "Tedehlia/state.txt"); 
      file.mkdir(); 
      FileWriter filewriter = new FileWriter(file); 
      BufferedWriter out = new BufferedWriter(filewriter); 
      out.write(day); 
      out.close(); 
     } 
    } catch (IOException e) { 

    }} 




} 
public int Reading() 
{int aux = 0; 
    try{ 


     File f = new File(Environment.getExternalStorageDirectory()+"/state.txt"); 

     FileInputStream fileIS = new FileInputStream(f); 

     BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS)); 

     String readString = new String(); 

     if((readString = buf.readLine())!= null){ 

      aux=Integer.parseInt(readString.toString()); 


     } 

    } catch (FileNotFoundException e) { 

     e.printStackTrace(); 

    } catch (IOException e){ 

     e.printStackTrace(); 

    } 

    return aux; 
} 

}

+0

但问题是什么?你有异常吗? (在你的catch子句中打印出LogCat的例外) – YuviDroid 2012-03-04 20:19:29

+0

我现在将测试它。我100%肯定它不会工作。我甚至不确定文件是否会被创建。 – AnTz 2012-03-04 20:23:32

+0

我也想只保存一个值在文件上。我想我可能需要删除文件后,我从中获得的价值,有人可以告诉我如何做到这一点? – AnTz 2012-03-04 20:24:20

回答

1

看来你正在试图读取该文件的应用程序有机会创造它。我强烈建议您使用SharedPreferences而不是SDCard上的文件。

public void onCreate() { 
    . . . 
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); 
    int aux = prefs.getInt("AUX", -1); 
    if (day == aux) { 
     . . . 
    } else { 
     aux = day; 
     SharedPreferences.Editor editor = prefs.edit(); 
     editor.putInt("AUX", day); 
     editor.apply(); // or editor.commit() if API level < 9 
    } 
    . . . 
} 
+0

因此,即使应用程序关闭,这将保存我的“辅助”的状态? – AnTz 2012-03-04 20:32:32

+0

@AnTz - 当然。这是SharedPreferences的优点之一。此外,尽管他们的名字,他们是你的应用程序私人。 – 2012-03-04 20:36:57

+0

编译并运行良好。谢谢你的回答! – AnTz 2012-03-04 20:37:15