简体   繁体   中英

Converting Facebook post ID from String to int

I am making a news feed where I retrieve Facebook posts from a specific Facebook page. I retrieve those posts with help of the Facebook Graph API. I have a FeedItem which has an ID (int). The ID is also used to check which item is at the current position (Recyclerview).

The problem is that Facebook gives the posts a String ID. I have no idea how I can possibly convert this so that it will work with my application.

My Adapter:

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

private ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private List<FeedItem> mFeedItems;
private Context mContext;

public FeedListAdapter(List<FeedItem> pFeedItems, Context pContext) {
    this.mFeedItems = pFeedItems;
    this.mContext = pContext;
}

/* Create methods for further adapter use.*/
@Override
public ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
    View feedView = LayoutInflater.from(parent.getContext())
                                  .inflate(R.layout.feed_item, parent, false);
    return new ViewHolder(feedView);
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    holder.populateRow(getFeedItem(position));
}

@Override
public long getItemId(int position) {
    return mFeedItems.get(position).getId();
}

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

private FeedItem getFeedItem(int position) {
    return mFeedItems.get(position);
}

class ViewHolder extends RecyclerView.ViewHolder implements OnClickListener {

    private ImageView mProfilePic;
    private TextView mName;
    private TextView mTimestamp;
    private TextView mTxtStatusMsg;
    private FeedImageView mFeedImage;

    //initialize the variables
    ViewHolder(View view) {
        super(view);
        mProfilePic = (ImageView) view.findViewById(R.id.feedProfilePic);
        mName = (TextView) view.findViewById(R.id.feedName);
        mTimestamp = (TextView) view.findViewById(R.id.feedTimestamp);
        mTxtStatusMsg = (TextView) view.findViewById(R.id.feedStatusMessage);
        mFeedImage = (FeedImageView) view.findViewById(R.id.feedImage);
        view.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

    }

    private void populateRow(FeedItem pFeedItem) {
        getProfilePic(pFeedItem);

        mName.setText(pFeedItem.getName());

        mTimestamp.setText(pFeedItem.getTimeStamp());

        mTxtStatusMsg.setText(pFeedItem.getStatus());

        getStatusImg(pFeedItem);
    }

    private void getProfilePic(FeedItem pFeedItem) {
        imageLoader.get(pFeedItem.getProfilePic(), new ImageListener() {
            @Override
            public void onResponse(ImageContainer response, boolean arg1) {
                if (response.getBitmap() != null) {
                    // load image into imageview
                    mProfilePic.setImageBitmap(response.getBitmap());
                }
            }

            @Override
            public void onErrorResponse(final VolleyError pVolleyError) {

            }
        });
    }

    private void getStatusImg(FeedItem pFeedItem) {
        if (pFeedItem.getImage() != null) {
            mFeedImage.setImageUrl(pFeedItem.getImage(), imageLoader);
            mFeedImage.setVisibility(View.VISIBLE);
            mFeedImage
                    .setResponseObserver(new FeedImageView.ResponseObserver() {
                        @Override
                        public void onError() {
                        }

                        @Override
                        public void onSuccess() {
                        }
                    });
        } else {
            mFeedImage.setVisibility(View.GONE);
        }
    }
}

My FeedFragment:

public class FeedFragment extends android.support.v4.app.Fragment {

private static final String TAG = FeedFragment.class.getSimpleName();
private FeedListAdapter mListAdapter;
private List<FeedItem> mFeedItems;
private RecyclerView mRecyclerView;
private String FACEBOOKURL = "**URL OF MY FB-POSTDATA**";

// newInstance constructor for creating fragment with arguments
public static FeedFragment newInstance() {
    FeedFragment fragment = new FeedFragment();
    return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout resource file
    View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_feed, container, false);

    initRecyclerView(view);
    initCache();

    return view;
}

@Override
public void onStart() {
    super.onStart();
}

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

private void initRecyclerView(View pView) {
    mRecyclerView = (RecyclerView) pView.findViewById(R.id.fragment_feed_recyclerview);
    LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.setHasFixedSize(false);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mRecyclerView.setNestedScrollingEnabled(true);
    }

    mFeedItems = new ArrayList<>();

    mListAdapter = new FeedListAdapter(mFeedItems, getActivity());
    mRecyclerView.setAdapter(mListAdapter);
}

private void initCache() {
    // We first check for cached request
    Cache cache = AppController.getInstance().getRequestQueue().getCache();
    Entry entry = cache.get(FACEBOOKURL);
    if (entry != null) {
        // fetch the data from cache
        try {
            String data = new String(entry.data, "UTF-8");
            try {
                parseJsonFeed(new JSONObject(data));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    } else {
        // making fresh volley request and getting json
        JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
                FACEBOOKURL, null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                VolleyLog.d(TAG, "Response: " + response.toString());
                if (response != null) {
                    parseJsonFeed(response);
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
            }
        });

        // Adding request to volley request queue
        AppController.getInstance().addToRequestQueue(jsonReq);
    }
}
private void parseJsonFeed(JSONObject response) {
    try {
        JSONArray feedArray = response.getJSONArray("data");

        for (int i = 0; i < feedArray.length(); i++) {
            JSONObject feedObj = (JSONObject) feedArray.get(i);

            FeedItem item = new FeedItem();
            item.setId(Integer.parseInt(feedObj.getString("id")));
            item.setName("name of page");

            // Image might be null sometimes
            String image = feedObj.isNull("full_picture") ? null : feedObj
                    .getString("full_picture");
            item.setImage(image);
            // Status message might be null sometimes
            String status = feedObj.isNull("message") ? null : feedObj
                    .getString("message");
            item.setStatus(status);

            item.setProfilePic("**profile picture url**");
            item.setTimeStamp(feedObj.getString("created_time"));

            mFeedItems.add(item);
        }

        // notify data changes to list adapter
        mListAdapter.notifyDataSetChanged();
    } catch (JSONException e) {
        e.printStackTrace();
    }
} }

As I said; I have no idea how to handle this and I figured someone here would maybe have an idea on how to convert this, so that I can use the String that the graph api gives me, and use it as an integer.

If the id is all numeric, you should be able to do this: int id = Integer.valueOf(facebookId)

If you have an undescore you can try this:

public int getIdFromString(String postId) {
    String finalId;
    while (postId.indexOf("_") > 0) {
        finalId = postId.substring(0, postId.indexOf("_"));
        postId = finalId.concat(postId.substring(postId.indexOf("_") + 1));
    }
    return Integer.valueOf(postId);
}

If the value is numeric and you want an integer object, do

Integer id = Integer.valueOf(facebookId);

If you want the primitive type int, then do

int id = Integer.parseInt(facebookId);

or

int id = Integer.valueOf(facebookId);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM