在Android中使用Realm添加信息后,数据不会立即更新 [英] Data is not updated promptly after adding the information using Realm in Android

查看:127
本文介绍了在Android中使用Realm添加信息后,数据不会立即更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的App中实现了Realm数据库.首先,我想显示一些预置数据.到现在为止,我这里只有三个数据.我已经实现了一个对话框片段,该片段曾用于在Realm数据库中添加数据.我已经阅读了Realm的官方文档.但是Adapter类的实现对我来说是如此复杂.因此,我在Adpater类中使用了RecyclerView.Adapter.现在我面临的问题是,添加信息后,数据无法立即显示.数据没有快速更新.再次单击添加按钮后显示.在这种情况下,我无法确定问题所在.如果此代码的编写不好,有人建议我也很高兴.对不起,我的英语不好.

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.

编辑的适配器类 这是我的Adpater类

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

编辑过的活动记录,我的活动分类为

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

   }
}

推荐答案

使用 realm-android-适配器:

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

您需要做

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

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

这篇关于在Android中使用Realm添加信息后,数据不会立即更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