简体   繁体   English

如何从另一个 class 访问 arraylist?

[英]How to access an arraylist from another class?

In the class Register Activity, I have created ArrayList, and logs show it is being populated.在 class 注册活动中,我创建了 ArrayList,并且日志显示它正在被填充。 But when I access it in AllUsers class, it is empty.但是当我在 AllUsers class 中访问它时,它是空的。

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.在 signup() 活动中,我正在使用 firebase 注册用户,同时我正在向 ArrayList 添加名称,一切正常。 But when i access this ArrayList in the All users class through getUsernames(), it is empty.但是当我通过 getUsernames() 在所有用户 class 中访问这个 ArrayList 时,它是空的。

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

The declaration of private static ArrayList userNames;私有 static ArrayList 用户名的声明; is static.是 static。 That implies you can access the arraylist directly using这意味着您可以使用直接访问 arraylist

RegisterActivity.userNames

without using an accessor method (get..).不使用访问器方法(get..)。 You do not need to instantiate RegisterActivity to have access to the arraylist.您无需实例化 RegisterActivity 即可访问 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.如果您想保持使用getUserNames() ,则将其声明为 static 并通过 class 名称调用它。

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,如果是这种情况,您可以简单地将您的列表传递给您的 AllUser 活动,

intent.putStringArrayListExtra()

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.尝试将用户名保存在另一个包含此列表的常规 class (使用 singleton 模式)中,然后您将能够获取此数据通过捆绑传递此数据 - 首选方式。

The problem is not where you access the array list class, but when you access it.问题不在于访问数组列表 class 的位置,而在于您访问它的时间。 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.在您当前的代码中,当您的for(String n: muserNames)运行时,还没有一个userNames.add(userName)运行。 To learn more about why that is, read: getContactsFromFirebase() method return an empty list要了解有关原因的更多信息,请阅读: getContactsFromFirebase() 方法返回一个空列表

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 .使用ValueEventListener而不是ChildEventListener ,以便在一次调用onDataChange中获取所有数据。
  2. Then start the other activity from within onDataChange .然后从onDataChange中启动其他活动。

In code that'd be something like:在代码中类似于:

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

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

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