使用getSharedPreferences保存新值

时间:2015-02-14 22:48:57

标签: android sharedpreferences record

我试图保存一个新值(按钮的点击次数),只要" new score"大于oldscore。使用TextView我会在用户点击按钮时显示点击次数,当时间结束时,我想用另一个TextView显示得分。我没有任何日志错误,记录的文本视图一直在说0。请问你能帮帮我吗? 我的MainActivity ...

public class MainActivity extends ActionBarActivity {

SharedPreferences mPrefs;
final String welcomeScreenShownPref = "welcomeScreenShown";
private TextView txtCount, textViewTimer;
private Button btnCount;
int count = 0;
int clicks = 0;
boolean[] timerProcessing = { false };
boolean[] timerStarts = { false };
private MyCount timer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Check if we're running on Android 5.0 or higher
    //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    // Call some material design APIs here

    // } else {
    // Implement this feature without material design
    //}

    mPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    Boolean welcomeScreenShown = mPrefs.getBoolean(welcomeScreenShownPref, false);

    if (!welcomeScreenShown) {

        final MaterialDialog mMaterialDialog = new MaterialDialog(this);
        mMaterialDialog.setTitle(R.string.dialog_title);
        mMaterialDialog.setMessage(R.string.dialog_message);
        mMaterialDialog.setPositiveButton(R.string.start, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMaterialDialog.dismiss();
            }
        });mMaterialDialog.show();

        SharedPreferences.Editor editor = mPrefs.edit();
        editor.putBoolean(welcomeScreenShownPref, true);
        editor.apply(); // Very important to save the preference
    }

    Typeface myTypeface = Typeface.createFromAsset(this.getAssets(),
            "DS-DIGII.TTF");
    TextView digital= (TextView) findViewById(R.id.textView2);
    digital.setTypeface(myTypeface);

    txtCount = (TextView) findViewById(R.id.textView1);
    txtCount.setText(String.valueOf(count));
    TextView txtRecord = (TextView) findViewById(R.id.record);
    txtRecord.setText(String.valueOf(clicks));
    btnCount  = (Button) findViewById(R.id.button1);
    Button btnRestart = (Button) findViewById(R.id.button2);
    textViewTimer = (TextView) findViewById(R.id.textView2);

    timer = new MyCount(10000, 1);

    btnCount.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {
            // start timer once when button first click
            if (!timerStarts[0]) {
                timer.start();
                timerStarts[0] = true;
                timerProcessing[0] = true;
            }

            if (timerProcessing[0]) {
                count++;
                txtCount.setText(String.valueOf(count));
            }
        }
    });
    btnRestart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            timerStarts[0] = false;
            timerProcessing[0] = true;
            count = 0;
            txtCount.setText(String.valueOf(count));
            timer.cancel();
            textViewTimer.setText("10:000");

            if (btnCount.isPressed()) {
                timer.start();

            }

        }

    });
    btnRestart.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            Vibrator vb = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            vb.vibrate(1);
            return false;
        }
    });

}

public class MyCount extends CountDownTimer {
    public MyCount(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
    }

    @Override
    public void onFinish() {
        textViewTimer.setText("0:000");
        timerProcessing[0] = false;
        final int oldscore = getSharedPreferences("myPrefs", MODE_PRIVATE).getInt("highscore", 0);
        if (count > oldscore)
            getSharedPreferences("myPrefs", MODE_PRIVATE).edit().putInt("highscore", clicks).commit();
        final MaterialDialog mMaterialDialog = new MaterialDialog(MainActivity.this);
        mMaterialDialog.setTitle("IL TUO PUNTEGGIO");
        mMaterialDialog.setMessage("Hai fatto " + txtCount.getText().toString() + " click.");
        mMaterialDialog.setPositiveButton("CONDIVIDI", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, "Ho fatto " + txtCount.getText().toString() + " click in 10 secondi. Scarica l'app e prova a battermi.");
                sendIntent.setType("text/plain");
                startActivity(Intent.createChooser(sendIntent, ""));
            }
        });
        mMaterialDialog.setNegativeButton("CHIUDI", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMaterialDialog.dismiss();
            }
        });mMaterialDialog.show();

    }

    @Override
    public void onTick(long millisUntilFinished) {
        textViewTimer.setText("" + millisUntilFinished / 1000 + ":"
                + millisUntilFinished % 1000);

    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

修改:简而言之,我尝试将_count_的值保存到另一个 Texview

1 个答案:

答案 0 :(得分:1)

您需要在时间结束时保存clicks值。

在您的计时器onFinish()方法中,添加此代码

if (count > oldscore){
    getSharedPreferences("myPrefs", MODE_PRIVATE).edit().putInt("highscore", clicks).commit();
    //Save your value
    getSharedPreferences("myPrefs", MODE_PRIVATE).edit().putInt("highscore_count", count).commit();
    //Display the value
    textView.setText(String.valueOf(count)); 
}

然后,在您的onCreate方法中,您获取该值并将其显示为

SharedPreference prefs = getSharedPreferences("myPrefs", MODE_PRIVATE); 
int highscore_count = prefs.getInt("highscore_count", 0); 
textView.setText(String.valueOf(highscore_count));
相关问题