RecyclerView Listview 在 activity 加载时不填充,但在按下后退按钮时填充(有时在多个后退按钮上)

RecyclerView Listview doesn't populate when the activity loads but populates on pressing back button (sometimes on multiple backpress)

我正在使用 firebase 作为我的数据库。当 activity 第一次加载时,我的 recyclerview 不会填充,但它会在 backpress 操作后填充,有时会多次 backpress。

HomeActivity.java

public class HomeActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

//Recycler Contact list variables
private RecyclerView mContactList;

//Firebase Variables

private DatabaseReference rDatabase;
private FirebaseAuth mAuth;
private StorageReference mStorageRef;
private FirebaseAuth.AuthStateListener mAuthListener;
FirebaseUser user;
FirebaseRecyclerAdapter<ContactList,ContactListViewHolder> firebaseRecyclerAdapter;

//Request Contact Constant
private static final int REQUEST_READ_CONTACTS = 0;

private Long contactId;
private Uri downloadUrl = null;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    if (Build.VERSION.SDK_INT >= 23) {
        //do your check here
        mayRequestContacts();
    }

    //initialize Recycler view
    mContactList = (RecyclerView) findViewById(R.id.contact_list);
    mContactList.setHasFixedSize(true);
    mContactList.setLayoutManager(new LinearLayoutManager(this));

   //initialize UI elements
    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    View headView =  navigationView.getHeaderView(0);
    TextView uName = (TextView)headView.findViewById(R.id.userName);
    ImageView dPhoto = (ImageView)headView.findViewById(R.id.imageView);
    TextView mEmail = (TextView)headView.findViewById(R.id.uEmail);

    //initialize Firebase variables
    mStorageRef = FirebaseStorage.getInstance().getReference();
    user = FirebaseAuth.getInstance().getCurrentUser();
    rDatabase = FirebaseDatabase.getInstance().getReference().child("users").child(user.getUid()).child(user.getDisplayName()).child("contacts");
    mAuth = FirebaseAuth.getInstance();
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user == null) {
                // user auth state is changed - user is null
                // launch login activity
                startActivity(new Intent(HomeActivity.this, LoginActivity.class));
                finish();
            }
        }
    };

    if (user != null) {
        // Name, email address, and profile photo Url
        String name = user.getDisplayName();
        String email = user.getEmail();
        Uri photoUrl = user.getPhotoUrl();
        System.out.println(name);
        if(name!=null) {
            uName.setText(name);
            mEmail.setText(email);
        }
        if(photoUrl!=null){


            Picasso.with(this)
                    .load(photoUrl)
                    .into(dPhoto);
        }

        // The user's ID, unique to the Firebase project. Do NOT use this value to
        // authenticate with your backend server, if you have one. Use
        // FirebaseUser.getToken() instead.

    }

    //initialize FirebaseRecyclerAdapter
    firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<ContactList, ContactListViewHolder>(

            ContactList.class,
            R.layout.contact_list_row,
            ContactListViewHolder.class,
            rDatabase

    ) {
        @Override
        protected void populateViewHolder(ContactListViewHolder viewHolder, ContactList model, int position) {

            viewHolder.setName(model.getName());
            viewHolder.setPhone(model.getPhone());

        }

    };

    mContactList.setAdapter(firebaseRecyclerAdapter);        //set adapter for recycler view

    setSupportActionBar(toolbar);   //instantiate toolbar

    //initialize floating action button
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with add contact or agenda", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    //initialize navigation drawer
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(mDrawerToggle);
    mDrawerToggle.syncState();


    navigationView.setNavigationItemSelectedListener(this); //listen if any item selected




}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.

    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();


    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }



    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_importContacts) {
        // Handle the Import Contacts Action

        final ProgressDialog ringProgressDialog = ProgressDialog.show(HomeActivity.this, "Please Wait", "Importing Contacts", true);

        ringProgressDialog.setCancelable(true);

        new Thread(new Runnable() {

            @Override

            public void run() {

                try {


                    //user = FirebaseAuth.getInstance().getCurrentUser(); //Get the currently logged in user information
                    //Uid = user.getUid();    //Get User ID
                    //UName = user.getDisplayName();

                    //Initialize cursor to import contacts
                    ContentResolver cr = getContentResolver();
                    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                            null, null, null, null);

                    assert cur != null;
                    if (cur.getCount() > 0) {
                        while (cur.moveToNext()) {

                            //Get current Contact ID
                            contactId=cur.getLong(cur.getColumnIndex(ContactsContract.Contacts._ID));

                            //Get current Contact Name
                            String cName = cur.getString(cur.getColumnIndex(
                                    ContactsContract.Contacts.DISPLAY_NAME));

                            //Get Current Contact URI
                            Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);

                            //Get Current Contact Photo Uri
                            Uri displayPhotoUri=null;
                            if(Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO)!=null){
                                displayPhotoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);

                            }
                           try {
                                AssetFileDescriptor fd =
                                        getContentResolver().openAssetFileDescriptor(displayPhotoUri, "r");

                            } catch (IOException e) {
                                // return null;
                            }

                            if(contactId!=null && cName!=null && displayPhotoUri!=null){

                                boolean flag = true;

                                Cursor emailCursor = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                                        null,
                                        ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] {contactId.toString()}, null);

                                if(cur.getInt(cur.getColumnIndex(
                                        ContactsContract.Contacts.HAS_PHONE_NUMBER))  <=0){
                                    flag = false;
                                }
                                else{

                                    //Import Contact Photo

                                    StorageReference filepath = mStorageRef.child("users/"+user.getUid()+"/"+contactId+"/contactPhoto").child(displayPhotoUri.getLastPathSegment());
                                    filepath.putFile(displayPhotoUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {


                                        @Override
                                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                                            // System.out.println(photoUri.toString()); //debug point

                                            downloadUrl = taskSnapshot.getDownloadUrl();
                                            rDatabase.child(contactId.toString()).child("photoUrl").setValue(downloadUrl.toString());


                                        }
                                    }).addOnFailureListener(new OnFailureListener() {
                                        @Override
                                        public void onFailure(@NonNull Exception e) {

                                        }
                                    });

                                    //Import Contact Email ID if Any
                                    assert emailCursor != null;
                                    while (emailCursor.moveToNext())
                                    {
                                        String cEmail = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                                        int type = emailCursor.getInt(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                                        rDatabase.child(contactId.toString()).child("email").setValue(cEmail);
                                    }
                                    emailCursor.close();

                                    Cursor pCur = cr.query(
                                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                        null,
                                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
                                        new String[]{contactId.toString()}, null);
                                    while (pCur.moveToNext()) {
                                    String phoneNo = pCur.getString(pCur.getColumnIndex(
                                            ContactsContract.CommonDataKinds.Phone.NUMBER));
                                    //Import Contact Phone No.
                                    rDatabase.child(contactId.toString()).child("phone").setValue(phoneNo);
                                    //Import Contact Name
                                        rDatabase.child(contactId.toString()).child("name").setValue(cName);

                                    }
                                pCur.close();

                            }}

                        }
                    }   cur.close();

                    Thread.sleep(10000);

                } catch (Exception e) {

                    return;

                }

                ringProgressDialog.dismiss();

            }

        }).start();




    } else if (id == R.id.nav_logout) {

        mAuth.signOut();    //Log out user method

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

//Method to request contacts (Required for API 23 and greater)
private boolean mayRequestContacts() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return true;
    }
    if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
        return true;
    }
    if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
        if (checkSelfPermission(Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(HomeActivity.this, "Permission Granted",
                    Toast.LENGTH_LONG).show();
            //File write logic here
            return true;
        }
    } else {

        requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
    }
    return false;
}

