简体   繁体   中英

How to access an arraylist from another class?

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

The declaration of private static ArrayList 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.

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

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.

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: getContactsFromFirebase() method return an empty list

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("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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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