Search code examples
androidandroid-fragmentsrealmandroid-alertdialogrealm-mobile-platform

Data is not updated promptly after adding the information using Realm in Android


I have implement Realm database in my App. At first I want to show some prelod data. Till now I have only three data here. I have implement a dialog fragment which I used to add data in Realm database. I have read the official documentation of Realm. But the implementation of Adapter class is so complecated for me. Hence I have used RecyclerView.Adapter in my Adpater class. Now the problem I am facing that After adding the information the data is not showing promptly.The data is not upadted quickly. it is showing after clicking the add button again. I cannot identify what would be the problem in this case. Also I am happy if someone provide me suggessstion if the writing of this code is not good. Sorry for my bad English.

Edited Adapter Class Here is my Adpater class

   public class PersonAdapter extends RealmRecyclerViewAdapter<PersonModel, PersonAdapter.PersonHolder> {

    private RealmResults<PersoneModel> realmResults;
    private List<PersonModel> personModels;
    private Context context;

    public interface PersonListListener {
        void addPerson(PersonModel personModel);
        void editPerson(PersonModel personModel);
    }

    public PersonAdapter(Context context,RealmResults<PersonModel> realmResults) {
        this.realmResults = realmResults;
        this.context = context;
    }

    // create new views (invoked by the layout manager)
    @Override
    public PersonHolder onCreateViewHolder(ViewGroup parent, int viewType) {
       // inflate a new person view
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.colleage_row_layout,parent,false);
        return new PersonHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
        // get the colleague
        final PersonModel person=realmResults.get(position);
        // cast the generic view holder to the specific one
        final PersonHolder holder = (PersonHolder) viewHolder;
        holder.name.setText(person.getName());
        holder.companye.setText(person.getCompany());
        holder.title.setText(person.getTitle());
        holder.cardView.setTag(position);
        holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //editDataInterface.editData(view,position);
                int pos = (int)view.getTag();
                Intent i=new Intent(context,DetailPerson.class);
                i.putExtra("name",person.getName());
                i.putExtra("company",person.getCompany());
                i.putExtra("title",person.getTitle());
                context.startActivity(i);
            }
        });
    }

    // return the size of your data set (invoked by the layout manager)
    public int getItemCount() {
        return realmResults.size();
    }

    public class PersonHolder extends RecyclerView.ViewHolder{

        public CardView cardView;
        public ImageView picture;
        public TextView  name;
        public TextView  company;
        public TextView  title;

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

            name=(TextView)itemView.findViewById(R.id.person_name);
            company=(TextView) itemView.findViewById(R.id.company_name);
            title=(TextView) itemView.findViewById(R.id.job_title);
            cardView=(CardView)itemView.findViewById(R.id.cardview_user);
        }
    }
}

Edited Activity Calss My Activity class is

public class MainActivity extends AppCompatActivity implements PersonAdapter.PersonListListener{

private RecyclerView recyclerView;
private PersonAdapter adapter;
private Realm personRealm;
private List<PersonModel> personObject;
private RealmResults<PersonModel> dataResult;
private static final String DIALOG_TAG = "EmployeeDialog";

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

    // Showing and Enabling clicks on the Home/Up button
    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }
    personRealm = Realm.getDefaultInstance();
    recyclerView = (RecyclerView) findViewById(R.id.person_recycler);

    setUpRecycler();

    if (!Prefs.with(this).getPreLoad()) {
        setRealmData();
    }
    showAllPersons();
}
private void showAllPersons() {
    dataResult = personRealm.where(PersonModel.class).findAll();
    setAdapter(dataResult);
    adapter.notifyDataSetChanged();
}


private void setAdapter(RealmResults<PersonModel> results) {
    adapter = new PersonAdapter(this, results);
    recyclerView.setAdapter(adapter);
    adapter.notifyDataSetChanged();

}
private void setUpRecycler() {
    // use this setting to improve performance if you know that changes
    // in content do not change the layout size of the RecyclerView
    recyclerView.setHasFixedSize(true);
    // use a linear layout manager since the cards are vertically scrollable
    final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(layoutManager);
}

