2012-03-04 22 views
-1

毎日何かをするアプリケーションを作りたいと思います。私はその日を救うことができたし、翌日には今日の日に比べて欲しい。SDカードへの書き込みと読み取り

例: 日= 5; aux = 5;

明日:

日= 6; aux = 5;

(日!= AUX)であれば、何か他の が何か

をしないん私はSDカード上のファイルにAUXの状態を保存したかったが、作業コードを見つけることは難しいです。私は誰かが見て、それに答えることを望む、私は明日のためにそれが必要になります。

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

+0

今すぐテストします。私はそれが動作しないことを100%確信しています。私はファイルが作成されるかどうかもわかりません。 – AnTz

+0

ファイルに保存される値は1つだけです。私はそれから値を取得した後、私はファイルを削除する必要があるかもしれないと思う誰かが私にこれを行う方法を教えてもらえますか? – AnTz

答えて

1

あなたがアプリがそれを作成する機会を持つ前にファイルを読み込もうとしているようです。このためにSDCardのファイルの代わりにSharedPreferencesを使用することを強くお勧めします。

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

これは、これは、アプリケーションが終了しても私の "AUX"の状態を保存しますか? – AnTz

+0

@AnTz - 絶対に。これはSharedPreferencesに関する素晴らしい点の1つです。また、彼らの名前にもかかわらず、彼らはあなたのアプリケーションにプライベートです。 –

+0

コンパイルされ、素晴らしい作品です。答えてくれてありがとう! – AnTz

関連する問題