访问另一个类的ArrayList如何做?

huangapple go评论83阅读模式
英文:

How to access an arraylist from another class?

问题

在Register Activity类中,我创建了一个ArrayList,并且日志显示它正在被填充。但是当我在AllUsers类中访问它时,它是空的。

这是Register Activity的代码。在signup()方法中,我正在使用Firebase注册用户,同时将名称添加到ArrayList中,这一部分运行正常。但是当我通过getUserNames()方法在AllUsers类中访问这个ArrayList时,它是空的。

英文:

In the class Register Activity, I have created ArrayList, and logs show it is being populated. But when I access it in AllUsers class, it is empty.

public class AllUsers extends AppCompatActivity {

    private FirebaseUser user;
    private ArrayAdapter adapter;
    private FirebaseAuth mAuth;
    private ListView userListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all_users);
        userListView = findViewById(R.id.usersListView);
        RegisterActivity registerActivity = new RegisterActivity();
        adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, registerActivity.getUserNames());
        userListView.setAdapter(adapter);
        for(String n : muserNames)
            Log.d("TagAllUsers", n);
        adapter.notifyDataSetChanged();
    }
}

This is the Register activity. In the signup() activity I am registering the user with firebase and at the same time I am adding name to the ArrayList, which is going fine. But when i access this ArrayList in the All users class through getUsernames(), it is empty.

public class RegisterActivity extends AppCompatActivity {
private EditText name, email, password, matchPassword, phone;
private TextView textLogin;
private FirebaseAuth mAuth;
private ProgressBar progressBar;
private Button btnSaveImage;
private String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
private static ArrayList<String> userNames;
private static String userName;
@Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
progressBar = findViewById(R.id.progressBar);
btnSaveImage = findViewById(R.id.btnSaveImage);
name = (EditText) findViewById(R.id.editTextPersonName);
email = (EditText) findViewById(R.id.editTextPersonEmail);
phone = (EditText) findViewById(R.id.editTextPersonPhone);
matchPassword = (EditText) findViewById(R.id.editTextMatchPassword);
password = (EditText) findViewById(R.id.editTextPersonPassword);
Button register = (Button) findViewById(R.id.buttonRegister);
textLogin = findViewById(R.id.textlogin);
userNames = new ArrayList();
mAuth = FirebaseAuth.getInstance();
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
signUp();
}
});
textLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
}
catch (Exception e){
Toast.makeText(getApplicationContext(), "Error - "+e.getMessage(), Toast.LENGTH_LONG).show();
}
}
public ArrayList<String> getUserNames() {
return userNames;
}
private void signUp() {
try {
String Email = email.getText().toString().trim();
String Password = password.getText().toString().trim();
if (Email.isEmpty()) {
email.setError("Email required");
email.requestFocus();
return;
}
if(!Email.matches(emailPattern)){
email.setError("Valid Email required");
email.requestFocus();
return;
}
if (Password.isEmpty()) {
password.setError("Valid password required");
password.requestFocus();
return;
}
if (Password.length() < 6) {
password.setError("Password should be at least 6 characters long");
password.requestFocus();
return;
}
progressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(Email, Password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d("TAG", "createUserWithEmail:success");
Toast.makeText(getApplicationContext(), "Registration successful",
Toast.LENGTH_SHORT).show();
FirebaseUser user = mAuth.getCurrentUser();
Users users = new Users(name.getText().toString(), email.getText().toString(), phone.getText().toString(), password.getText().toString());
FirebaseDatabase.getInstance().getReference("User_data").child(task.getResult().getUser().getUid()).setValue(users).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(), "Data saved", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Something went wrong!!", Toast.LENGTH_SHORT).show();
}
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
FirebaseDatabase.getInstance().getReference("User_data").addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
userName = snapshot.child("name").getValue().toString();
Log.d("TaguserName", userName);
userNames.add(userName);
for(String user_Name : userNames)
Log.d("TagArrayList", user_Name);
}
@Override
public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
}
@Override
public void onChildRemoved(@NonNull DataSnapshot snapshot) {
}
@Override
public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
});
Intent intent = new Intent(getApplicationContext(), AllUsers.class);
//This is to clear the login/signup actity so that whwn we press back, login activity dont come
intent.putExtra("From", "Register");
startActivity(intent);
finish();
} else {
if(task.getException() instanceof FirebaseAuthUserCollisionException){
Toast.makeText(getApplicationContext(), "User already exists Login to continue",
Toast.LENGTH_SHORT).show();
}
else {
// If sign in fails, display a message to the user.
Log.w("TAG", "createUserWithEmail:failure", task.getException());
Toast.makeText(getApplicationContext(), "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
}
});
}
catch (Exception e){
Toast.makeText(getApplicationContext(), "Error - "+e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}

答案1

得分: 3

声明*private static ArrayList<String> userNames;*是静态的。这意味着您可以直接访问数组列表,而不需要使用访问器方法(get..)。您不需要实例化RegisterActivity来访问数组列表。因此,

adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, RegisterActivity.userNames);

