我想问一下是否可以全局存储一个字符串供我在任何其他 Activity 中调用?例如我代码中的字符串电子邮件,我想将它全局保存,以便我可以从其他 Activity 中调用它。
我尝试使用 intent 来携带数据,但它似乎不适用于我的代码。
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
@Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
最佳答案
您可以使用全局变量,但大多数情况下您不应该使用它。
你必须知道这个变量是否在你的大部分应用程序中使用(很多类需要访问它,并注意线程不要有并发问题)。如果是这种情况,您也许可以使用全局变量,我认为这是个坏主意。你也可以做一个单例类。
但是,如果您只是尝试在两个 View 之间发送变量,我认为您应该使用 this
关于android - 如何全局保存一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33049999/