如何在Android中使用SharedPreferences来存储,获取和编辑值?

时间:2014-12-29 06:11:32

标签: android sharedpreferences

我想存储分数和名称值,并且需要在用户获得更高分数时检索和编辑它。我怎样才能做到这一点?有人可以帮我使用我的代码吗?

MainActivity.java

package com.thesis.boggleit;


import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

	//VARIABLES HERE
  
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      
      
        dbHelper =new DBAdapter(this);
        search = (EditText) findViewById(R.id.textHere);
      
		OnClickListener myCommoClickListner = new OnClickListener(){

			@Override
			public void onClick(View arg0) {
		        Log.i(TAG,"arg0.getId()="+arg0.getId());
                
                
                if (arg0.getId()==R.drawable.a){
                    Log.i(TAG,"arg0.getId()="+arg0.getId());
                    generatedString=generatedString+("a");
                    text.setText(generatedString);
                    ((ImageButton) arg0).setImageResource(R.drawable.changea);

        				if (!timeHasStarted) {
        					   countDownTimer.start();
        					   timeHasStarted = true;
        					   }
        	}
			
		};
		image1.setOnClickListener(myCommoClickListner);
    }
    
    //TIMER HERE
    private int optionTxtView = 0  ;
    private int addClick = 0  ;
    
    private void calculate(){
		x = Integer.parseInt(tv3.getText().toString().replaceAll("\\s",""));
	    y = Integer.parseInt(tv2.getText().toString().replaceAll("\\s",""));
	    z = x + y;
	    score.setText(Integer.toString(z));
	    }

    	String s1= search.getText().toString();
        String s2= dbHelper.getData(s1);
      
........

}

TIA

3 个答案:

答案 0 :(得分:0)

Official Android developer guide明确指出

  

如果您要保存的密钥值集合相对较少,则应使用SharedPreferences API。 SharedPreferences对象指向包含键值对的文件,并提供读取和写入它们的简单方法。每个SharedPreferences文件都由框架管理,可以是私有的或共享的。

这意味着您必须使用SharedPreferences类来实现您想要的目标。

实施例: -

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); // In a fragment

SharedPreferences sharedPref = getApplicationContext().getPreferences(Context.MODE_PRIVATE); //In an Activity

 最好的学习方法是访问上面的链接并阅读它。

答案 1 :(得分:0)

存储值

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("name", name);
editor.putInt("score", score);
editor.commit();

获取价值

String name = prefs.getString("name", "");
int score = prefs.getInt("score", 0);

答案 2 :(得分:0)

使用此Common类:

public static boolean setPreference(Context context, String key, int value) {

    if (context == null) {
        throw new IllegalArgumentException("'context' must not be null.");
    }
    if (key == null) {
        throw new IllegalArgumentException("'key' must not be null.");
    }

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putInt(key, value);
    return editor.commit();
} 
public static int getPreference(Context context, String key, int defValue) {

    if (context == null) {
        throw new IllegalArgumentException("'context' must not be null.");
    }
    if (key == null) {
        throw new IllegalArgumentException("'key' must not be null.");
    }

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    return preferences.getInt(key, defValue);
}

使用方法:

int currentScore = 20; 
    PreferenceUtil.setPreference(context, "key1", currentScore);

    //get. If the key1 in not available, return default value 0

    int myScore = PreferenceUtil.getPreference(context, "key1", 0);