如果您想继续使用getUserNames(),那么也将其声明为静态,并通过类名调用它。

英文:

The declaration of private static ArrayList<String> userNames; is static. That implies you can access the arraylist directly using

RegisterActivity.userNames

without using an accessor method (get..). You do not need to instantiate RegisterActivity to have access to the arraylist. Hence

adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, RegisterActivity.userNames);

If you want to maintain the use of getUserNames(), then declare it as static as well and call it via class name.

答案2

得分: 1

你不能只是调用以下方式来创建注册活动:

RegisterActivity registerActivity = new RegisterActivity();

根据我理解,你有一个注册活动,在那里你填充了用户列表。然后,你转到所有用户活动,在那里你访问了这个特定的列表。如果是这种情况,你可以通过以下方式简单地将你的列表传递给AllUser活动:

intent.putStringArrayListExtra()
英文:

You can't create your register activity by simply calling :

RegisterActivity registerActivity = new RegisterActivity();

From what I understood you have ur register activity where u populate ur users in the list. Then you move to all users activity where you are accessing this particular list. If that is the scenario, you can simply pass your list to you AllUser activity through ,

intent.putStringArrayListExtra()

答案3

得分: 1

在导航到其他活动时(不通过捆绑传递此数据),实际上您正在丢失这些数据。

尝试将userNames保存在另一个常规类中(使用单例模式),该类保存此列表,然后您将能够获取这些数据通过捆绑传递此数据 - 推荐的方式。

英文:

While navigating to other Activity (without passing this data through a bundle) you're actually losing this data

Try saving userNames in another regular class (use singleton pattern) that holds this list and then you'll be able to fetch this data OR pass this data through a bundle - preferred way.

答案4

得分: 1

问题不在于你访问数组列表类的位置,而在于你访问的时间。更具体地说,是在你将其传递给其他活动时的时间点。

在你当前的代码中,在for(String n : muserNames)运行时,userNames.add(userName) 尚未执行。要了解为什么会这样,请阅读:https://stackoverflow.com/questions/50434836/getcontactsfromfirebase-method-return-an-empty-list/50435519#50435519

为解决这个问题,你需要确保在启动新活动之前读取所有数据。最简单的方法是:

  1. 使用 ValueEventListener 而不是 ChildEventListener,这样你可以在一次 onDataChange 调用中获取所有数据。
  2. 然后在 onDataChange 中启动另一个活动。

在代码中,可以这样做:

FirebaseDatabase.getInstance().getReference("User_data").addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
            userName = snapshot.child("name").getValue().toString();
            Log.d("TaguserName", userName);
            userNames.add(userName);
            for(String user_Name : userNames)
            Log.d("TagArrayList", user_Name);
        }
        Intent intent = new Intent(getApplicationContext(), AllUsers.class);
        intent.putExtra("From", "Register");
        startActivity(intent);
        finish();
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
});
英文:

The problem is not where you access the array list class, but when you access it. Or more specifically, when you put it pass it to the other activity.

In your current code, by the time your for(String n : muserNames) runs, none of the userNames.add(userName) has run yet. To learn more about why that is, read: https://stackoverflow.com/questions/50434836/getcontactsfromfirebase-method-return-an-empty-list/50435519#50435519

To address this problem, you need to make sure all data is read, before you start the new activity. The easiest way to do that is to:

  1. Use a ValueEventListener instead of a ChildEventListener, so that you get all data in a single call to onDataChange.
  2. Then start the other activity from within onDataChange.

In code that'd be something like:

FirebaseDatabase.getInstance().getReference(&quot;User_data&quot;).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
userName = snapshot.child(&quot;name&quot;).getValue().toString();
Log.d(&quot;TaguserName&quot;, userName);
userNames.add(userName);
for(String user_Name : userNames)
Log.d(&quot;TagArrayList&quot;, user_Name);
}
Intent intent = new Intent(getApplicationContext(), AllUsers.class);
intent.putExtra(&quot;From&quot;, &quot;Register&quot;);
startActivity(intent);
finish();
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}

huangapple
  • 本文由 发表于 2020年8月13日 20:46:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/63395486.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定