【问题标题】:Is it possible to send data from a class to another class (not an acitivity) in Android Studio?是否可以在 Android Studio 中将数据从一个类发送到另一个类(不是活动)?
【发布时间】:2016-07-11 20:45:19
【问题描述】:

我不想将数据从一个活动发送到另一个活动。 我得到的错误是这样的:

   Intent intent = new Intent(this,LogOut.class) ;

无法解析构造函数 Intent !!!

【问题讨论】:

  • 你为什么不把它放在构造函数中,或者可能是调用一个方法或者通过接口发送它?
  • 这种方式只用于Activity。为什么不使用首选存储选项?
  • 要么添加导入 import android.content.Intent 要么 this 不是 Context 的实例
  • 这里不需要intent(正如你所说的不是活动类),你可以创建Logout对象。
  • 您是否在片段中使用此代码?用户 ActivityName.this 而不是只有这个

标签: android class android-intent


【解决方案1】:

全局声明变量,然后为声明的变量创建getter、setter。因此,您可以通过 getter 方法在您想要的任何其他类中获取变量的值。

public class GetSet2 {

    public GetSet2(String value) {
        this.value = value;
    }

    private String value;

    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }

}

【讨论】:

    【解决方案2】:

    你能告诉我们你到底想做什么。不可能使用意图来做到这一点。检查意图的定义http://developer.android.com/reference/android/content/Intent.html 您可以使用 set 和 get 的类。如果你想保存你的活动数据,你可以使用共享偏好。 http://www.tutorialspoint.com/android/android_shared_preferences.htm

    示例:在您的第一堂课中:

            SharedPreferences.Editor editor = sharedpreferences.edit();
    
            editor.putString("Name", n);
            editor.putString("Phone", ph);
            editor.putString("Email", e);
            editor.commit();
    

    第二个:

    SharedPreferences prefs =     PreferenceManager.getDefaultSharedPreferences(this);
    String imgSett = prefs.getString("Name", "");
    

    .......................

    注意使用上下文。如果您将活动用于非活动,请使用上下文。

    【讨论】:

    • 我有 2 个类,Log_In 和 Log_out,我想将变量 ID 从类 Log_in 发送到类 Log_out,以便我可以将数据发送到我的服务器(它需要相同ID,因为我想在一个人注销时显示数据)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    • 2017-01-07
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    相关资源
    最近更新 更多