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());
Related
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;
}
}
}
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);
}
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();
}
}
...
}
I'm creating an Android map app by getting venue from Foursquare and using Google Map.
I have set my MainActivity to get the venue results, a MapFragmentClass and a VenueModel.
I keep all the JSON result from Foursquare into a List venueModelList in the MainActivity.
What I want to do is to add markers in the MapFragmentClass based on the coordinates received from Foursquare.
However, I am stuck trying to pass the venueModelList to the MapFragmentClass.
Any help is appreciated. Thanks.
MainActivity.java
public class MainActivity extends AppCompatActivity implements LocationListener{
private final String VENUE_URL = "https://api.foursquare.com/v2/venues/search?ll=";
private final int LIMIT = 40;
private final double RADIUS = 50000;
private String MOSQUE_URL;
private String RES_URL;
public static final String CLIENT_ID = "";
public static final String CLIENT_SECRET = "";
private static final long MIN_TIME_BW_UPDATES = 20000;
private static final float MIN_DISTANCE_CHANGE_FOR_UPDATES = 1;
private LocationManager locationManager;
private Location lastLocation;
private Location location;
private boolean receivedLocation = false;
private double lt;
private double lg;
private boolean canGetLocation;
private boolean isGPSEnabled;
private boolean isNetworkEnabled;
private boolean updateSettings = false;
private String TAG = "TAG";
private ListView lvVenues;
private Bundle bundle;
private ArrayList<VenueModel> venueModelList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvVenues = (ListView) findViewById(R.id.lvVenues);
String t = timeMilisToString(System.currentTimeMillis());
Bundle extras = getIntent().getExtras();
if (extras != null)
{
lt = extras.getDouble("LATITUDE");
lg = extras.getDouble("LONGITUDE");
receivedLocation = true;
}
else
{
receivedLocation = false;
}
location = getLocation();
if (location != null)
{
if(receivedLocation)
{
location.setLatitude(lt);
location.setLongitude(lg);
}
else
{
lt = location.getLatitude();
lg = location.getLongitude();
Log.d("LAT", "Latitude: " + lt);
Log.d("LONG", "Longitude: " + lg);
}
}
double lt = 3.142182;
double lg = 101.710602;
MOSQUE_URL = VENUE_URL + lt + "," + lg
+ "&client_id=" + CLIENT_ID
+ "&client_secret=" + CLIENT_SECRET
+ "&v=" + t
+ "&categoryId=4bf58dd8d48988d138941735"
+ "&radius=" + RADIUS
+ "&limit=" + LIMIT;
RES_URL = VENUE_URL + lt + "," + lg
+ "&client_id=" + CLIENT_ID
+ "&client_secret=" + CLIENT_SECRET
+ "&v=" + t
+ "&categoryId=52e81612bcbc57f1066b79ff"
+ "&radius=" + RADIUS
+ "&limit=" + LIMIT;
}
public class JSONTask extends AsyncTask<String, String, List<VenueModel>>
{
#Override
public List<VenueModel> doInBackground(String... params)
{
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONObject secondObject = parentObject.getJSONObject("response");
JSONArray parentArray = secondObject.getJSONArray("venues");
venueModelList = new ArrayList<>();
for (int i = 0; i < parentArray.length(); i++)
{
JSONObject finalObject = parentArray.getJSONObject(i);
JSONObject thirdObject = finalObject.getJSONObject("location");
try {
VenueModel venueModel = new VenueModel();
venueModel.setId(finalObject.getString("id"));
venueModel.setName(finalObject.getString("name"));
venueModel.setAddress(thirdObject.optString("address"));
venueModel.setPostalCode(thirdObject.optString("postalCode"));
venueModel.setCity(thirdObject.optString("city"));
venueModel.setState(thirdObject.optString("state"));
venueModel.setDistance(thirdObject.getInt("distance"));
venueModel.setLat(thirdObject.getDouble("lat"));
venueModel.setLng(thirdObject.getDouble("lng"));
LatLng coordinate = new LatLng(thirdObject.getDouble("lat"), thirdObject.getDouble("lng"));
venueModel.setCoordinate(coordinate);
venueModelList.add(venueModel);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Collections.sort(venueModelList);
return venueModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<VenueModel> result)
{
super.onPostExecute(result);
VenueAdapter adapter = new VenueAdapter(getApplicationContext(), R.layout.row, result);
lvVenues.setAdapter(adapter);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_mosque)
{
new JSONTask().execute(MOSQUE_URL);
FragmentManager fmanager = getSupportFragmentManager();
FragmentTransaction FT = fmanager.beginTransaction();
MapFragmentClass mfc = new MapFragmentClass();
FT.add(R.id.mapLayout, mfc);
FT.commit();
return true;
}
if (id == R.id.action_restaurant)
{
new JSONTask().execute(RES_URL);
FragmentManager fmanager = getSupportFragmentManager();
FragmentTransaction FT = fmanager.beginTransaction();
MapFragmentClass mfc = new MapFragmentClass();
FT.add(R.id.mapLayout, mfc);
FT.commit();
return true;
}
return super.onOptionsItemSelected(item);
}
private String timeMilisToString(long milis)
{
SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milis);
return sd.format(calendar.getTime());
}
public Location getLocation()
{
try
{
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
{
Log.v(TAG, "No network provider enabled");
}
else
{
this.canGetLocation = true;
if (isNetworkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d(TAG, "Network Enabled");
if(locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
if (isGPSEnabled)
{
if (location == null)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d(TAG, "GPS Enabled");
if(locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return location;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onLocationChanged(Location location)
{
lastLocation = location;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider)
{
Log.v(TAG, "onProviderEnabled");
}
#Override
public void onProviderDisabled(String provider)
{
Log.v(TAG, "onProviderDisabled");
}
public LatLng setCoordinate()
{
LatLng coordinate = new LatLng(getLocation().getLatitude(), getLocation().getLongitude());
LatLng coordinate = new LatLng(lt, lg);
return coordinate;
}
}
VenueModel.java
public class VenueModel implements Comparable<VenueModel>, Parcelable
{
private String id;
private String name;
private String address;
private String postalCode;
private String city;
private String state;
private Integer distance;
private double lat;
private double lng;
private LatLng coordinate;
private List<VenueModel> venueModelList;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public void setVenueModelList(List<VenueModel> venueModelList)
{
this.venueModelList = venueModelList;
}
public List<VenueModel> getVenueModelList()
{
return venueModelList;
}
public LatLng getCoordinate() {
return coordinate;
}
public void setCoordinate(LatLng coordinate)
{
this.coordinate = coordinate;
}
#Override
public int compareTo(VenueModel venueModel) {
return this.distance.compareTo(venueModel.distance);
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.id);
dest.writeString(this.name);
dest.writeString(this.address);
dest.writeString(this.postalCode);
dest.writeString(this.city);
dest.writeString(this.state);
dest.writeValue(this.distance);
dest.writeDouble(this.lat);
dest.writeDouble(this.lng);
dest.writeParcelable(this.coordinate, flags);
dest.writeList(this.venueModelList);
}
public VenueModel() {
}
protected VenueModel(Parcel in) {
this.id = in.readString();
this.name = in.readString();
this.address = in.readString();
this.postalCode = in.readString();
this.city = in.readString();
this.state = in.readString();
this.distance = (Integer) in.readValue(Integer.class.getClassLoader());
this.lat = in.readDouble();
this.lng = in.readDouble();
this.coordinate = in.readParcelable(LatLng.class.getClassLoader());
this.venueModelList = new ArrayList<VenueModel>();
in.readList(this.venueModelList, VenueModel.class.getClassLoader());
}
public static final Parcelable.Creator<VenueModel> CREATOR = new Parcelable.Creator<VenueModel>() {
#Override
public VenueModel createFromParcel(Parcel source) {
return new VenueModel(source);
}
#Override
public VenueModel[] newArray(int size) {
return new VenueModel[size];
}
};
}
MapFragmentClass.java
public class MapFragmentClass extends Fragment implements OnMapReadyCallback
{
private MainActivity mA;
private GoogleMap gmap;
private static final LatLng coordinate = new LatLng(3.152182, 101.710602);
private LatLng coordinate2;
private ArrayList<VenueModel> venueModelList;
#Override
public void onAttach(Context context)
{
super.onAttach(context);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.activity_maps, container, false);
SupportMapFragment supportMapFragment = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(this);
return v;
}
#Override
public void onMapReady(GoogleMap googleMap)
{
gmap = googleMap;
gmap.addMarker(new MarkerOptions().position(coordinate).title("Your location").draggable(true));
gmap.moveCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 14));
}
}
Convert that Object to JSON string using GSON and then reconvert that string again to Object of list again.
MapFragment.getInstance(new Gson().toJson(venuList));
public static final getInstance(String venusStringListObj) {}
Bundle argument = new Bundle();
argument.putString("VENUES", venusStringListObj);
MapFragment fragment = new MapFragment();
fragment.setArgument(argument);
return fragment;
}
onCreate(...) {
private List<VenueModel> venueList;
Type listType = new TypeToken<ArrayList<VenueModel>>() {}.getType();
String venueStringRecvFromFragArg = getArguments().getString("VENUES");
venueList = new Gson().fromJson(venueStringRecvFromFragArg, listType);
}
MapFragmentClass mfc = new MapFragmentClass();
Bundle b = new Bundle();
b.putParcelableArrayList("Parcel", list);
mfc.setArguments(b);
FT.add(R.id.mapLayout, mfc);
FT.commit();
To access arrayList in MapFragment use this
ArrayList<VenueModel> myList = getArguments().getParcelableArrayList("Parcel");
I tried to add textwatcher with filter class but it do not work plz help. I get the json array through the server using the url. the search(filter) doesnt work well.
public class CallDetails extends Activity {
SessionManager session;
ArrayList<Drivers> driverList = new ArrayList<Drivers>();
private List<Drivers> driverlist = null;
ListView listview;
ImageButton btback;
DriverAdapter dadapter;
String uid;
String name;
String email;
String odtyp;
static String oid;
Drivers driver;
private EditText editTextFilter;
private static String OUTBOX_URL ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calldetails);
Intent i = getIntent();
oid =i.getStringExtra("orderId");
odtyp =i.getStringExtra("ordertype");
OUTBOX_URL ="http://www.gdrive.com/api/calldetails.php?id="+oid;
//managing session...
session = new SessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
name = user.get(SessionManager.KEY_NAME);
email = user.get(SessionManager.KEY_EMAIL);
uid = user.get(SessionManager.KEY_UID);
btback =(ImageButton)findViewById(R.id.btnBack);
btback.setVisibility(View.INVISIBLE);
// Locate the EditText in listview_main.xml
editTextFilter = (EditText)findViewById(R.id.editTextFilter);
editTextFilter.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
String text = editTextFilter.getText().toString().toLowerCase(Locale.getDefault());
dadapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3){ /* to do*/ }
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) { /*to do*/ }
});
//populating view with data...
//driverList = new ArrayList<Drivers>();
new JSONAsyncTask().execute(OUTBOX_URL);
listview = (ListView)findViewById(R.id.drlist);
dadapter = new DriverAdapter(CallDetails.this, R.layout.list_item, driverList);
listview.setItemsCanFocus(false);
listview.setAdapter(dadapter);
//populating list ends
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), driverList.get(position).getName(), Toast.LENGTH_LONG).show();
}
});
}
public void back(View v){
Intent back = new Intent(getApplicationContext(), SafetyDrive.class);
startActivity(back);
finish();
}
private class DriverAdapter extends ArrayAdapter<Drivers> {
Context context;
int Resource;
LayoutInflater inflater;
ArrayList<Drivers> driverList = new ArrayList<Drivers>();
public DriverAdapter(Context context, int layoutResourceId,ArrayList<Drivers> drs) {
super(context, layoutResourceId, drs);
//inflater = ((Activity) context).getLayoutInflater();
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = layoutResourceId;
driverList = drs;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//Log.d("in ", "view start");
View item = convertView;
DriverWrapper DriverWrapper = null;
if (item == null) {
DriverWrapper = new DriverWrapper();
item = inflater.inflate(Resource, null);
DriverWrapper.ename = (TextView) item.findViewById(R.id.textName);
DriverWrapper.ephone = (TextView) item.findViewById(R.id.textPhone);
DriverWrapper.mkcall = (ImageButton) item.findViewById(R.id.btnphone);
item.setTag(DriverWrapper);
} else {
DriverWrapper = (DriverWrapper) item.getTag();
}
Drivers driver = driverList.get(position);
DriverWrapper.ename.setText("Name: " + driver.getName());
DriverWrapper.ephone.setText("Phone: " + driver.getPhone());
final String dp = driver.getPhone().trim();
DriverWrapper.mkcall.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//making call..
//Log.e("no is", dp);
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" +dp));
//callIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(callIntent);
//finish();
}
});
return item;
}
class DriverWrapper {
TextView ename;
TextView ephone;
ImageButton mkcall;
//ImageButton msg;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
driverList.clear();
if (charText.length() == 0) {
driverList.addAll(driverList);
} else {
for (Drivers driver : driverList) {
if (driver.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
driverList.add(driver);
}
}
}
notifyDataSetChanged();
}
}
class JSONAsyncTask extends AsyncTask {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(CallDetails.this);
dialog.setMessage("Loading, please wait");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//Log.d("in at-", "asynctask");
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("drivers");
if(jarray.length()!=0){
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Drivers driver = new Drivers();
driver.setPhone(object.getString("phone"));
driver.setName(object.getString("emp_name"));
driverList.add(driver);
}
}else{
driver = new Drivers();
driver.setPhone(" ");
driver.setName(" No Driver Place yet");
driverList.add(driver);
}
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
btback.setVisibility(View.VISIBLE);
dadapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
public class Drivers {
private String name;
private String phone;
public Drivers() {
}
public Drivers(String name, String phone) {
super();
this.name = name;
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
actually it wont filter because youve cleared the driverList and then in the else statement you loop to driverList which is already empty. the only thing you can do is create a backup list for the driversList and then use the backup list to get all data for filtering to the driverList.
Example Here:
// here is the backuplist
ArrayList<Drivers> backupList = new ArrayList<Drivers>();
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
// actually its easy to just clear the backup list
// but due to reasons where users press backspace you have to load backup list only once
if(backupList.isEmpty()) {
backupList.addAll(driverList);
}
driverList.clear();
if (charText.length() == 0) {
driverList.addAll(backupList);
} else {
for (Drivers driver : backupList) {
if (driver.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
driverList.add(driver);
}
}
}
notifyDataSetChanged();
}
Hope it helps :)