public void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListener); //Listen to current user Login status

    mContactList.setAdapter(firebaseRecyclerAdapter); //Set adapter for contact list recycler view

}

@Override
public void onStop() {
    super.onStop();
    if (mAuthListener != null) {
        mAuth.removeAuthStateListener(mAuthListener);
    }
}

//ViewHolder for ContactList Recycler View
public static class ContactListViewHolder extends RecyclerView.ViewHolder{

    View mView;
    TextView contact_Name;
    TextView contact_Phone;

    public ContactListViewHolder(View itemView) {
        super(itemView);

        mView = itemView;
    }

    public void setName(String name){

        contact_Name = (TextView) itemView.findViewById(R.id.ContactName);
        contact_Name.setText(name);
    }

    public void setPhone(String phone){

        contact_Phone = (TextView) itemView.findViewById(R.id.ContactPhone);
        contact_Phone.setText(phone);
    }
}

}

适配器class

public class ContactList {

private String name;
private String phone;

public ContactList(){}

public ContactList(String name, String phone) {
    this.name = name;
    this.phone = phone;
}

public String getPhone() {
    return phone;
}

public void setPhone(String phone) {
    this.phone = phone;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}

content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/content_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="neeti.contactapp.HomeActivity"
tools:showIn="@layout/activity_main">

<android.support.v7.widget.RecyclerView
    android:id="@+id/contact_list"
    android:scrollbars="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

</RelativeLayout>

contact_list_row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:clickable="true"
android:background="?android:attr/selectableItemBackground"
android:orientation="vertical">

<TextView
    android:id="@+id/ContactName"
    android:textColor="@color/ContactName"
    android:textSize="16dp"
    android:textStyle="bold"
    android:layout_alignParentTop="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/ContactPhone"
    android:layout_below="@id/ContactName"
    android:textColor="@color/ContactPhone"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />


</RelativeLayout>

你不见了firebaseRecyclerAdapter.notifyDataSetChanged(); 然后将适配器设置为:

mContactList.setAdapter(firebaseRecyclerAdapter);