private void setRealmData(){

    List<MyColleagueModel> colleague = new ArrayList<>();
    MyColleagueModel model = new MyColleagueModel();
    model.setId(1 + System.currentTimeMillis());
    model.setName("Name1");
    model.setCompany("Comapny1");
    model.setTitle("Title1");
    colleague.add(model);

    model = new MyColleagueModel();
    model.setId(2 + System.currentTimeMillis());
    model.setName("Name2");
    model.setCompany("Comapny2");
    model.setTitle("Title1");
    colleague.add(model);

    model = new MyColleagueModel();
    model.setId(3 + System.currentTimeMillis());
    model.setName("Name3");
    model.setCompany("Comapny3");
    model.setTitle("Title3");
    colleague.add(model);


    for (MyColleagueModel realmModel : colleague) {
            // Persist the colleague data
            colleagueRealm.beginTransaction();
            colleagueRealm.copyToRealm(realmModel);
            colleagueRealm.commitTransaction();
    }

    Prefs.with(this).setPreLoad(true);

 }


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.recycler_menu, menu);

    final MenuItem item = menu.findItem(R.id.search);
    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();

    if (id == android.R.id.home) {
        finish();
    }
    //onOptionsItemSelected(MenuItem item) add will open dialog box, which allows user to fill required data
    if (id == R.id.addColleague) {
        showAlertDialog();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

private void showAlertDialog() {
    EditColleagueFragment dialog = new EditColleagueFragment();
    //dialog.setPositiveButtonClickListener(this);
    dialog.show(getSupportFragmentManager(), DIALOG_TAG);
    //adapter.notifyDataSetChanged();
}

@Override
protected void onDestroy() {
    if (colleagueRealm!= null)
        colleagueRealm.close();
    super.onDestroy();
}

/*@Override
public void onSaved() {
    dataResult = colleagueRealm.where(MyColleagueModel.class).findAll();
    setAdapter(dataResult);
    adapter.notifyDataSetChanged();
}*/

@Override
public void addPerson(MyColleagueModel colleagueModel) {

}

@Override
public void editPerson(MyColleagueModel colleagueModel) {

   }
}

Solution

  • Using realm-android-adapters:

    dependencies {
        compile 'io.realm:android-adapters:2.1.0'
    }
    

    You need to do

    public class MyColleaguesAdapter extends RealmRecyclerViewAdapter<MyColleagueModel, MyColleaguesAdapter.ColleagueHolder> {   
        public interface ColleagueListListener {
            void addPerson(MyColleagueModel colleagueModel);
            void editPerson(MyColleagueModel colleagueModel);
        }
    
        private final ColleagueListListener colleagueListListener;
    
        public MyColleaguesAdapter(ColleagueListListener colleagueListListener, RealmResults<MyColleagueModel> results) {
            super(results, true);
            this.colleagueListListener = colleagueListListener;
        }
    
        @Override
        public ColleagueHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new ColleagueHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.colleage_row_layout,parent,false));
        }
    
        @Override
        public void onBindViewHolder(ColleagueHolder holder, int position) {
            final MyColleagueModel myColleague = getData().get(position);
            holder.bind(myColleague);
        }
    
        public class ColleagueHolder extends RecyclerView.ViewHolder {
    
            public CardView cardView;
            public ImageView colleaguePicture;
            public TextView  colleagueName;
            public TextView  companyName;
            public TextView  jobTitle;
    
            private MyColleagueModel myColleague;
    
            private final View.OnClickListener listener = new View.OnClickListener() {
                 @Override
                 public void onClick(View view) {
                      colleagueListListener.editPerson(myColleague);
                 }
            }
    
            public ColleagueHolder(View itemView) {
                super(itemView);
                //colleaguePicture=(ImageView)itemView.findViewById(R.drawable.profile_image);
                colleagueName=(TextView)itemView.findViewById(R.id.colleague_name);
                companyName=(TextView) itemView.findViewById(R.id.company_name);
                jobTitle=(TextView) itemView.findViewById(R.id.job_title);
                cardView=(CardView)itemView.findViewById(R.id.cardview_user);
              }
            }
    
            public void bind(MyColleagueModel myColleague) {
                this.myColleague = myColleague;
                holder.colleagueName.setText(myColleague.getName());
                holder.companyName.setText(myColleague.getCompany());
                holder.jobTitle.setText(myColleague.getTitle());
                holder.cardView.setTag(position);
                holder.cardView.setOnClickListener(listener);
            }
     }
    

    and

    public class MyColleaguesPage extends AppCompatActivity implements MyColleaguesAdapter.ColleagueListListener {
    
        private Realm realm;
        private RecyclerView recyclerView;
        private MyColleaguesAdapter adapter;
    
        private static final String DIALOG_TAG = "EmployeeDialog";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.mycolleagues_layout);
    
            // Showing and Enabling clicks on the Home/Up button
            if (getSupportActionBar() != null) {
                getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                getSupportActionBar().setDisplayShowHomeEnabled(true);
            }
            realm = Realm.getDefaultInstance();
            recyclerView = (RecyclerView) findViewById(R.id.colleagues_recycler);
    
            recyclerView.setHasFixedSize(true);
            final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            recyclerView.setLayoutManager(layoutManager);
            adapter = new MyColleaguesAdapter(this, realm.where(MyColleagueModel.class).findAllSortedAsync("id"));
            recyclerView.setAdapter(adapter);
         }
    
         @Override
         protected void onDestroy() {
            super.onDestroy();
            realm.close();
            realm = null;
         }
    }