如何使用共享首选项存储和检索recyclerview数据

时间:2016-03-17 13:03:48

标签: java android sharedpreferences android-arrayadapter

我需要存储由recyclerview检索的数据并显示它们以供离线使用。

以下是我的代码:

RecyclerViewFragment

public class HomeFragment extends Fragment implements OnClickListener {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    this.mContext = getActivity().getApplicationContext();
    mView = inflater.inflate(R.layout.fragment_home, container, false);
    initializeView();
    getPosts();
    return mView;
}

private void initializeView() {
    postsList = (RecyclerView) mView.findViewById(R.id.postsList);
    pBar = (LinearLayout) mView.findViewById(R.id.pBar2);
    mFabButton = (FloatingActionButton) mView.findViewById(R.id.fabButton);
    mFabButton.setOnClickListener(this);
    mFabButton.setRippleColor(getActivity().getResources().getColor(R.color.accentColor));
    //layout manager
    notice = (TextView) mView.findViewById(R.id.notice);
    layoutManager = new LinearLayoutManager(getActivity());
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    postsList.setLayoutManager(layoutManager);
    mPostsItems = new ArrayList<PostsItem>();
    mHomeListAdapter = new HomeListAdapter(getActivity(), mPostsItems);
    postsList.setAdapter(mHomeListAdapter);
    mSwipeRefreshLayout = (SwipeRefreshLayout) mView.findViewById(R.id.swipeHome);
    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

        @Override
        public void onRefresh() {
            M.L("called");
            // Refresh items
            setCurrentPage(1);
            getPosts();
        }
    });
    //setting up our OnScrollListener
    postsList.addOnScrollListener(new HidingScrollListener(layoutManager) {
        @Override
        public void onHide() {
            FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mFabButton.getLayoutParams();
            int fabBottomMargin = lp.bottomMargin;
            mFabButton.animate()
                    .translationY(mFabButton.getHeight() + fabBottomMargin)
                    .setInterpolator(new AccelerateInterpolator(2))
                    .start();
        }

        @Override
        public void onShow() {
            mFabButton.animate()
                    .translationY(0)
                    .setInterpolator(new DecelerateInterpolator(2))
                    .start();
        }

        @Override
        public void onLoadMore(int currentPage) {
        }
    });

}


@Override
public void onDestroy() {
    super.onResume();
}

public void getPosts() {
    PostsAPI mPostsAPI = APIService.createService(PostsAPI.class, M.getToken(getActivity()));

    pBar.setVisibility(View.VISIBLE);
    mFabButton.setVisibility(View.GONE);
    postsList.setVisibility(View.GONE);
    mPostsAPI.getPosts(getCurrentPage(), new Callback<List<PostsItem>>() {
        @Override
        public void success(List<PostsItem> postsItems, retrofit.client.Response response) {
            updateView(postsItems);

            notice.setVisibility(View.GONE);
            pBar.setVisibility(View.GONE);
            mFabButton.setVisibility(View.VISIBLE);
            postsList.setVisibility(View.VISIBLE);
        }

        @Override
        public void failure(RetrofitError error) {
            M.T(getActivity(), getString(R.string.ServerError));
            pBar.setVisibility(View.GONE);
            notice.setVisibility(View.VISIBLE);
        }
    });
}

private void updateView(List<PostsItem> postsItems) {

    if (getCurrentPage() != 1) {
        List<PostsItem> oldItems = mHomeListAdapter.getPosts();
        oldItems.addAll(postsItems);
        mHomeListAdapter.setPosts(oldItems);
    } else {
        mHomeListAdapter.setPosts(postsItems);
    }
    if (mSwipeRefreshLayout.isRefreshing()) {
        mSwipeRefreshLayout.setRefreshing(false);
    }
}

@Override
public void onClick(View v) {
    if (v.getId() == R.id.fabButton) {
        mIntent = new Intent(getActivity(), SendPhotoActivity.class);
        startActivity(mIntent);
    }
}
public int getCurrentPage() {
    return currentPage;
}

public void setCurrentPage(int currentPage) {
    this.currentPage = currentPage;
}
}

RecyclerItemClass

public class PostsItem {
private int id;
public String status;
public String image;
private String date;
private String place;
private String youtube;
//private String link;
private int views;
private int ownerID;
private int privacy;
private int likes;
private int comments,totalComments;
private String ownerName;
private String ownerUsername;
private String ownerPicture;
private boolean liked;
private LinkModel link;

public PostsItem() {

}

public int getTotalComments() {
    return totalComments;
}

public void setTotalComments(int totalComments) {
    this.totalComments = totalComments;
}

public String getPlace() {
    return place;
}

public void setPlace(String place) {
    this.place = place;
}

public String getYoutube() {
    return youtube;
}

public void setYoutube(String youtube) {
    this.youtube = youtube;
}

public LinkModel getLink() {
    return link;
}

public void setLink(LinkModel link) {
    this.link = link;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getOwnerUsername() {
    return ownerUsername;
}

public void setOwnerUsername(String ownerUsername) {
    this.ownerUsername = ownerUsername;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public int getViews() {
    return views;
}

public void setViews(int views) {
    this.views = views;
}

public int getLikes() {
    return likes;
}

public void setLikes(int uses) {
    this.likes = uses;
}

public int getComments() {
    return comments;
}

public void setComments(int uses) {
    this.comments = uses;
}


public String getOwnerName() {
    return ownerName;
}

public void setOwnerName(String ownerName) {
    this.ownerName = ownerName;
}

public int getPrivacy() {
    return privacy;
}

public void setPrivacy(int privacy) {
    this.privacy = privacy;
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

public String getOwnerPicture() {
    return ownerPicture;
}

public void setOwnerPicture(String ownerPicture) {
    this.ownerPicture = ownerPicture;
}

public String getDate() {
    return date;
}

public void setDate(String date) {
    this.date = date;
}

public int getOwnerID() {
    return ownerID;
}

public void setOwnerID(int ownerID) {
    this.ownerID = ownerID;
}

public boolean isLiked() {
    return liked;
}

public void setLiked(boolean liked) {
    this.liked = liked;
}


}

2 个答案:

答案 0 :(得分:0)

/* I not worked with retrofit library,In your background process when you are parsing the json just use */

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("id", id);
editor.putString("status", status); 
editor.apply();

/* For getting the shared Pref */
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
String id = sharedPreferences.getString("id", "default value");
String status = sharedPreferences.getString("status", "default value");

答案 1 :(得分:0)

/* add this line of code to ur fragment or activity here you get the arraylist. */ 

private MyOrderDatabase myOrder_db;
myOrder_db = MyOrderDatabase.getInstance(getActivity());
myOrderArrayLists = (ArrayList<OrderPogo>) myOrder_db.getAllOrder();

/ *创建一个sqlite表并添加这样的返回List * /

的方法
public void addOrder(HashMap<String, String> orderHashMap) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_ID, orderHashMap.get(KEY_ID));
    values.put(KEY_LOADINGLOCATION,       orderHashMap.get(KEY_LOADINGLOCATION));
    values.put(KEY_LOCATION_DISTANCE, orderHashMap.get(KEY_LOCATION_DISTANCE));
    values.put(KEY_UNLOADINGLOCATION, orderHashMap.get(KEY_UNLOADINGLOCATION));
    values.put(KEY_QUANTITY, orderHashMap.get(KEY_QUANTITY));
    values.put(KEY_MATERIALNAME, orderHashMap.get(KEY_MATERIALNAME));
    values.put(KEY_SCHEDULE_DATE, orderHashMap.get(KEY_SCHEDULE_DATE));
    values.put(KEY_STATUS_NAME, orderHashMap.get(KEY_STATUS_NAME));
    values.put(KEY_TRUCK_TYPE, orderHashMap.get(KEY_TRUCK_TYPE));

// values.put(KEY_NMBR_OF_TRUCK,orderHashMap.get(KEY_NMBR_OF_TRUCK)); // values.put(KEY_COST_PER_TRUCK,orderHashMap.get(KEY_COST_PER_TRUCK)); // values.put(KEY_QUOTE_TOTAL_AMOUNT,orderHashMap.get(KEY_QUOTE_TOTAL_AMOUNT)); // values.put(KEY_QUOTES_TRUCK_TYPE,orderHashMap.get(KEY_QUOTES_TRUCK_TYPE));

    values.put(KEY_TRANSIT_PERIOD, orderHashMap.get(KEY_TRANSIT_PERIOD));
    values.put(KEY_QUOTE_AMOUNT, orderHashMap.get(KEY_QUOTE_AMOUNT));




    db.insert(TABLE_MYORDER_CONTENT, null, values);
    db.close();
}

public List<OrderPogo> getAllOrder() {
ArrayList<OrderPogo> orderList = new ArrayList<OrderPogo>();
String selectQuery = "";
selectQuery = "SELECT * FROM " + TABLE_MYORDER_CONTENT;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
OrderPogo orderPogo = new OrderPogo();
                  orderPogo.setLoadingLocation(cursor.getString(cursor.getColumnIndex(KEY_LOADINGLOCATION)));
                    orderPogo.setUnloadingLocation(cursor.getString(cursor.getColumnIndex(KEY_UNLOADINGLOCATION)));
                    orderPogo.setDistance(cursor.getString(cursor.getColumnIndex(KEY_LOCATION_DISTANCE)));
                    orderPogo.setTonnes(cursor.getString(cursor.getColumnIndex(KEY_QUANTITY)));
                    orderPogo.setMaterial(cursor.getString(cursor.getColumnIndex(KEY_MATERIALNAME)));
                    orderPogo.setDate(cursor.getString(cursor.getColumnIndex(KEY_SCHEDULE_DATE)));
                    orderPogo.setFlag(cursor.getString(cursor.getColumnIndex(KEY_STATUS_NAME)));
                    orderPogo.setTransitPeriod(cursor.getString(cursor.getColumnIndex(KEY_TRANSIT_PERIOD)));
                    orderPogo.setWaiting(cursor.getString(cursor.getColumnIndex(KEY_QUOTE_AMOUNT)));
                    orderPogo.setTruckType(cursor.getString(cursor.getColumnIndex(KEY_TRUCK_TYPE)));

orderList.add(orderPogo);
} while (cursor.moveToNext());
}
cursor.close();
db.close();

return orderList;
}