如何使用共享首选项来保存从数据库获取的数据?

时间:2016-07-21 05:12:27

标签: java android sharedpreferences

我有这个按钮代码,它连接到数据库

bLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String username = etUsername.getText().toString();
            final String password = etPassword.getText().toString();

            // Response received from the server
            Response.Listener<String> responseListener = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);
                        boolean success = jsonResponse.getBoolean("success");

                        if (success) {
                            String name = jsonResponse.getString("name");
                            String email = jsonResponse.getString("email");
                            String alamat = jsonResponse.getString("alamat");
                            int notelp = jsonResponse.getInt("notelp");
                            String username = jsonResponse.getString("username");
                            String password = jsonResponse.getString("password");

                            Intent intent = new Intent(MainActivity.this, adminarea.class);
                            intent.putExtra("name", name);
                            intent.putExtra("email", email);
                            intent.putExtra("alamat", alamat);
                            intent.putExtra("notelp", notelp);
                            intent.putExtra("username", username);
                            intent.putExtra("password", password);
                            MainActivity.this.startActivity(intent);
                        } else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                            builder.setMessage("Login Gagal")
                                    .setNegativeButton("Ulangi", null)
                                    .create()
                                    .show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            };

我有一个名为admin的表,其中包含字段名称,电子邮件等。如何从数据库中获取数据,然后将名称,电子邮件,alamat和其他数据保存到共享的prefences中。那你可以帮我把它叫做另一个活动吗?

8 个答案:

答案 0 :(得分:5)

首先,您必须创建SharedPreferences

SharedPreferences pref = getApplicationContext().getSharedPreferences("YOUR_PREF_NAME", MODE_PRIVATE); 
Editor edt = pref.edit();

优先添加价值:

edt.putString("name", name);           
edt.putString("email", email);       
edt.putString("alamat", alamat);   
edt.putString("notelp", notelp);     
edt.putString("username",username); 

// Save your changes
edt.commit();

现在从偏好中获取数据:

String name=pref.getString("name", null);  
String email=pref.getString("email", null);  
String alamat=pref.getString("alamat", null);  
String notelp=pref.getString("notelp", null);  
String username=pref.getString("username", null);

如果要清除首选项数据:

edt.clear();
edt.commit(); 

答案 1 :(得分:1)

保存如下。

        SharedPreferences getPref = PreferenceManager.getDefaultSharedPreferences(this);

        Intent intent = new Intent(MainActivity.this, adminarea.class);

        intent.putExtra("name", name);
        getPref.edit().putString("name",name).apply();
        intent.putExtra("email", email);
        getPref.edit().putString("email",name).apply();
        intent.putExtra("alamat", alamat);
        getPref.edit().putString("alamat",name).apply();
        intent.putExtra("notelp", notelp);
        intent.putExtra("username", username);
        intent.putExtra("password", password);

        MainActivity.this.startActivity(intent);

像这样检索。

        SharedPreferences getPref = PreferenceManager.getDefaultSharedPreferences(this);
        String name = getPref.getString("name","");
        String email = getPref.getString("email","");
        String alamat = getPref.getString("alamat","");

答案 2 :(得分:1)

创建一个SharePrefUtil类

private Context context;
private SharedPreferences prefs;

public SharePrefUtil(Context mContext) {
    this.context = mContext;
    prefs = this.context.getSharedPreferences("your package name", Context.MODE_PRIVATE);
}


public void setValueInSharePref(String keyName, String value) {
    prefs.edit().putString(keyName, value).apply();
}

public String getValueFromSharePref(String keyName) {
    return prefs.getString(keyName, "");
}
}

什么时候想要存储值 只需在您的活动中创建一个类的对象即可获取或设置一个值 例如

SharePreUtil shef = new SharePreUtil(this);

什么时候在活动中设置值

shef.setValueInSharePref("key", "yourvalue");

当你想获得价值时

shef.getValueFromSharePref("key");

一切顺利......

答案 3 :(得分:0)

您可以在活动类的SharedPreferences中保存数据,如下所示:

config/environments/[production.rb, development.rb, test.rb]

在您要获取它们的活动中,请执行以下操作:

  SharedPreferences sharedPreferences = getSharedPreferences("USER_INFO", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("name", name);
    editor.putString("email", alamat);
    editor.putString("alamat", alamat);
    editor.commit();

放入int,

  SharedPreferences sharedPreferences = getSharedPreferences("USER_INFO", Context.MODE_PRIVATE);
    String name=sharedPreferences.getString("name", "abc");
    String email=sharedPreferences.getString("email", "abc@gmail.com");

要重温它,

editor.putInt("number",0);    

答案 4 :(得分:0)

for ($i = 0; $i < 4; $i++) {
     name_person( $name_array[$i], $i+1);
}

答案 5 :(得分:0)

引用https://developer.android.com/training/basics/data-storage/shared-preferences.html

上的培训指南
var obj = {
  "locations": [
      {
        "id": 8817,
        "loc": "NEW YORK CITY"
      },
      {
        "id": 2873,
        "loc": "UNITED STATES"
      },
      {
        "id": 1501,
        "loc": "NEW YORK STATE"
      }
    ]
}
var val = '8817';
var res = obj.locations.filter(function(item) {
    return item.id == val;
  });

  console.log(res[0].loc);

并阅读

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>

答案 6 :(得分:0)

在你的其他活动中....首先从意图中接收数据......像这样

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();

现在,将这些数据保存到共享的prefrences ....要做到这一点......你需要sharedPreferences.Editor来写数据......就像这样......

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);

答案 7 :(得分:0)

if (success) {

    // once you retrieve all the required data
    SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);

    // Writing data to SharedPreferences
    Editor editor = prefs.edit();
    editor.putString("name", name);
    editor.putString("email", email);
    editor.putInt("notelp", notelp);
    editor.commit();

    // start your AdminArea activity here
}

在AdminArea类中检索数据:

// Reading from SharedPreferences
String value = prefs.getString("name", "DEFAULT_STRIGN"); // if the given key not found, it'll take the default string as value
int intValue = prefs.getInt("notelp", -1); // instead of -1, you can give any default value 

希望这有助于:)