NullPointerException while evaluating toString() for anonymous class - java

Trying to convert JSON array to list of objects using Gson library.
Code:
TypeToken<List<Comment>> token = new TypeToken<List<Comment>>() {}; //this line throws the following exception
public class Comment implements Serializable{
#SerializedName("id")
private int mID;
#SerializedName("content")
private String mContent;
#SerializedName("author")
private String mAuthor;
#SerializedName("author_id")
private int mAuthorID;
#SerializedName("author_email")
private String mAuthorEmail;
#SerializedName("date")
private String mDate;
#SerializedName("name")
private String mName;
#SerializedName("image")
private String mImage;
public int getmID() {
return mID;
}
public void setmID(int mID) {
this.mID = mID;
}
public String getmContent() {
return mContent;
}
public void setmContent(String mContent) {
this.mContent = mContent;
}
public String getmAuthor() {
return mAuthor;
}
public void setmAuthor(String mAuthor) {
this.mAuthor = mAuthor;
}
public int getmAuthorID() {
return mAuthorID;
}
public void setmAuthorID(int mAuthorID) {
this.mAuthorID = mAuthorID;
}
public String getmAuthorEmail() {
return mAuthorEmail;
}
public void setmAuthorEmail(String mAuthorEmail) {
this.mAuthorEmail = mAuthorEmail;
}
public String getmDate() {
return mDate;
}
public void setmDate(String mDate) {
this.mDate = mDate;
}
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public String getmImage() {
return mImage;
}
public void setmImage(String mImage) {
this.mImage = mImage;
}
}
public class CommentListingActivity extends BaseActivity implements View.OnClickListener {
private static final String TAG = "CommentListingActivity";
private ListView mListViewComments;
private CommentAdapter mCommentAdapter;
private ArrayList<Comment> mCommentList = new ArrayList<Comment>();
private ProgressBar mProgressBar;
private TextView mTextViewErrorMessage;
private Button mButtonRefresh;
private LinearLayout mLinearLayoutError;
private int mPostID;
private boolean isCommentListLoading = true;
private EditText mEditTextComment;
private ImageView mImageViewSend;
private InputMethodManager mInputMethodManager;
private SwipeRefreshLayout mSwipeRefreshLayout;
private boolean mIsRefreshing = false;
private int mOffset = 0;
private View mProgressBarView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comment_listing);
mPostID = getIntent().getIntExtra("postID",0);
setToolbar();
setToolBarTitle(getString(R.string.commentsLabel));
setToolbarHomeAsUpEnabled(true);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mSwipeRefreshLayout.setRefreshing(false);
mIsRefreshing = true;
mOffset = 0;
fetchComments();
}
});
mListViewComments = (ListView) findViewById(R.id.listViewComments);
mCommentAdapter = new CommentAdapter(this, mCommentList,mImageLoader);
mListViewComments.setAdapter(mCommentAdapter);
mProgressBarView = getLayoutInflater().inflate(R.layout.recyclerview_loading_item,null);
mListViewComments.addFooterView(mProgressBarView);
// set the custom dialog components - text, image and button
mEditTextComment = (EditText) findViewById(R.id.editTextComment);
mImageViewSend = (ImageView) findViewById(R.id.imageViewSend);
mImageViewSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postComment();
}
});
mEditTextComment.requestFocus();
mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mInputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
initProgressBar();
initErrorView();
mListViewComments.setOnScrollListener(new EndlessScrollListener() {
#Override
public boolean onLoadMore(int page, int totalItemsCount) {
mOffset = mOffset + LIST_LIMIT;
mListViewComments.addFooterView(mProgressBarView);
fetchComments();
return true;
}
});
fetchComments();
}
private void fetchComments(){
if (!mIsRefreshing && mCommentAdapter.getCount()==0)
showProgressBar();
HashMap<String,String> parameters = new HashMap<String, String>();
parameters.put("post",String.valueOf(mPostID));
parameters.put("offset",String.valueOf(mOffset));
NetworkUtility.getJSONRquest(this, APIURLs.LIST_COMMENTS, parameters, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Remove loading item
if(mCommentList.size()>0) {
mListViewComments.removeFooterView(mProgressBarView);
}
try {
if(response.getString(API_KEY_STATUS).equalsIgnoreCase(API_RESPONSE_SUCCESS)){
JSONArray jsonArrayComments = response.getJSONArray(API_KEY_DATA);
if(jsonArrayComments.length()>0) {
if (mIsRefreshing) {
mCommentList.clear();
mCommentAdapter.notifyDataSetChanged();
}
TypeToken<List<Comment>> token = new TypeToken<List<Comment>>() {};
mCommentList.addAll((Collection<? extends Comment>) GsonUtility.convertJSONStringToObject(jsonArrayComments.toString(), token));
mCommentAdapter.notifyDataSetChanged();
}
mIsRefreshing = false;
if(mCommentAdapter.getCount()>0) {
showContent();
} else {
if (mOffset == 0)
showError("No comments found.");
}
} else {
mProgressBarView.setVisibility(View.GONE);
if(mCommentAdapter.getCount()>0){
AlertDialogUtility.showErrorMessage(CommentListingActivity.this,getString(R.string.errorLabel),response.getString(API_KEY_MESSAGE),getString(R.string.okLabel),null,null,null);
} else
showError(response.getString(API_KEY_MESSAGE));
}
} catch (JSONException e) {
e.printStackTrace();
mProgressBarView.setVisibility(View.GONE);
if(mCommentAdapter.getCount()>0){
AlertDialogUtility.showErrorMessage(CommentListingActivity.this,getString(R.string.errorLabel),getString(R.string.volleyErrorMessage),getString(R.string.okLabel),null,null,null);
} else {
showError(getString(R.string.volleyErrorMessage));
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mProgressBarView.setVisibility(View.GONE);
if(mCommentAdapter.getCount()>0){
AlertDialogUtility.showErrorMessage(CommentListingActivity.this,getString(R.string.errorLabel),getString(R.string.volleyErrorMessage),getString(R.string.okLabel),null,null,null);
} else {
showError(error.getCause().getMessage());
}
error.printStackTrace();
}
},null,TAG);
}
private void postComment() {
final AppProgressDialog appProgressDialog = new AppProgressDialog(this);
appProgressDialog.setProgressDialogTitle("Posting Comment");
appProgressDialog.setProgressDialogMessage("Please Wait...");
appProgressDialog.showProgressDialog();
try {
final String comment = mEditTextComment.getText().toString();
if (!ValidatorUtility.isBlank(comment) && mPostID!=0) {
JSONObject jsonData = new JSONObject();
jsonData.put("content",comment);
jsonData.put("post",mPostID);
NetworkUtility.postRquestWithBasicAuth(this, APIURLs.POST_COMMENT, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if(response.has("id") && response.getInt("id")>0){
AppToast.toastLong(mContext,"Comment Added");
Comment objComment = new Comment();
if (response.has("author_name"))
objComment.setmAuthor(response.getString("author_name"));
if (response.has("author_email"))
objComment.setmAuthorEmail(response.getString("author_email"));
if (response.has("author"))
objComment.setmAuthorID(response.getInt("author"));
objComment.setmContent(comment);
if (response.has("date"))
objComment.setmDate(response.getString("date"));
if (response.has("id"))
objComment.setmID(response.getInt("id"));
objComment.setmImage(mUser.getImage());
objComment.setmName(mUser.getName());
mCommentList.add(0,objComment);
mCommentAdapter.notifyDataSetChanged();
mEditTextComment.setText(null);
mEditTextComment.clearFocus();
mInputMethodManager.hideSoftInputFromWindow(mEditTextComment.getWindowToken(),0);
showContent();
} else {
AlertDialogUtility.showErrorMessage(CommentListingActivity.this,getString(R.string.errorLabel),"Failed to add comment. Please try again later.",getString(R.string.okLabel),null,null,null);
}
} catch (JSONException e) {
e.printStackTrace();
} finally {
appProgressDialog.dismissProgressDialog();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
appProgressDialog.dismissProgressDialog();
AlertDialogUtility.showErrorMessage(CommentListingActivity.this,getString(R.string.errorLabel),error.getCause().getMessage(),getString(R.string.okLabel),null,null,null);
}
}, jsonData, TAG);
} else {
appProgressDialog.dismissProgressDialog();
}
} catch (Exception e){
e.printStackTrace();
appProgressDialog.dismissProgressDialog();
}
}
private void initProgressBar(){
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
}
private void initErrorView(){
mLinearLayoutError = (LinearLayout) findViewById(R.id.linearLayoutError);
mTextViewErrorMessage = (TextView) findViewById(R.id.textViewErrorMessage);
mButtonRefresh = (Button) findViewById(R.id.buttonRefresh);
mButtonRefresh.setOnClickListener(this);
}
private void showProgressBar(){
mProgressBar.setVisibility(View.VISIBLE);
mLinearLayoutError.setVisibility(View.GONE);
mSwipeRefreshLayout.setVisibility(View.GONE);
}
private void showContent(){
mProgressBar.setVisibility(View.GONE);
mLinearLayoutError.setVisibility(View.GONE);
mSwipeRefreshLayout.setVisibility(View.VISIBLE);
}
private void showError(String message){
mProgressBar.setVisibility(View.GONE);
mLinearLayoutError.setVisibility(View.VISIBLE);
mSwipeRefreshLayout.setVisibility(View.GONE);
mTextViewErrorMessage.setText(message);
}
#Override
public void onClick(View view) {
if(view == mButtonRefresh){
fetchComments();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
KeyboardUtility.closeKeyboard(this,mEditTextComment);
}
}
Exception:
Method threw 'java.lang.NullPointerException' exception. Cannot evaluate app.govindaconnect.mangaltaraproductions.com.views.CommentListingActivity$4$1.toString()
Only 1 JSON objects get converted and added to the list.
What might be causing the exception? Because this is not happening with other classes.

You can try this
replace this line
TypeToken<List<Comment>> token = new TypeToken<List<Comment>>() {};
with this and try
Type token = new TypeToken<List<Comment>>() {}.getType();
List<Comment> commentsList = gson.fromJson(String.valueOf(resultArray), type);

I took JSON array in a string variable and then it started working.

why don't you try Jackson parser for conversion, it's much simpler and easier
example for you :
List<Comment> list=null;
String json="your json array";
ObjectMapper mapper = new ObjectMapper();
try {
list= mapper.readValue(json, new TypeReference<List<Comment>>(){});
} catch (IOException e) {
throw new Exception(e);
}

Related

How to show multiple data source data in single recycle view or adapter using LazyLoading?

The above image is a simple design that I want to develop.
I have four type of different data with different view type like the below image enter image description here. but that is not a problem. problem is the data will come from different API with lazy loading like when user scroll the list from recycle view it will grab the data from the server. My question is how to combine them in a single adapter because I need to use lazy loading .so I can't load whole data at a time so I need to call the different type of API like goal-list API, appraisal API, post API etc. When user scroll. anyone can give me an idea with example. How can I handle that? Also when user will scroll it will call another api likeCount and comment count also. Currently, In my, I am calling single API and show that in the single recycle view. Currently, I am using android architecture component LiveData
Fragment :
public class NewsFeedFragment extends FcaFragment {
private View view;
private RecyclerView postRecyclerView;
private PostsAdapter postsAdapter;
private List<Post> posts;
private TimelineViewModel timelineViewModel;
private ImageView addPostView;
private View addPostPanel;
private long lastApiCallTime;
private SwipyRefreshLayout swipeRefresh;
private long lastScroolItemInPost= 0;
public NewsFeedFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(lastScroolItemInPost < 1) {
initViewModel(1 , 0 , true);
lastScroolItemInPost = 1;
}else {
initViewModel(((int) lastScroolItemInPost + 5), lastScroolItemInPost , true);
lastScroolItemInPost += 5;
}
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ownerActivity);
view = inflater.inflate(R.layout.fragment_news_feed, container, false);
postRecyclerView = (RecyclerView) view.findViewById(R.id.postRecyclerView);
postRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(RecyclerView postRecyclerView, int dx, int dy) {
super.onScrolled(postRecyclerView, dx, dy);
int lastVisiableItemInPostList = linearLayoutManager.findLastVisibleItemPosition();
if(lastScroolItemInPost < lastVisiableItemInPostList)
{
if(lastScroolItemInPost == 1)
{
initViewModel((int) (lastScroolItemInPost + 2), ( lastScroolItemInPost - 2 ) , false);
lastScroolItemInPost += 2;
}else{
initViewModel((int) (lastScroolItemInPost + 2), ( lastScroolItemInPost - 2 ) , false );
lastScroolItemInPost += 2;
}
}
}
});
posts = new ArrayList<>();
postRecyclerView.setLayoutManager(linearLayoutManager);
postsAdapter = new PostsAdapter(ownerActivity,posts,timelineViewModel);
postRecyclerView.setAdapter(postsAdapter);
swipeRefresh = (SwipyRefreshLayout) view.findViewById(R.id.swipeRefresh);
swipeRefresh.setOnRefreshListener(new SwipyRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh(SwipyRefreshLayoutDirection direction) {
if(direction == SwipyRefreshLayoutDirection.TOP){
timelineViewModel.fetchPosts2();
}
if(direction == SwipyRefreshLayoutDirection.BOTTOM){
timelineViewModel.fetchPosts();
}
}
});
return view;
}
private void initViewModel(int lastVisiableItemInPostList , long lastScroolItemInPost , boolean isFirstTimeOpenFeedFragment) {
TimelineViewModel.Factory factory = new TimelineViewModel.Factory(UserPreferences.getToken(ownerActivity), TaskUtils.getMySelfContact(ownerActivity));
timelineViewModel = ViewModelProviders.of(this,factory).get(TimelineViewModel.class);
timelineViewModel.getPostList().observe(this, new Observer<List<Post>>() {
#Override
public void onChanged(#Nullable List<Post> posts) {
postsAdapter.setPostList(posts);
swipeRefresh.setRefreshing(false);
}
});
timelineViewModel.getPostDeleted().observe(this, new Observer<Boolean>() {
#Override
public void onChanged(#Nullable Boolean aBoolean) {
if(aBoolean){
postsAdapter.setPostList(Post.getAll());
}
}
});
timelineViewModel.init( lastVisiableItemInPostList , lastScroolItemInPost ,isFirstTimeOpenFeedFragment);
}
}
ViewModel :
public class TimelineViewModel extends FCViewModel implements PostDetailsDownloadManager.PostDetailDownloadedListener,OnContactReceivedListner{
public TimelineViewModel(String token,Contact user){
super(token);
this.user = user;
post = new MutableLiveData<>();
postDeleted = new MutableLiveData<>();
}
public void init(int lastVisiableItemInPostList , long lastScroolItemInPost , boolean isFirstTimeOpenFeedFragment){
repository =
//postDetailsDownloadManager = ServiceLocator.getServiceLocator().postDetailsDownloadManager;
likePostDownloadManager = ServiceLocator.getServiceLocator().likePostDownloadManager;
likePostDownloadManager.setPostDetailDownloadedListener(new DataDownloadManager.DataDownloadedListener<LikePostTouple>() {
#Override
public void onDataDownloaded(List<LikePostTouple> dataTouple) {
TimelineViewModel.this.post.setValue(Post.getAll());
}
#Override
public void onSingleDataDownloaded(LikePostTouple dataTouple) {
}
});
postDetailDownloadManager = ServiceLocator.getServiceLocator().postDetailDownloadManager;
postDetailDownloadManager.setPostDetailDownloadedListener(new DataDownloadManager.DataDownloadedListener<PostTouple>() {
#Override
public void onDataDownloaded(List<PostTouple> dataTouple) {
TimelineViewModel.this.post.setValue(Post.getAll());
}
#Override
public void onSingleDataDownloaded(PostTouple dataTouple) {
}
});
post.setValue(Post.getAll());
if(isFirstTimeOpenFeedFragment)
{
fetchPosts2();
}
try {
if(Post.getAll().size() > 0)
{
List<Post> tempPosts = Post.getAll();
List<Post> passList = tempPosts.subList( (int) lastScroolItemInPost ,lastVisiableItemInPostList);
fetchLikesOfPosts(passList);
}else{
fetchLikesOfPosts(Post.getAll());
}
} catch (Exception e) {
e.printStackTrace();
}
Log.d("Testing Injecting", repository.toString());
}
public LiveData<List<Post>> getPostList() {
return post;
}
public MutableLiveData<Boolean> getPostDeleted() {
return postDeleted;
}
boolean isContactFetched = false;
public void fetchPosts(){
if(Contact.getAll().size() < 1){
fetchContacts();
return;
}
Map<String,Object> requestData = new HashMap<>();
requestData.put("type",1);
requestData.put("cpid",Post.getLastPid());
isDataLoading = true;
repository.getData(new Repository.DataFetchedListener<List<Post>>() {
#Override
public void onDataFetched(List<Post> posts) {
isDataLoading = false;
Log.d("fetched posts",""+posts.size());
post.setValue(Post.getAll());
fetchPostDetails(posts);
if(posts.size() > 0){
fetchLikesOfPosts(posts);
}
}
},requestData);
}
private boolean isDataLoading = false;
public void fetchPosts2(){
if(Contact.getAll().size() < 1){
fetchContacts();
return;
}
Map<String,Object> requestData = new HashMap<>();
requestData.put("type",2);
requestData.put("cpid", Post.getFirstPid()); // cpid means cursor pid
isDataLoading = true;
repository.getData(new Repository.DataFetchedListener<List<Post>>() {
#Override
public void onDataFetched(List<Post> posts) {
isDataLoading = false;
Log.d("fetched posts",""+posts.size());
post.setValue(Post.getAll());
fetchPostDetails(posts);
if(posts.size() > 0){
fetchLikesOfPosts(posts);
}
}
},requestData);
}
public boolean isDataLoading() {
return isDataLoading;
}
private void fetchContacts() {
contactRepository.getData(new Repository.DataFetchedListener<List<Contact>>() {
#Override
public void onDataFetched(List<Contact> data) {
if(data.size()>0 && !isContactFetched) {
fetchPosts2();
isContactFetched = true;
}
}
},null);
}
#NonNull
private PostTouple getPostToubleFromPost(Post post) throws JSONException {
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String json = gson.toJson(post);
JSONObject postJson = new JSONObject(json);
return new PostTouple(postJson,post.getPid());
}
#NonNull
private LikePostTouple getLkePostToupleFromPost(Post post) throws JSONException {
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String json = gson.toJson(post);
JSONObject postJson = new JSONObject(json);
return new LikePostTouple(postJson,post.getPid());
}
public void giveLike(String token, final long pid){
Map<String,Object> requestData = new HashMap<>();
requestData.put("token",token);
requestData.put("pid",Long.toString(pid));
likeRepository.postData(new Repository.DataFetchedListener<Post>() {
#Override
public void onDataFetched(Post data) {
Log.d("Like post", data.toString());
Post post = getPostById(pid);
post.setLikes(data.getLikes());
post.setComments(data.getComments());
TimelineViewModel.this.post.setValue(TimelineViewModel.this.post.getValue());
fetchLikesOfLikedPost(data);
}
},requestData);
}
private void fetchLikesOfLikedPost(Post data) {
try {
likePostDownloadManager.addItemInQueue(getLkePostToupleFromPost(data));
likePostDownloadManager.startDownload();
} catch (JSONException e) {
e.printStackTrace();
}
}
private Post getPostById(long pid){
List<Post> posts = post.getValue();
for(Post post : posts){
if(post.getPid()==pid){
return post;
}
}
return null;
}
public Contact getSenderContactFromComment(Post post) {
if(post.getPqrc().equals(user.getUserId())){
return user;
}
Contact contact = Contact.getByUserId(post.getPqrc());
return contact;
}
public String getDescriptionForType5(Post post,String message){
try {
PostDetail postDetail = PostDetail.getByPostId(post.getPid());
if(postDetail!=null) {
String qrc = JSonUtils.qrcFromCntOfPostDetails(postDetail.getContent());
int sid = JSonUtils.skillidFromCntOfPostDetails(postDetail.getContent());
if (qrc == null || sid == 0) {
return "";
}
SkillDb skill = SkillDb.getBySId(Integer.toString(sid));
Contact contact = getPosterContact(post.getPqrc());
return contact.getName() + " " + message + " " + skill.getSkillName() + ".";
}
return "";
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public String getDescriptionForPost(Post post, String message){
if(post.getCtype()==1){
return post.getDescr();
}
if(post.getCtype() == 2){
String postDetail = getContent(post);
if (postDetail != null) return Html.fromHtml(""+postDetail+"").toString();
}
if(post.getCtype()==5){
return getDescriptionForType5(post, message);
}
return "";
}
#Nullable
public String getContent(Post post) {
PostDetail postDetail = PostDetail.getByPostId(post.getPid());
if(postDetail!=null){
return postDetail.getContent();
}
return null;
}
public Contact getPosterContact(String qrc){
try {
String userqrc = user.getUserId();
if (userqrc.equals(qrc)) {
return user;
}
}catch (Exception e){
e.printStackTrace();
}
try {
return Contact.getByUserId(qrc);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public void fetchUrlPreview(String url, final UrlMetaDataFetchListener metaDataFetchListener){
String modifiedUrl = !url.contains("http://")&&!url.contains("https://")? "http://"+url : url;
TextCrawler textCrawler = new TextCrawler();
LinkPreviewCallback linkPreviewCallback = new LinkPreviewCallback() {
#Override
public void onPre() {
}
#Override
public void onPos(SourceContent sourceContent, boolean b) {
String imageUrl = sourceContent.getImages().isEmpty()? "" : sourceContent.getImages().get(0);
metaDataFetchListener.onMetaDataFetched(sourceContent.getTitle(),sourceContent.getDescription(), imageUrl);
}
};
textCrawler.makePreview(linkPreviewCallback, modifiedUrl,1);
}
public interface UrlMetaDataFetchListener{
void onMetaDataFetched(String title, String description, String imageUrl);
}
#Override
public void onPostDownloaded(PostTouple postTouple) {
this.post.setValue(Post.getAll());
}
#Override
public void onContactsReceived() {
fetchPosts();
}
public void deletePost(long pid) {
Map<String, Object> requestData = new HashMap<>();
requestData.put("token",token);
requestData.put("pid",pid);
repository.postData(new Repository.DataFetchedListener<Post>() {
#Override
public void onDataFetched(Post data) {
postDeleted.setValue(data!=null);
}
},requestData);
}
public boolean isMyPost(Post post){
return user.getUserId().equals(post.getPqrc());
}
public static class Factory extends ViewModelProvider.NewInstanceFactory {
private String token;
private Contact user;
public Factory(String token,Contact user) {
this.token = token;
this.user = user;
}
#Override
public <T extends ViewModel> T create(Class<T> modelClass) {
return (T) new TimelineViewModel(token,user);
}
}
}
Adapter :
public class PostsAdapter extends RecyclerView.Adapter {
private Context context;
private List<Post> postList;
private int[] badges = {R.drawable.badge1, R.drawable.badge2, R.drawable.badge3};
private List<Integer> randomNumbers = Utils.getRandomNumberList(2,true);
private ArrayDeque<Integer> randomQueue = new ArrayDeque<>(randomNumbers);
private static Map<Long,URLPreview> urlPreviewMap = new HashMap<>();
private TimelineViewModel timelineViewModel;
public PostsAdapter(Context context, List<Post> postList, TimelineViewModel timelineViewModel){
super();
this.context = context;
this.postList = postList;
this.timelineViewModel = timelineViewModel;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.post_item_layout, null);
PostViewHolder postViewHolder = new PostViewHolder(view);
postViewHolder.setIsRecyclable(false);
return postViewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final Post post = postList.get(position);
final PostViewHolder postViewHolder = (PostViewHolder) holder;
final String postDetail = timelineViewModel.getDescriptionForPost(post,context.getResources().getString(R.string.postType5message));
setPostDescription(post, postViewHolder, postDetail);
handlePreviewVisibility(post, postViewHolder);
postViewHolder.setLikes(""+post.getLikes()+" Likes");
postViewHolder.setCommentCount("" + post.getComments() + " Comments");
postViewHolder.setSupDescription("Posted By System");
int randomNumber = getRandomNumber();
postViewHolder.setBadgeIcon(badges[randomNumber]);
setPostLikedIndicator(post, postViewHolder);
postViewHolder.getLikeButtonWrapper().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
giveLikeToPost(post);
if(post.getIsLiked() == 0) {
post.setLikes(post.getLikes() + 1);
postViewHolder.setLikes("" + post.getLikes() + " Likes");
post.setIsLiked(1);
setPostLikedIndicator(post, postViewHolder);
}
}
});
postViewHolder.getCommentPanel().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CommentPostFragment fragment = CommentPostFragment.GetInstance(post.getPid());
ViewUtils.launchFragmentKeepingInBackStack(context,fragment);
}
});
Contact contact = timelineViewModel.getPosterContact(post.getPqrc());
if(contact!=null && TaskUtils.isNotEmpty(contact.getImageToken())){
Utils.setImageToImageView(postViewHolder.getPosterImage(),timelineViewModel.getToken(),contact.getImageToken());
postViewHolder.getPosterNameTextView().setText(contact.getName());
}
postViewHolder.getPostingDate().setText(Utils.getDateFromMilliseconds(post.getdC()));
if(post.getCtype() != 3)
{
postViewHolder.contentImage.setVisibility(View.GONE);
postViewHolder.fullScreenIndicatorIcon.setVisibility(View.GONE);
}
if(post.getCtype() == 3){
setContentOfType3(post, postViewHolder);
}
}
#Override
public void onViewRecycled(RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
PostViewHolder viewHolder = (PostViewHolder) holder;
viewHolder.pTitle.setText("");
viewHolder.pDescription.setText("");
viewHolder.pImage.setImageDrawable(null);
}
private void handlePreviewVisibility(Post post, PostViewHolder postViewHolder) {
if(post.getCtype()==2){
postViewHolder.preview.setVisibility(View.VISIBLE);
}else{
postViewHolder.preview.setVisibility(View.GONE);
}
}
private void handleShowingOptionsIcon(Post post, PostViewHolder postViewHolder) {
if(post.getCtype()!=5 && timelineViewModel.isMyPost(post)){
postViewHolder.options.setVisibility(View.VISIBLE);
}else{
postViewHolder.options.setVisibility(View.GONE);
}
}
private void giveLikeToPost(Post post) {
post.setLikes(post.getLikes()+1);
post.setIsLiked(1);
//notifyDataSetChanged();
timelineViewModel.giveLike(UserPreferences.getToken(context),post.getPid());
}
private void setPostLikedIndicator(Post post, PostViewHolder postViewHolder) {
if(post.getIsLiked()==1) {
postViewHolder.getLikeButton().setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.ic_like_red, null));
}else{
postViewHolder.getLikeButton().setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.ic_like_filled, null));
}
}
private void setPostDescription(final Post post, final PostViewHolder postViewHolder, final String postDetail) {
if(post.getCtype()==2){
String postDescription = "<p>"+ post.getDescr()+"</p>";
postViewHolder.description.setText( Html.fromHtml(postDescription +""+postDetail+"") );
postViewHolder.descriptionContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = !postDetail.contains("http://")&&!postDetail.contains("https://")? "http://"+postDetail : postDetail;
Uri uri = Uri.parse(url);
context.startActivity(new Intent(Intent.ACTION_VIEW,uri));
}
});
URLPreview urlPreview = null;
if((urlPreview=urlPreviewMap.get(post.getPid()))==null) {
timelineViewModel.fetchUrlPreview(postDetail, new TimelineViewModel.UrlMetaDataFetchListener() {
#Override
public void onMetaDataFetched(String title, String description, String imageUrl) {
showURLPreview(title, description, imageUrl, postViewHolder);
urlPreviewMap.put(post.getPid(),new URLPreview(title,description,imageUrl));
}
});
}else {
showURLPreview(urlPreview.getTitle(),urlPreview.getDescription(),urlPreview.getImageUrl(),postViewHolder);
}
}else if(post.getCtype() == 3)
{
String postDescription = post.getDescr();
postViewHolder.description.setText(postDescription);
}
else {
postViewHolder.setDescription(postDetail);
}
}
private void initImageClickListener(final ImageView imageView, final String pictureLink) {
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
List<String> pictureLinks = new ArrayList<String>();
pictureLinks.add(pictureLink);
int[] screenLocation = new int[2];
imageView.getLocationOnScreen(screenLocation);
ImagePagerFragment imagePagerFragment = ImagePagerFragment.newInstance(pictureLinks, 0, screenLocation, imageView.getWidth(), imageView.getHeight());
ViewUtils.launchPopUpFragmentUpdated(context, imagePagerFragment);
}
});
}
private void showURLPreview(String title, String description, String imageUrl, PostViewHolder postViewHolder) {
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(!TaskUtils.isEmpty(imageUrl)) {
Picasso.with(context)
.load(imageUrl)
.into(postViewHolder.pImage);
}
view.findViewById(R.id.description);
postViewHolder.pTitle.setText(title);
postViewHolder.pDescription.setText(description);
}
#Override
public int getItemCount() {
return postList.size();
}
private int getRandomNumber(){
if(!randomQueue.isEmpty()){
return randomQueue.poll();
}
randomQueue = new ArrayDeque<>(randomNumbers);
return randomQueue.poll();
}
public void setPostList(List<Post> postList) {
this.postList = postList;
notifyDataSetChanged();
Log.d("Data rec", postList.size()+"");
}
class PostViewHolder extends RecyclerView.ViewHolder implements PopupMenu.OnMenuItemClickListener {
}
public void setLikes(String likes) {
this.likes.setText(likes);
}
public void setCommentCount(String commentCount)
{
this.commentCount.setText(commentCount);
}
public void setDescription(String description){
this.description.setText(description);
}
public void setSupDescription(String subDescription){
this.supDescription.setText(subDescription);
}
public void setBadgeIcon(int resID){
Utils.setImageViewFromResource(badgeIcon,resID);
}
public ImageView getLikeButton() {
return likeButton;
}
public RelativeLayout getLikeButtonWrapper()
{
return likeButtonWrapper;
}
public ImageView getCommentButton() {
return commentButton;
}
public ImageView getPosterImage() {
return posterImage;
}
public TextView getPosterNameTextView() {
return posterNameTextView;
}
public TextView getPostingDate() {
return postingDate;
}
public RelativeLayout getCommentPanel() {
return commentPanel;
}
#Override
public boolean onMenuItemClick(MenuItem item) {
timelineViewModel.deletePost(postList.get(getAdapterPosition()).getPid());
return false;
}
}
}

How to add Progress Dialog Box

I'm using Fragment to Display the Movies name, poster and reviews and Trailer using API key. I am trying to add progressbar such that when the RecyclerView is loading it will display the progress bar and when loading is complete..it will become invisible.
I tried to put various method but it always gives me error or app compiles and run but crashes.
Below is my MoviesUtil class file
public class MoviesUtil {
private static final Webb WEBB = Webb.create();
private static final String TMDB_API_MOVIES_URL = "http://api.themoviedb.org/3/movie/%s?api_key=%s&page=%s";
private static final String TMDB_API_VIDEOS_URL = "http://api.themoviedb.org/3/movie/%s/videos?api_key=%s";
private static final String TMDB_API_REVIEWS_URL = "http://api.themoviedb.org/3/movie/%s/reviews?api_key=%s";
private static final String TMDB_POSTER_URL = "https://image.tmdb.org/t/p/w185%s";
private static final String TMDB_BACKDROP_URL = "https://image.tmdb.org/t/p/w300%s";
private static final String TYPE_POPULAR = "popular";
private static final String TYPE_TOP_RATED = "top_rated";
private static final String TYPE_FAVORITES = "favorites";
public static boolean isFavorite(Context context, Movie movie) {
Cursor cursor = context.getContentResolver()
.query(MovieContract.CONTENT_URI,
null,
String.format("%s = ? and %s = ?", MovieContract.MOVIE_ID, MovieContract.TYPE),
new String[]{movie.getId() + "", TYPE_FAVORITES},
null
);
boolean isFavorite = cursor.getCount() > 0;
cursor.close();
return isFavorite;
}
public static boolean toggleFavorite(Context context, Movie movie) {
if (isFavorite(context, movie)) {
deleteMovie(context, TYPE_FAVORITES, movie);
return false;
} else {
saveMovie(context, TYPE_FAVORITES, movie);
return true;
}
}
public static void getPopularMovies(Activity activity, MoviesCallback callback) {
getMovies(activity, TYPE_POPULAR, callback);
}
public static void getTopRatedMovies(Activity activity, MoviesCallback callback) {
getMovies(activity, TYPE_TOP_RATED, callback);
}
public static void getFavoritesMovies(Activity activity, MoviesCallback callback) {
getMovies(activity, TYPE_FAVORITES, callback);
}
private static void getMovies(final Activity activity, final String type, final MoviesCallback callback) {
AsyncTask.execute(new Runnable() {
#Override
public void run() {
if (Util.isConnected(activity, false) && !type.equals(TYPE_FAVORITES)) {
getMoviesFromApi(activity, type);
}
getMoviesFromDb(activity, type, callback);
}
});
}
private static void getMoviesFromApi(Activity activity, String type) {
String apiUrl = String.format(TMDB_API_MOVIES_URL, type, activity.getString(R.string.tmdb_api_key), 1);
try {
JSONArray moviesJson = WEBB.get(apiUrl)
.asJsonObject()
.getBody()
.getJSONArray("results");
List<Movie> movies = toMovies(activity, moviesJson);
deleteMovies(activity, type);
saveMovies(activity, type, movies);
} catch (JSONException e) {
e.printStackTrace();
}
}
private static void getMoviesFromDb(Activity activity, String type, final MoviesCallback callback) {
try {
Cursor cursor = activity.getContentResolver()
.query(MovieContract.CONTENT_URI,
null,
MovieContract.TYPE + " = ?",
new String[]{type},
null
);
final List<Movie> movies = toMovies(cursor);
cursor.close();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
callback.success(movies);
}
});
} catch (final Exception e) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
callback.error(e);
}
});
}
}
public static void getReviewsFromApi(final Activity activity, final Movie movie, final ReviewsCallback callback) {
if (Util.isConnected(activity, false)) {
AsyncTask.execute(new Runnable() {
#Override
public void run() {
String apiUrl = String.format(TMDB_API_REVIEWS_URL, movie.getId(), activity.getString(R.string.tmdb_api_key));
final List<Review> reviews = new ArrayList<>();
try {
JSONArray reviewsJson = WEBB.get(apiUrl)
.asJsonObject()
.getBody()
.getJSONArray("results");
reviews.addAll(toReviews(reviewsJson));
} catch (final Exception e) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
callback.error(e);
}
});
}
if (reviews.isEmpty()) {
Review review = new Review();
review.setContent(activity.getString(R.string.no_review_found));
reviews.add(review);
}
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
callback.success(reviews);
}
});
}
});
} else {
Review review = new Review();
review.setContent(activity.getString(R.string.conn_internet));
final List<Review> reviews = new ArrayList<>();
reviews.add(review);
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
callback.success(reviews);
}
});
}
}
private static void saveMovie(final Context context, final String type, final Movie movie) {
AsyncTask.execute(new Runnable() {
#Override
public void run() {
List<Movie> movies = new ArrayList<>();
movies.add(movie);
saveMovies(context, type, movies);
}
});
}
private static void saveMovies(Context context, String type, List<Movie> movies) {
if (movies != null) {
ContentValues[] moviesValues = new ContentValues[movies.size()];
for (int i = 0; i < movies.size(); i++) {
try {
Movie movie = movies.get(i);
ContentValues movieValues = new ContentValues();
movieValues.put(MovieContract.MOVIE_ID, movie.getId());
movieValues.put(MovieContract.TYPE, type);
movieValues.put(MovieContract.TITLE, movie.getTitle());
movieValues.put(MovieContract.OVERVIEW, movie.getOverview());
movieValues.put(MovieContract.POSTER_URL, movie.getPosterUrl());
movieValues.put(MovieContract.BACKDROP_URL, movie.getBackdropUrl());
movieValues.put(MovieContract.TRAILER_URL, movie.getTrailerUrl());
movieValues.put(MovieContract.RELEASE_DATE, Util.toDbDate(movie.getReleaseDate()));
movieValues.put(MovieContract.RATING, movie.getRating());
movieValues.put(MovieContract.ADULT, movie.isAdult() ? 1 : 0);
moviesValues[i] = movieValues;
} catch (Exception ignore) {
}
}
context.getContentResolver()
.bulkInsert(MovieContract.CONTENT_URI, moviesValues);
}
}
private static void deleteMovie(final Context context, final String type, final Movie movie) {
AsyncTask.execute(new Runnable() {
#Override
public void run() {
context.getContentResolver()
.delete(MovieContract.CONTENT_URI,
MovieContract.MOVIE_ID + " = ? and " + MovieContract.TYPE + " = ?",
new String[]{movie.getId() + "", type});
}
});
}
private static void deleteMovies(final Context context, final String type) {
AsyncTask.execute(new Runnable() {
#Override
public void run() {
context.getContentResolver()
.delete(MovieContract.CONTENT_URI,
MovieContract.TYPE + " = ?",
new String[]{type});
}
});
}
private static List<Movie> toMovies(Cursor cursor) {
List<Movie> movies = new ArrayList<>();
while (cursor.moveToNext()) {
Movie movie = new Movie();
movie.setId(cursor.getInt(
cursor.getColumnIndex(MovieContract.MOVIE_ID)));
movie.setTitle(cursor.getString(
cursor.getColumnIndex(MovieContract.TITLE)));
movie.setOverview(cursor.getString(
cursor.getColumnIndex(MovieContract.OVERVIEW)));
movie.setPosterUrl(cursor.getString(
cursor.getColumnIndex(MovieContract.POSTER_URL)));
movie.setBackdropUrl(cursor.getString(
cursor.getColumnIndex(MovieContract.BACKDROP_URL)));
movie.setTrailerUrl(cursor.getString(
cursor.getColumnIndex(MovieContract.TRAILER_URL)));
movie.setReleaseDate(Util.toDate(cursor.getString(
cursor.getColumnIndex(MovieContract.RELEASE_DATE))));
movie.setRating(cursor.getFloat(
cursor.getColumnIndex(MovieContract.RATING)));
movie.setAdult(cursor.getInt(
cursor.getColumnIndex(MovieContract.ADULT)) == 1);
movies.add(movie);
}
return movies;
}
private static List<Movie> toMovies(Context context, JSONArray jsonMovies) {
List<Movie> movies = new ArrayList<>();
if (jsonMovies != null) {
for (int i = 0; i < jsonMovies.length(); i++) {
try {
JSONObject jsonMovie = jsonMovies.getJSONObject(i);
int movieId = jsonMovie.getInt("id");
Movie movie = new Movie();
movie.setId(movieId);
movie.setTitle(jsonMovie.getString("title"));
movie.setOverview(jsonMovie.getString("overview"));
movie.setPosterUrl(String.format(TMDB_POSTER_URL, jsonMovie.getString("poster_path")));
movie.setBackdropUrl(String.format(TMDB_BACKDROP_URL, jsonMovie.getString("backdrop_path")));
movie.setTrailerUrl(getTrailerUrl(context, movieId));
movie.setReleaseDate(Util.toDate(jsonMovie.getString("release_date")));
movie.setRating((float) jsonMovie.getDouble("vote_average"));
movie.setAdult(jsonMovie.getBoolean("adult"));
movies.add(movie);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return movies;
}
private static List<Review> toReviews(JSONArray jsonReviews) {
List<Review> reviews = new ArrayList<>();
if (jsonReviews != null) {
for (int i = 0; i < jsonReviews.length(); i++) {
try {
JSONObject jsonReview = jsonReviews.getJSONObject(i);
Review review = new Review();
review.setAuthor(jsonReview.getString("author"));
review.setContent(jsonReview.getString("content"));
reviews.add(review);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return reviews;
}
private static String getTrailerUrl(Context context, int movieId) {
String apiUrl = String.format(TMDB_API_VIDEOS_URL, movieId, context.getString(R.string.tmdb_api_key));
try {
JSONArray trailersJson = WEBB.get(apiUrl)
.asJsonObject()
.getBody()
.getJSONArray("results");
for (int i = 0; i < trailersJson.length(); i++) {
JSONObject trailerJson = trailersJson.getJSONObject(i);
if (trailerJson.getString("site").toLowerCase().equals("youtube")) {
return "https://youtube.com/watch?v=" + trailerJson.getString("key");
}
}
return "";
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
}
and my Fragment class is
public class MoviesFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener,
RecyclerItemClickSupport.OnItemClickListener {
private static final String ARG_FRAG_TYPE = "fragType";
private static final String ARG_FRAG_TWO_PANE = "twoPane";
public enum Type {
POPULAR,
TOP_RATED,
FAVORITES
}
#State
ArrayList<Movie> movies;
#State
Type fragType;
#State
boolean twoPane;
#BindView(R.id.refresh)
SwipeRefreshLayout refreshView;
#BindView(R.id.movies)
RecyclerView moviesView;
public static MoviesFragment newInstance(Type fragType, boolean twoPane) {
MoviesFragment fragment = new MoviesFragment();
Bundle args = new Bundle();
args.putSerializable(ARG_FRAG_TYPE, fragType);
args.putBoolean(ARG_FRAG_TWO_PANE, twoPane);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Icepick.restoreInstanceState(this, savedInstanceState);
if (getArguments() != null) {
fragType = (Type) getArguments().getSerializable(ARG_FRAG_TYPE);
twoPane = getArguments().getBoolean(ARG_FRAG_TWO_PANE);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_movies_list, container, false);
unbinder = ButterKnife.bind(this, rootView);
init();
return rootView;
}
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
#Override
public void onRefresh() {
movies = null;
updateMovies();
}
#Override
public void onItemClicked(RecyclerView recyclerView, int position, View v) {
showMovieAtPosition(position);
}
#Subscribe(sticky = true)
public void onEvent(UpdateFavoritesEvent event) {
if (fragType == Type.FAVORITES) {
EventBus.getDefault().removeStickyEvent(UpdateFavoritesEvent.class);
onRefresh();
}
}
#Subscribe(sticky = true)
public void onEvent(TwoPaneEvent event) {
twoPane = event.twoPane;
}
#Override
protected void init() {
RecyclerItemClickSupport.addTo(moviesView)
.setOnItemClickListener(this);
moviesView.setLayoutManager(new GridLayoutManager(getContext(), 2));
moviesView.setHasFixedSize(true);
refreshView.setOnRefreshListener(this);
updateMovies();
}
private void updateMovies() {
if (movies == null) {
MoviesCallback callback = new MoviesCallback() {
#Override
public void success(List<Movie> result) {
movies = new ArrayList<>(result);
if (moviesView != null) {
moviesView.setAdapter(new MoviesAdapter(getContext(), movies));
}
refreshView.setRefreshing(false);
}
#Override
public void error(Exception error) {
Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
error.printStackTrace();
refreshView.setRefreshing(false);
}
};
switch (fragType) {
case POPULAR:
MoviesUtil.getPopularMovies(getActivity(), callback);
break;
case TOP_RATED:
MoviesUtil.getTopRatedMovies(getActivity(), callback);
break;
case FAVORITES:
MoviesUtil.getFavoritesMovies(getActivity(), callback);
break;
}
} else if (moviesView != null) {
moviesView.setAdapter(new MoviesAdapter(getContext(), movies));
refreshView.setRefreshing(false);
}
}
private void showMovieAtPosition(int position) {
if (movies != null && position <= movies.size() - 1) {
Movie movie = movies.get(position);
EventBus.getDefault().postSticky(new ShowMovieEvent(movie));
if (twoPane) {
getFragmentManager().beginTransaction()
.replace(R.id.movie_detail, new MovieFragment())
.commit();
} else {
startActivity(new Intent(getContext(), MovieActivity.class));
}
}
}
}

java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference Retrofit

I'm trying to use blog id to get JSON object from server. At the moment I'm getting this error
java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()
on a null object reference`.How do I use the post Id to get the full content what am I doing wrong. Please help!!!
MyBlog Adapter:
public class MyBlogAdapter extends RecyclerView.Adapter<BlogViewHolder> {
List<BlogResponse> postsList;
Context context;
public static String blog_Id, blogID;
private LayoutInflater inflater;
public MyBlogAdapter(Context context, List<BlogResponse> postsList){
this.context = context;
this.inflater = LayoutInflater.from(context);
this.postsList = postsList;
}
#Override
public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_view,parent, false);
return new BlogViewHolder(view);
}
#Override
public void onBindViewHolder(BlogViewHolder holder, int position) {
final BlogResponse posts= postsList.get(position);
holder.summary.setText(posts.getBlogExcerpt().trim().toString());
holder.title.setText(posts.getBlogTitle().trim().toString());
// Glide.with(context).load(posts.getBlogThumbnail()).into(holder.cover);
holder.blogHolder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, AnotherSingleView.class);
blog_Id = posts.getBlogId();
intent.putExtra(blogID,blog_Id);
Log.d("MyblogAdapter","Please check blog Id: "+blog_Id);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
Log.d("MyBlogAdapter,","getItemCount"+postsList.size());
return postsList == null ? (0) : postsList.size();
}
}
SecondActivity:
public class AnotherSingleView extends AppCompatActivity {
String postID;
int position;
public TextView blogTitle,blogSub,blogContent;
public ImageView blogPic;
List<SingleBlogPost> singleBlogPosts;
SingleBlogPost singleBlogPost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another_single_view);
Intent intent = getIntent();
Bundle showBlogId = intent.getExtras();
postID = showBlogId.getString(blogID);
Log.d("AnotherSingleView","Please check blog Id: "+postID);
singleBlogPosts = new ArrayList<>();
blogContent = (TextView)findViewById(R.id.blog_content);
blogSub = (TextView) findViewById(R.id.blog_subtitle);
blogTitle =(TextView) findViewById(R.id.blog_title);
blogPic =(ImageView) findViewById(R.id.blog_pix);
singlePostDisplay();
}
private void singlePostDisplay() {
BlogaPI api = ApiClient.getBlogInterface();
Call<List<SingleBlogPost>> call = api.postResponse(postID);
call.enqueue(new Callback<List<SingleBlogPost>>() {
#Override
public void onResponse(Call<List<SingleBlogPost>> call, Response<List<SingleBlogPost>> response) {
singleBlogPosts = response.body();
if (singleBlogPosts != null && !singleBlogPosts.isEmpty() ){
for (SingleBlogPost posts : singleBlogPosts){
Log.d("AnotherSingleView","Please check RESPONSE: "+response.body().toString());
blogTitle.setText(posts.getBlogTitle());
blogSub.setText(posts.getBlogSubtitle());
blogContent.setText(posts.getBlogContent());
// Glide.with(AnotherSingleView.this).load(singlepost.getBlogMedimg()).into(blogPic);
}
}
else{
Toast.makeText(AnotherSingleView.this, "Something is empty", Toast.LENGTH_SHORT).show();
} }
#Override
public void onFailure(Call<List<SingleBlogPost>> call, Throwable t) {
Toast.makeText(AnotherSingleView.this, "check again: "+t.toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
Interface:
public interface BlogaPI {
#GET("blog")
Call<BlogList> response();
#GET("post/{blog_id}")
Call<List<SingleBlogPost>> postResponse(#Path("blog_id") String blog_id);
//Call<List<SingleBlogPost>> postResponse();
}
SingleBlogPost:
public class SingleBlogPost {
#SerializedName("blog_id")
#Expose
private String blogId;
#SerializedName("blog_title")
#Expose
private String blogTitle;
#SerializedName("blog_subtitle")
#Expose
private String blogSubtitle;
#SerializedName("blog_excerpt")
#Expose
private String blogExcerpt;
#SerializedName("blog_content")
#Expose
private String blogContent;
#SerializedName("blog_thumbnail")
#Expose
private String blogThumbnail;
#SerializedName("blog_medimg")
#Expose
private String blogMedimg;
#SerializedName("category_title")
#Expose
private String categoryTitle;
public SingleBlogPost(String blogId,String blogTitle, String blogSubtitle, String blogExcerpt,
String blogContent, String blogThumbnail, String blogMedimg, String categoryTitle){
this.blogId = blogId;
this.blogTitle = blogTitle;
this.blogSubtitle = blogSubtitle;
this.blogExcerpt = blogExcerpt;
this.blogContent = blogContent;
this.blogThumbnail = blogThumbnail;
this.blogMedimg = blogMedimg;
this.categoryTitle = categoryTitle;
}
public String getBlogId() {
return blogId;
}
public void setBlogId(String blogId) {
this.blogId = blogId;
}
public String getBlogTitle() {
return blogTitle;
}
public void setBlogTitle(String blogTitle) {
this.blogTitle = blogTitle;
}
public String getBlogSubtitle() {
return blogSubtitle;
}
public void setBlogSubtitle(String blogSubtitle) {
this.blogSubtitle = blogSubtitle;
}
public String getBlogExcerpt() {
return blogExcerpt;
}
public void setBlogExcerpt(String blogExcerpt) {
this.blogExcerpt = blogExcerpt;
}
public String getBlogContent() {
return blogContent;
}
public void setBlogContent(String blogContent) {
this.blogContent = blogContent;
}
public String getBlogThumbnail() {
return blogThumbnail;
}
public void setBlogThumbnail(String blogThumbnail) {
this.blogThumbnail = blogThumbnail;
}
public String getBlogMedimg() {
return blogMedimg;
}
public void setBlogMedimg(String blogMedimg) {
this.blogMedimg = blogMedimg;
}
public String getCategoryTitle() {
return categoryTitle;
}
public void setCategoryTitle(String categoryTitle) {
this.categoryTitle = categoryTitle;
}
}
Check if the server response is different then null before you do a enhanced for like this:
if(singleBlogPosts!= null) {
for (SingleBlogPosts posts : singleBlogPosts){
Log.d("AnotherSingleView","Please check RESPONSE: "+response.body().toString());
blogTitle.setText(posts.getBlogTitle());
blogSub.setText(posts.getBlogSubtitle());
blogContent.setText(posts.getBlogContent());
// Glide.with(AnotherSingleView.this).load(singlepost.getBlogMedimg()).into(blogPic);
}
}
you question was list iterator,but we can`t see you list use on anywhere,i guess you may be use recyclerView on you data has not get,because get data was asynchronous.try to use data if you can sure it is existing.

How do you do pojo with asynctask json

I take https://jsonplaceholder.typicode.com/users with asynctask but i take to use pojo object .
What should I add code between ? What line should I write and how should i write ?
DataRetriever.java
public DataRetriever(Activity activity) {
activityWeakReference = new WeakReference<>(activity);
current_activity = activityWeakReference.get();
}
#Override
protected void onPreExecute() {
imageView = (ImageView) current_activity.findViewById(R.id.imageView);
if (current_activity != null) {
recyclerView = (RecyclerView) current_activity.findViewById(R.id.recyclerView);
swipeRefreshLayout = (SwipeRefreshLayout) current_activity.findViewById(R.id.swipe_container);
swipeRefreshLayout.setColorSchemeResources(
android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
recyclerView.setHasFixedSize(true);
} else {
Log.d(TAG, "unable to get current activity");
Toast.makeText(current_activity, "unable to get current activity", Toast.LENGTH_SHORT).show();
}
super.onPreExecute();
progressDialog = new ProgressDialog(current_activity);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#SafeVarargs
#Override
protected final Integer doInBackground(List<String>... integers) {
HttpURLConnection httpURLConnection = null;
URL url;
List<String> local_list = integers[0];
type = Integer.parseInt(local_list.get(0));
String jsonString, jsonData;
return_status = 0;
switch (type) {
case 1:
url_string = "https://jsonplaceholder.typicode.com/users";
break;
case 2:
url_string = "https://jsonplaceholder.typicode.com/albums";
recieved_id = Integer.parseInt(local_list.get(1));
title = local_list.get(2);
break;
case 3:
url_string = "https://jsonplaceholder.typicode.com/photos";
recieved_id = Integer.parseInt(local_list.get(1));
title = local_list.get(2);
break;
}
try {
url = new URL(url_string);
httpURLConnection = (HttpURLConnection) url.openConnection();
int statusCode = httpURLConnection.getResponseCode();
if (statusCode == 200) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
while ((jsonData = bufferedReader.readLine()) != null) {
stringBuilder.append(jsonData);
}
jsonString = stringBuilder.toString();
jsonParser(jsonString);
return_status = 1;
} else {
Log.d(TAG, "Some error occurred could'nt fetch data");
Toast.makeText(current_activity, "Some error occurred could'nt fetch data", Toast.LENGTH_SHORT).show();
return_status = 0;
}
publishProgress(local_list);
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
return return_status;
}
private void jsonParser(String jsonString) {
int names_count, id;
String name;
try {
JSONArray jsonArray = new JSONArray(jsonString);
names_count = jsonArray.length();
if (!listValues.isEmpty())
listValues.clear();
if (!pictureValues.isEmpty())
pictureValues.clear();
for (int i = 0; i < names_count; i++) {
JSONObject array_items = jsonArray.getJSONObject(i);
ListValues jsonValues, pictureValue;
switch (type) {
case 1:
id = array_items.optInt("id");
name = array_items.optString("name");
jsonValues = new ListValues(id, name);
listValues.add(jsonValues);
break;
case 2:
id = array_items.optInt("userId");
name = array_items.optString("title");
if (id == recieved_id) {
jsonValues = new ListValues(id, name);
listValues.add(jsonValues);
}
break;
case 3:
id = array_items.optInt("albumId");
name = array_items.optString("title");
String pictureURL = array_items.getString("url");
if (id == recieved_id) {
jsonValues = new ListValues(id, name);
pictureValue = new ListValues(id, pictureURL);
listValues.add(jsonValues);
pictureValues.add(pictureValue);
}
break;
}
}
} catch (JSONException e) {
Log.d(TAG, e.getLocalizedMessage());
}
}
#Override
protected void onProgressUpdate(final List<String>... values) {
List<String> progressList = values[0];
Log.d(TAG, progressList.get(0));
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
switch (type) {
case 1:
new DataRetriever(current_activity).execute(values[0]);
case 2:
new DataRetriever(current_activity).execute(values[0]);
case 3:
new DataRetriever(current_activity).execute(values[0]);
}
}
});
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(final Integer integer) {
if (integer != 0) {
recyclerAdapter = new RecyclerAdapter(listValues);
recyclerView.addItemDecoration(new ListItemDecorator(current_activity.getApplicationContext()));
recyclerView.setAdapter(recyclerAdapter);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(current_activity);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
if (swipeRefreshLayout.isRefreshing())
swipeRefreshLayout.setRefreshing(false);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(current_activity.getApplicationContext(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
String pictureURL = null;
ListValues feed = listValues.get(position);
if (!pictureValues.isEmpty()) {
ListValues feed2 = pictureValues.get(position);
pictureURL = feed2.getValue();
}
String value = feed.getValue();
switch (type) {
case 1:
intent = new Intent(current_activity, AlbumActivity.class);
intent.putExtra("id", (position + 1));
intent.putExtra("value", value);
current_activity.startActivity(intent);
break;
case 2:
intent = new Intent(current_activity, PhotosActivity.class);
intent.putExtra("id", (position + 1));
intent.putExtra("value", value);
current_activity.startActivity(intent);
break;
case 3:
intent = new Intent(current_activity, ImageDisplay.class);
intent.putExtra("imageUrl", pictureURL);
current_activity.startActivity(intent);
break;
}
}
#Override
public void onLongClick(View view, int position) {
}
}));
} else {
// Log.d(TAG, "unable to get data");
if (swipeRefreshLayout.isRefreshing()) {
Toast.makeText(current_activity, "Unable to refresh data! Try opening application again", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(current_activity, "Failed to fetch data! try again", Toast.LENGTH_SHORT).show();
}
}
super.onPostExecute(integer);
progressDialog.dismiss();
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
}
Post.java
public class Post implements Serializable {
#SerializedName("userId")
private int userId;
#SerializedName("name")
#Expose
public String name;
#SerializedName("id")
private int id;
#SerializedName("title")
private String title;
#SerializedName("body")
private String body;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
Your important advice for me
Thank you!
You can easily do that with GSON and POJO
first.. you need to create several model
Post.java
public class Post
{
private String id;
private String phone;
private String username;
private String website;
private Address address;
private String email;
private Company company;
private String name;
//setter and getter
}
Company.java
public class Company
{
private String catchPhrase;
private String name;
private String bs;
//setter and getter
}
Address.java
public class Address
{
private Geo geo;
private String zipcode;
private String street;
private String suite;
private String city;
//setter and getter
}
Geo.java
public class Geo
{
private String lng;
private String lat;
//setter and getter
}
After that, json string you get from the API. parse it using Gson..
List<Post> post = new Gson().fromJson(YOUR_JSON_STRING,new TypeToken<List<Post>>() {}.getType());

How to handle java.lang.NumberFormatException: Invalid double: "" error in Android Studio?

I'm trying to run an application and it crashes because of this error:
FATAL EXCEPTION: main
Process: com.panaceasoft.citiesdirectory, PID: 4201
com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: Invalid double: ""
It had some Gradle errors, but I had solved them, and now it still crashed when I tried to run the app. It looks like that problem is in the class below, at line 252. Tried everything possible to check data and to solve this error, but nothing so far. What should I do? Thanks!
CitiesListFragment:
public class CitiesListFragment extends Fragment {
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Private Variables
//-------------------------------------------------------------------------------------------------------------------------------------
private RecyclerView mRecyclerView;
private ProgressWheel progressWheel;
private CityAdapter adapter;
private SwipeRefreshLayout swipeRefreshLayout;
private TextView display_message;
private ArrayList<PCityData> pCityDataList;
private ArrayList<PCityData> pCityDataSet;
private NestedScrollView singleLayout;
private TextView scCityName;
private TextView scCityLocation;
private TextView scCityAbout;
private TextView scCityCatCount;
private TextView scCitySubCatCount;
private TextView scCityItemCount;
private ImageView scCityPhoto;
private Button scCityExplore;
private String jsonStatusSuccessString;
private String connectionError;
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Public Variables
//-------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Constructor
//-------------------------------------------------------------------------------------------------------------------------------------
public CitiesListFragment() {
}
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Constructor
//-------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Override Functions
//-------------------------------------------------------------------------------------------------------------------------------------
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_cities_list, container, false);
initUI(view);
initData();
return view;
}
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Override Functions
//-------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Init UI Function
//-------------------------------------------------------------------------------------------------------------------------------------
private void initUI(View view){
initSingleUI(view);
initSwipeRefreshLayout(view);
initProgressWheel(view);
initRecyclerView(view);
startLoading();
}
private void initSingleUI(View view) {
singleLayout =(NestedScrollView) view.findViewById(R.id.single_city_layout);
scCityName = (TextView) view.findViewById(R.id.sc_city_name);
scCityLocation = (TextView) view.findViewById(R.id.sc_city_loc);
scCityAbout = (TextView) view.findViewById(R.id.sc_city_desc);
scCityCatCount = (TextView) view.findViewById(R.id.txt_cat_count);
scCitySubCatCount = (TextView) view.findViewById(R.id.txt_sub_cat_count);
scCityItemCount = (TextView) view.findViewById(R.id.txt_item_count);
scCityPhoto = (ImageView) view.findViewById(R.id.sc_city_photo);
scCityExplore = (Button) view.findViewById(R.id.button_explore);
int screenWidth = Utils.getScreenWidth();
int rlWidth = (screenWidth/3) - 20;
RelativeLayout r1 = (RelativeLayout) view.findViewById(R.id.rl_count1);
RelativeLayout r2 = (RelativeLayout) view.findViewById(R.id.rl_count2);
RelativeLayout r3 = (RelativeLayout) view.findViewById(R.id.rl_count3);
r1.setMinimumWidth(rlWidth);
r2.setMinimumWidth(rlWidth);
r3.setMinimumWidth(rlWidth);
scCityPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(pCityDataList !=null && pCityDataList.size() > 0) {
final Intent intent;
intent = new Intent(getActivity(), SelectedCityActivity.class);
GlobalData.citydata = pCityDataList.get(0);
intent.putExtra("selected_city_id", pCityDataList.get(0).id);
getActivity().startActivity(intent);
getActivity().overridePendingTransition(R.anim.right_to_left, R.anim.blank_anim);
}
}
});
scCityExplore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(pCityDataList !=null && pCityDataList.size() > 0) {
final Intent intent;
intent = new Intent(getActivity(), SelectedCityActivity.class);
GlobalData.citydata = pCityDataList.get(0);
intent.putExtra("selected_city_id", pCityDataList.get(0).id);
getActivity().startActivity(intent);
getActivity().overridePendingTransition(R.anim.right_to_left, R.anim.blank_anim);
}
}
});
}
private void initSwipeRefreshLayout(View view) {
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
requestData(Config.APP_API_URL + Config.GET_ALL);
}
});
}
private void initProgressWheel(View view) {
progressWheel = (ProgressWheel) view.findViewById(R.id.progress_wheel);
}
private void initRecyclerView(View view) {
mRecyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(llm);
display_message = (TextView) view.findViewById(R.id.display_message);
display_message.setVisibility(view.GONE);
pCityDataSet = new ArrayList<>();
adapter = new CityAdapter(getActivity(), pCityDataSet);
mRecyclerView.setAdapter(adapter);
mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), mRecyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
onItemClicked(position);
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Init UI Function
//-------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Init Data Function
//-------------------------------------------------------------------------------------------------------------------------------------
private void initData(){
requestData(Config.APP_API_URL + Config.GET_ALL);
jsonStatusSuccessString = getResources().getString(R.string.json_status_success);
connectionError = getResources().getString(R.string.connection_error);
}
private void requestData(String uri) {
JsonObjectRequest request = new JsonObjectRequest(uri,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String status = response.getString("status");
if (status.equals(jsonStatusSuccessString)) {
progressWheel.setVisibility(View.GONE);
Gson gson = new Gson();
Type listType = new TypeToken<List<PCityData>>() {
}.getType();
//String data="";
pCityDataList = gson.fromJson(response.getString("Data"), listType);
Utils.psLog("City Count : " + pCityDataList.size());
if(pCityDataList.size() > 1) {
singleLayout.setVisibility(View.GONE);
mRecyclerView.setVisibility(View.VISIBLE);
updateDisplay();
}else{
mRecyclerView.setVisibility(View.GONE);
singleLayout.setVisibility(View.VISIBLE);
stopLoading();
updateSingleDisplay();
}
updateGlobalCityList();
} else {
stopLoading();
Utils.psLog("Error in loading CityList.");
}
} catch (JSONException e) {
Utils.psErrorLogE("Error in loading CityList.", e);
stopLoading();
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError ex) {
progressWheel.setVisibility(View.GONE);
stopLoading();
/* NetworkResponse response = ex.networkResponse;
if (response != null && response.data != null) {
} else {*/
try {
display_message.setVisibility(View.VISIBLE);
display_message.setText(connectionError);
}catch (Exception e){
Utils.psErrorLogE("Error in Connection Url.", e);
}
//}
}
});
request.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
queue.add(request);
}
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Init Data Function
//-------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Bind Functions
//-------------------------------------------------------------------------------------------------------------------------------------
private void updateSingleDisplay() {
try {
if (pCityDataList.size() > 0) {
display_message.setVisibility(View.GONE);
singleLayout.startAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.fade_in));
scCityName.setText(pCityDataList.get(0).name);
scCityLocation.setText(pCityDataList.get(0).address);
scCityAbout.setText(pCityDataList.get(0).description);
scCityCatCount.setText(pCityDataList.get(0).category_count + " Categories");
scCitySubCatCount.setText(pCityDataList.get(0).sub_category_count + " Sub Categories");
scCityItemCount.setText(pCityDataList.get(0).item_count + " Items");
Picasso.with(getActivity()).load(Config.APP_IMAGES_URL + pCityDataList.get(0).cover_image_file).into(scCityPhoto);
}
}catch(Exception e){
Utils.psErrorLogE("Error in single display data binding.", e);
}
}
private void updateGlobalCityList() {
GlobalData.cityDatas.clear();
for (PCityData cd : pCityDataList) {
GlobalData.cityDatas.add(cd);
}
}
private void updateDisplay() {
if (swipeRefreshLayout.isRefreshing()) {
pCityDataSet.clear();
adapter.notifyDataSetChanged();
for (PCityData cd : pCityDataList) {
pCityDataSet.add(cd);
}
} else {
for (PCityData cd : pCityDataList) {
pCityDataSet.add(cd);
}
}
stopLoading();
adapter.notifyItemInserted(pCityDataSet.size());
}
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Bind Functions
//-------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Private Functions
//-------------------------------------------------------------------------------------------------------------------------------------
private void onItemClicked(int position) {
Utils.psLog("Position : " + position);
Intent intent;
intent = new Intent(getActivity(),SelectedCityActivity.class);
GlobalData.citydata = pCityDataList.get(position);
intent.putExtra("selected_city_id", pCityDataList.get(position).id);
getActivity().startActivity(intent);
getActivity().overridePendingTransition(R.anim.right_to_left, R.anim.blank_anim);
}
private void startLoading(){
try{
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
}
});
}catch (Exception e){}
}
private void stopLoading(){
try {
if (swipeRefreshLayout.isRefreshing()) {
swipeRefreshLayout.setRefreshing(false);
}
}catch (Exception e){}
}
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Private Functions
//-------------------------------------------------------------------------------------------------------------------------------------
Line 252:
pCityDataList = gson.fromJson(response.getString("data"), listType);
PCityData.class:
package com.panaceasoft.citiesdirectory.models;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
/**
* Created by Panacea-Soft on 6/8/15.
* Contact Email : teamps.is.cool#gmail.com
*/
public class PCityData implements Parcelable {
public int id;
public String name;
public String description;
public String address;
public String lat;
public String lng;
public String added;
public int status;
public int item_count;
public int category_count;
public int sub_category_count;
public int follow_count;
public String cover_image_file;
public int cover_image_width;
public int cover_image_height;
public String cover_image_description;
public ArrayList<PCategoryData> categories;
protected PCityData(Parcel in) {
id = in.readInt();
name = in.readString();
description = in.readString();
address = in.readString();
lat = in.readString();
lng = in.readString();
added = in.readString();
status = in.readInt();
item_count = in.readInt();
category_count = in.readInt();
sub_category_count = in.readInt();
follow_count = in.readInt();
cover_image_file = in.readString();
cover_image_width = in.readInt();
cover_image_height = in.readInt();
cover_image_description = in.readString();
if (in.readByte() == 0x01) {
categories = new ArrayList<PCategoryData>();
in.readList(categories, PCategoryData.class.getClassLoader());
} else {
categories = null;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(name);
dest.writeString(description);
dest.writeString(address);
dest.writeString(lat);
dest.writeString(lng);
dest.writeString(added);
dest.writeInt(status);
dest.writeInt(item_count);
dest.writeInt(category_count);
dest.writeInt(sub_category_count);
dest.writeInt(follow_count);
dest.writeString(cover_image_file);
dest.writeInt(cover_image_width);
dest.writeInt(cover_image_height);
dest.writeString(cover_image_description);
if (categories == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(categories);
}
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<PCityData> CREATOR = new Parcelable.Creator<PCityData>() {
#Override
public PCityData createFromParcel(Parcel in) {
return new PCityData(in);
}
#Override
public PCityData[] newArray(int size) {
return new PCityData[size];
}
};
}
L.E:
data:
[{"id":"1","name":"MaramureČ™","description":"MaramureČ™ is a mountainous .","address":"MaramureČ™, Romania","lat":"0","lng":"0","admin_id":"3","is_approved":"1","paypal_trans_id":"0","added":"2016-07-1420:45:50","status":"1","item_count":85,"category_count":49,"sub_category_count":0,"follow_count":0,"cover_image_file":"singapore.png","cover_image_width":"600","cover_image_height":"400","cover_image_description":"Singapore","categories":
L.E:
PCategoryData.java:
package com.panaceasoft.citiesdirectory.models;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
/**
* Created by Panacea-Soft on 8/8/15.
* Contact Email : teamps.is.cool#gmail.com
*/
public class PCategoryData implements Parcelable {
public int id;
public int shop_id;
public String name;
public int is_published;
public int ordering;
public String added;
public String updated;
public String cover_image_file;
public int cover_image_width;
public int cover_image_height;
public ArrayList<PSubCategoryData> sub_categories;
public Double value;
protected PCategoryData(Parcel in) {
id = in.readInt();
shop_id = in.readInt();
name = in.readString();
is_published = in.readInt();
ordering = in.readInt();
added = in.readString();
updated = in.readString();
cover_image_file = in.readString();
cover_image_width = in.readInt();
cover_image_height = in.readInt();
if (in.readByte() == 0x01) {
sub_categories = new ArrayList<PSubCategoryData>();
in.readList(sub_categories, PSubCategoryData.class.getClassLoader());
} else {
sub_categories = null;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeInt(shop_id);
dest.writeString(name);
dest.writeInt(is_published);
dest.writeInt(ordering);
dest.writeString(added);
dest.writeString(updated);
dest.writeString(cover_image_file);
dest.writeInt(cover_image_width);
dest.writeInt(cover_image_height);
if (sub_categories == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(sub_categories);
}
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<PCategoryData> CREATOR = new Parcelable.Creator<PCategoryData>() {
#Override
public PCategoryData createFromParcel(Parcel in) {
return new PCategoryData(in);
}
#Override
public PCategoryData[] newArray(int size) {
return new PCategoryData[size];
}
};
}
I guess that PCategoryData has double field, and guess that json value of that double field is "";
UPDATE
Your code will be like this:
public class CitiesListFragment extends Fragment {
...
private void requestData(String uri) {
...
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(PCategoryData.class, new PCategoryDataTypeAdapter());
final Gson gson = gsonBuilder.create();
Type listType = new TypeToken<List<PCityData>>() {
}.getType();
//String data="";
pCityDataList = gson.fromJson(response.getString("Data"), listType);
...
}
...
class PCategoryDataTypeAdapter extends TypeAdapter<PCategoryData> {
#Override
public PCategoryData read(JsonReader in) throws IOException {
final PCategoryData data = new PCategoryData();
in.beginObject();
while (in.hasNext()) {
switch (in.nextName()) {
case "value": //Please change "value" to your field name.
try {
data.value = Double.valueOf(in.nextString());
} catch (NumberFormatException e) {
data.value = 0;
}
break;
}
}
in.endObject();
return data;
}
#Override
public void write(JsonWriter out, PCategoryData data) throws IOException {
out.beginObject();
out.name("value").value(data.value); //Please change "value" to your field name.
out.endObject();
}
}
...
}

Categories