简体   繁体   English

访问已创建的相同类Android对象

[英]Accessing objects that have already been created of the same class Android

So I am creating a chat app for android and I'm using Java and I need some help wrapping my head around some things. 因此,我正在为Android创建一个聊天应用程序,并且正在使用Java,我需要一些帮助来解决一些问题。 Whenever the user first registers, I am creating a new object of a class named User. 每当用户首次注册时,我都会创建一个名为User的类的新对象。 When they enter the next layout, I need to access that objects data. 当他们进入下一个布局时,我需要访问该对象数据。

public class User {
public String username;
public User() {}

public User(String username) {
    this.username = username;
}

public String getUsername(){
    return username;
  }
}

This is my User class. 这是我的User类。 When they send a message, I need to be able to grab their username from this User object from an entirely different method without passing the object through a parameter. 当他们发送消息时,我需要能够通过完全不同的方法从此User对象中获取其用户名,而无需将该对象传递给参数。 I can't seem to wrap my head around how to access their information and none of my methods seem to work. 我似乎无法全神贯注于如何访问他们的信息,而且我的方法似乎都无效。 Any help is appreciated 任何帮助表示赞赏

If you do 如果你这样做

User myUser = new User();

the variable myUser contains a reference to the newly created object. 变量myUser包含对新创建对象的引用。 You must keep this reference around in order to later access the object. 您必须保留此引用,以便以后访问该对象。 How exactly you do this depends on the logic of your program. 具体执行方式取决于程序的逻辑。 Sometimes you would keep it in a field of another object or pass it around as parameter. 有时,您会将其保留在另一个对象的字段中或将其作为参数传递。 For example 例如

un = myUser.getUsername();

or 要么

void myMethod(User theUser) {
    ...
    String un = theUser.getUsername();
}

...

// call the method passing the user reference
myMethod(myUser);

in the main class make the data object... static 在主类中使数据对象成为静态对象

public static Model obj; 公共静态模型obj; obj= new Model(); obj = new Model(); then from other class access it with your class name 然后从其他班级使用您的班级名称访问它

example main.obj; 示例main.obj;

I solved this issue by just using SharedPreferences. 我仅使用SharedPreferences解决了这个问题。 I stored the username associated with the key of each user. 我存储了与每个用户的密钥关联的用户名。 This way, I can always search the username for each user. 这样,我总是可以搜索每个用户的用户名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM