【问题标题】:importing value to another class将值导入另一个类
【发布时间】:2015-08-15 22:26:25
【问题描述】:
    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
        }

我想将“名称”导入另一个类。我该怎么做?

【问题讨论】:

  • 请注意,您在 void 方法中使用 return 语句。你不能这样做
  • Onclick 不返回任何值,因此很明显它会显示错误。现在您想要的是将值返回到打开此活动的先前活动???还是您希望它返回到任何其他活动

标签: android class return


【解决方案1】:

我猜你想将值发送到另一个活动,对吧?那么你应该使用意图。

在你的活动中:

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

在要获取值的activity中:

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

【讨论】:

    【解决方案2】:

    最简单的方法是通过意图。 您可以为要启动的课程设置意图。然后你可以把名字作为额外的并启动活动类。

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

    【讨论】:

      【解决方案3】:

      您还可以使用首选项在任何需要的地方存储和检索数据。

      例如:这是在 Utils 类中。

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

      在活动 A 中:

      String password = inputPassword.getText().toString();
      Utils.storeInPreference("password",password); //key,value
      
       In Activity B:
      
      String password = Utils.getStringFromPreference("password"); //key
      

      【讨论】:

        猜你喜欢
        • 2021-12-01
        • 1970-01-01
        • 2019-08-23
        • 2020-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-21
        • 2016-01-27
        相关资源
        最近更新 更多