importing value to another class

2019-08-06 03:33发布

问题:

    btnRegister.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            String name = inputFullName.getText().toString();
            String email = inputEmail.getText().toString();
            String password = inputPassword.getText().toString();

            if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
                registerUser(name, email, password);
            } else {
                Toast.makeText(getApplicationContext(),
                        "Please enter your details!", Toast.LENGTH_LONG)
                        .show();
            }
            return name;              //<-here is the error
        }

i want to import "name" to another class.. How Can i do this?

回答1:

I guess you want to send the value to another activity, right? Then you should use intents.

In your activity:

Intent intent = new Intent();
intent.putExtra("name", name);
startActivity(intent);

In the activity where you want to get the value:

Bundle extras = getIntent().getExtras();
if (extras != null) {
String data = extras.getString("name");


回答2:

Easiest way to do it is via intents. You can set up an intent for the class you want to launch. Then you can put the name as extra and start the activity class.

Intent intent = new Intent(this,YourActivityClass.class);
intent.putExtra("Name","value");
startActivity(intent);


回答3:

You can also use preference to store and retrieve datas wherever you need.

For eg: this is in Utils class.

 private Editor mEditor;
  private SharedPreferences mPreferences;
     private static final String PREFERENCE_NAME = "pref";
  public Utils(Context context) {
    mPreferences = context.getSharedPreferences(PREFERENCE_NAME,
            Context.MODE_PRIVATE);
    mEditor = mPreferences.edit();
}

    /**
 * Store string in preference.
 *
 * @param key
 *            the key
 * @param value
 *            the value
 */
public static void storeStringInPreference(String key, String value) {
    mEditor.putString(key, value);
    mEditor.commit();
}

/**
 * Gets the string from preference.
 *
 * @param key
 *            the key
 * @return the string from preference
 */
public static String getStringFromPreference(String key) {
    return mPreferences.getString(key, null);
}

In Activity A:

String password = inputPassword.getText().toString();
Utils.storeInPreference("password",password); //key,value

 In Activity B:

String password = Utils.getStringFromPreference("password"); //key