2016-05-15 11 views
0

私は新しいアンドロイドアプリの開発者です。私はアプリを作っていましたが、共有の設定を使用して残高整数を保存したいのですが、どうすればよいか分かりません。私はグーグルで多くのことをしましたが、私はまだ混乱しています。誰も私のコードにバランスの整数を格納する共有の設定を入れてもらえますか?ここにコードがあります。Androidスタジオ共有の設定をデバイスストレージに保存

import android.content.SharedPreferences; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.view.WindowManager; 
import android.widget.ImageButton; 
import android.widget.TextView; 

public class MainActivity extends AppCompatActivity { 
    int balance = 0; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     //Hide notification bar 
     getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); 
     //Click counter 
     final TextView text = (TextView) findViewById(R.id.balance_text); 
     assert text != null; 
     text.setText(balance + " $"); 
     final ImageButton button = (ImageButton) findViewById(R.id.click_button); 
     assert button != null; 
     button.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       balance++; 
       text.setText("" + balance + " $"); 
      } 
     }); 
    } 

} 

答えて

2

sharedpreferences

public class MainActivity extends AppCompatActivity { 
int balance;; 
private SharedPreferences preferences; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    //Hide notification bar 
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); 
    //Click counter 
    final TextView text = (TextView) findViewById(R.id.balance_text); 
    assert text != null; 
    // to retreuve the values from the shared preference 
    preferences = PreferenceManager.getDefaultSharedPreferences(this); 
    balance = preferences.getInt("balance", 0); 
    text.setText(balance + " $"); 
    final ImageButton button = (ImageButton) findViewById(R.id.click_button); 
    assert button != null; 
    button.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      balance++; 
      text.setText("" + balance + " $"); 
     } 
    }); 
} 

}

共有好みに保存するためにこれらの行を使用してから値を取得するには、以下のコードを見つけてください。あなたはonBackPressed()にこれを使うことができます

@Override 
public void onBackPressed() { 
    super.onBackPressed(); 
    SharedPreferences.Editor editor = preferences.edit(); 
     editor.putInt("balance", balance); 
     editor.apply(); 
} 
+0

ありがとう!できます! – Camper1233

+0

クラスをインポートしてください.. import android.preference.PreferenceManager; import android.content.SharedPreferences; – somia

+0

もう一つ必要なことがあります。onBackPressed()を使う方法を教えてください。あるいは、私が入れる必要があるコードを教えてください。ありがとう。 – Camper1233

関連する問題