如何存储和检索RecyclerView项目以供离线使用

时间:2016-12-21 18:39:42

标签: java android realm offline

伙计们请不要将此问题视为重复,因为我在我的应用中找不到任何简单或简单的域实现。我正在创建一个聊天应用程序,我想要做的是让用户能够访问和阅读他收到的早期消息,即使没有互联网连接。

简而言之,我希望我的应用程序在没有互联网连接的情况下仍可访问,但我发现很难做到这一点,因为我是本地数据存储的新手。

以下是我的细读代码:

片段

public class ChatFragment extends Fragment {

public RecyclerView mChatsList;
public View mView;
public List<ChatsModel> mChatsModel;
public ChatsAdapter mChatsAdapter;
private Realm realm;


public ChatFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    mView = inflater.inflate(R.layout.fragment_chat, container, false);
    ((AppCompatActivity) getActivity()).getSupportActionBar().setShowHideAnimationEnabled(true);
    initUI();
    realm = Realm.getDefaultInstance();
    return mView;
}

//Method and views initializer
public void initUI() {

    mChatsList = (RecyclerView) mView.findViewById(R.id.chatsList);

    LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());

    mChatsModel = new ArrayList<ChatsModel>();
    mChatsAdapter = new ChatsAdapter(getActivity(), mChatsModel);
    mChatsList.setLayoutManager(layoutManager);
    mChatsList.setHasFixedSize(true);
    mChatsAdapter.notifyDataSetChanged();
    mChatsList.setAdapter(mChatsAdapter);
    RecyclerView.ItemAnimator itemAnimator = new DefaultItemAnimator();
    itemAnimator.setAddDuration(1000);
    itemAnimator.setRemoveDuration(1000);
    mChatsList.setItemAnimator(itemAnimator);
    prepareItems();

    Realm realm = Realm.getInstance(getActivity());
    realm.executeTransaction(new Realm.Transaction() {
        @Override
        public void execute(Realm realm) {
            ChatsModel chat = realm.createObject(ChatsModel.class);
            chat.setUsername("username");
            chat.setDate("date");
            chat.setPicture("Picture");
        }
    }, new Realm.Transaction.Callback() {
        @Override
        public void onSuccess() {
            Main.Mess(getString(R.string.real_sucess));
        }

        @Override
        public void onError(Exception e) {
            Main.Mess(getString(R.string.real_error));
        }
    });

}



// This is a simple method to add items to our recyclerview
private void prepareItems() {
    Rests mRests = RestService.createService(Rests.class, Session.getToken(getActivity()));
    mRests.suggest(new Callback<List<ChatsModel>>() {
        @Override
        public void success(List<ChatsModel> mChatsModel, Response response) {
            RealmList<ChatsModel> mChatsModel2 = new RealmList<ChatsModel>();
            mChatsAdapter.setUsers(mChatsModel);

        }

        @Override
        public void failure(RetrofitError error) {
            Main.Mess(getString(R.string.server_error));
        }
    });
}

}

我的适配器

public class ChatsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
private RealmList<ChatsModel> mChatsModel;
private Realm realm;
public Activity mActivity;

public ChatsAdapter(@NonNull Activity mActivity) {
    super();
    this.mChatsModel = new RealmList<>();
    this.realm = Realm.getDefaultInstance();
    this.mActivity = mActivity;
}


@Override
public RecyclerView.ViewHolder onCreateViewHolder (ViewGroup parent, int viewType) {
    if(viewType == TYPE_HEADER) {
        View v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.ad_view, parent, false);
        return new HeaderViewHolder (v);
    } else if(viewType == TYPE_ITEM) {
        View v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.chats_item, parent, false);
        return new ContentViewHolder (v);
        }
    return null;
}

private ChatsModel getItem (int position) {
    return mChatsModel.get (position);
}

@Override
public void onBindViewHolder (RecyclerView.ViewHolder holder, final int position) {
    if (holder instanceof HeaderViewHolder) {
        HeaderViewHolder headerHolder = (HeaderViewHolder) holder;
        if (Constant.SHOW_ADS) {
            headerHolder.mAdView.setVisibility(View.VISIBLE);
            AdRequest adRequest = new AdRequest.Builder().build();
            headerHolder.mAdView.loadAd(adRequest);
        } else {
            headerHolder.mAdView.setVisibility(View.GONE);
        }
    }else if (holder instanceof ContentViewHolder) {
        ContentViewHolder contentHolder = (ContentViewHolder) holder;
        ChatsModel item  = getItem (position - 1);

        contentHolder.username.setText(item.getUsername());
        contentHolder.date.setText(item.getDate());
        contentHolder.message.setText(item.getMessage());

        Picasso.with(mActivity.getApplicationContext())
                .load(Constant.IMAGE_SMALL + item.getPicture())
                .error(R.drawable.user)
                .into(contentHolder.picture);
    }
}

@Override
public int getItemViewType (int position) {
    if(isPositionHeader (position)) {
        return TYPE_HEADER;
    }
    return TYPE_ITEM;
}

public void setUsers(RealmList<ChatsModel> friendsItems) {
    this.mChatsModel = friendsItems;
    notifyDataSetChanged();
}

public List<ChatsModel> getSuggestionsModel() {
    return this.mChatsModel;
}

private boolean isPositionHeader (int position) {
    return position == 0;
}


@Override
public int getItemCount () {
    return mChatsModel.size ();
}


public class HeaderViewHolder extends RecyclerView.ViewHolder {
    public AdView mAdView;

    public HeaderViewHolder(View itemView) {
        super(itemView);
        mAdView = (AdView) itemView.findViewById(R.id.ad_view);
    }
}
public class ContentViewHolder extends RecyclerView.ViewHolder {

    public ImageView picture;
    public TextView username, date, message;
    public LinearLayout chat;

    public ContentViewHolder(View v) {
        super(v);
        picture = (ImageView) v.findViewById(R.id.picture);
        username = (TextView) v.findViewById(R.id.username);
        date = (TextView) v.findViewById(R.id.date);
        message = (TextView) v.findViewById(R.id.message);
    }
}
}

好的,那就是我的代码。

2 个答案:

答案 0 :(得分:1)

您可以使用 SQLite数据库离线存储聊天记录,观看this YouTube tutorial,这种情况很广泛,但您可以跳过某些部分。

下载/发送聊天消息时,将它们镜像到数据库中并使用数据库和仅限数据库作为RecyclerView的数据源(永远不要让任何在线数据直接进入列表,始终首先将它存储在数据库中,并在将其放入布局时从数据库中读取它。)

为了提高性能,您可以在内存中存储相关的聊天消息(例如,在单独的ArrayList中)而不是始终从您刚写入的数据库中读取数据

答案 1 :(得分:0)

正如@geisshirt在评论中所说,使用RealmRecyclerViewAdapter代替RecyclerView.Adapter。关于你可以在official doc找到的android领域适配器的几个词。

另外,您可以查看RealmRecyclerViewAdapter example