Tan Chong Kai
Tan Chong Kai

Reputation: 332

How to save a string globally?

I want to ask if is it possible to store a string globally for me to call in any other activity? Like for example the String email in my code, I want to save it globally so I can call it from other activity.

I tried using intent to carry data but it does not seem to work for my code.

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);
}

Upvotes: 1

Views: 165

Answers (3)

Rajesh Jadav
Rajesh Jadav

Reputation: 12861

You can use SharedPreferences to save data to preference and use it any Activity.

You can use this method to save your email String into SharedPreferences.

public void saveValueToPrefrence(Context mContext, String key, String value) {
    SharedPreferences pref = mContext.getSharedPreferences("UserData", 0);
    SharedPreferences.Editor editor = pref.edit();
    editor.putString(key, value);
    editor.apply();
}

You can get email String in any other Activity using below method:

public String getValueFromPrefrence(Context mContext, String key) {
    SharedPreferences pref = mContext.getSharedPreferences("UserData", 0);
    return pref.getString(key, "");
}

You can use this method to save your email String:

saveValueToPrefrence(ActivityName.this,"email",email)

You can get email String like this:

String email = getValueFromPrefrence(ActivityName.this,"email")

Basically you need Activity's Context to save and get value from SharedPreferences.

I hope it helps you.

Upvotes: 1

miversen33
miversen33

Reputation: 569

@FreeYourSoul is correct.

But as an answer to this question, there are multiple ways to do this. The easiest way would be to simply create a Static class that has a hashmap inside it that you can manipulate with any class.

Likely not your best choice, but it certainly is possible

Upvotes: 1

FreeYourSoul
FreeYourSoul

Reputation: 364

You can use global variable, but most of the time you shouldn't use this.

Are global variables bad?

You have to know if this variable is used in most of your application (lot of class need an access to it, and be careful about threads to not have a concurrency issue). If it's the case you can maybe use a global, which is a bad idea in my opinion. You also can do a singleton class.

But if you just try to send your variable between two view, I think you should use this

Upvotes: 2

Related Questions