RecyleView showing all items duplicates - android

I am trying to display posts from a server in listView. So I used recycle-view to achieve that. Everything is working fine except that ll items are displaying twice.
I counted the total fetched items from server, and the count is 5, but adapter.getItemCount is showing 10.
After searching hours on the internet, I tried following :
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
and
homeFragmentAdapter.setHasStableIds(true);
Below is my fragment...
package com.example.projectName;
import static android.content.Context.MODE_PRIVATE;
import static android.webkit.ConsoleMessage.MessageLevel.LOG;
import static com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade;
public class HomeFollowersFragment extends Fragment implements InfiniteScrollListener.OnLoadMoreListener, RecyclerViewItemListener {
private static final String TAG = "HomeFollowersFragment";
private static final String URL = "https://api.androidhive.info/json/movies_2017.json";
private RecyclerView recyclerView;
private ProgressBar postLoader;
FFmpeg ffmpeg;
// private List<Movie> movieList;
// private HomeAdapter mAdapter;
private List<PostList> postListGlobal = new ArrayList<>();
List<VerticalDataModal> verticalDataModals;
List<HorizontalDataModal> horizontalDataModals;
private SwipeRefreshLayout swipeMore;
private InfiniteScrollListener infiniteScrollListener;
private HomeFragmentAdapter homeFragmentAdapter;
SharedPreferences sharedPreferences;
private Boolean isLoggedIn = false;
private String email = "";
private String token = "";
private String userId = "";
private Dialog customLoader;
SkeletonScreen skeletonScreen;
private int pastVisiblesItems, visibleItemCount, totalItemCount;
private boolean loading = false;
private EndlessScrollListener scrollListener;
SharedPreferences sp;
SharedPreferences.Editor Ed;
public HomeFollowersFragment() {
//super();
}
/**
* #return A new instance of fragment HomeFollowersFragment.
*/
public static HomeFollowersFragment newInstance() {
return new HomeFollowersFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
// ((AppCompatActivity) getActivity()).getSupportActionBar().show();
try{
sharedPreferences = getActivity().getSharedPreferences("Login", MODE_PRIVATE);
email = sharedPreferences.getString("email", null);
token = sharedPreferences.getString("token", null);
isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);
userId = sharedPreferences.getString("id", null);
}catch (Exception e){
e.printStackTrace();
Log.d("StackError", "StackError: "+e);
}
sp = getActivity().getSharedPreferences("Posts", MODE_PRIVATE);
if(!isLoggedIn || token == null || userId == null){
Intent intent = new Intent(getActivity(), RegisterActivity.class);
intent.putExtra("loginFrom", "profile");
startActivity(intent);
}
recyclerView = view.findViewById(R.id.recycler_view);
postLoader = view.findViewById(R.id.post_loader);
swipeMore = view.findViewById(R.id.swipe_layout);
homeFragmentAdapter = new HomeFragmentAdapter(postListGlobal, this, "home");
if(sp.contains("postListGlobal"))
skeletonScreen = Skeleton.bind(recyclerView)
.adapter(homeFragmentAdapter)
.shimmer(true)
.angle(20)
.frozen(false)
.duration(1200)
.count(10)
.load(R.layout.item_skelton_home_page)
.show(); //default count is 10
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
StaggeredGridLayoutManager sLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(sLayoutManager);
homeFragmentAdapter.setHasStableIds(true);
recyclerView.setAdapter(homeFragmentAdapter);
recyclerView.setNestedScrollingEnabled(false);
customLoader = new Dialog(getActivity(), R.style.crystal_range_seek_bar);
customLoader.setCancelable(false);
View loaderView = getLayoutInflater().inflate(R.layout.custom_loading_layout, null);
customLoader.getWindow().getAttributes().windowAnimations = R.style.crystal_range_seek_bar;
customLoader.getWindow().setBackgroundDrawableResource(R.color.translucent_black);
ImageView imageLoader = loaderView.findViewById(R.id.logo_loader);
Glide.with(this).load(R.drawable.logo_loader).into(imageLoader);
customLoader.setContentView(loaderView);
if(homeFragmentAdapter.getItemCount() == 0 && !loading){
// server fetchdata
Log.d(TAG, "no item available..");
postLoader.setVisibility(View.VISIBLE);
loading = true;
fetchStoreItems();
}else{
postLoader.setVisibility(View.GONE);
}
swipeMore.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.d(TAG, "on refresh...");
fetchStoreItems();
}
});
return view;
}
#Override
public void onItemClicked(int position) {
Log.d(TAG, "click position: "+position);
Toast.makeText(getActivity(),postListGlobal.get(position).getTitle(),Toast.LENGTH_SHORT).show();
// Toast.makeText(getActivity(),""+position, Toast.LENGTH_SHORT).show();
}
public int getLastVisibleItem(int[] lastVisibleItemPositions) {
int maxSize = 0;
for (int i = 0; i < lastVisibleItemPositions.length; i++) {
if (i == 0) {
maxSize = lastVisibleItemPositions[i];
}
else if (lastVisibleItemPositions[i] > maxSize) {
maxSize = lastVisibleItemPositions[i];
}
}
return maxSize;
}
#Override
public void onLoadMore() {
homeFragmentAdapter.addNullData();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
homeFragmentAdapter.removeNull();
Toast.makeText(getContext(), "load more here...", Toast.LENGTH_LONG).show();
// fetchStoreItems();
swipeMore.setRefreshing(false);
}
}, 2000);
}
private void fetchStoreItems() {
RequestQueue queue = Volley.newRequestQueue(getActivity());
Log.d(TAG, "Post Data Followers: "+Constant.FETCH_POSTS_API);
CacheRequest cacheRequest = new CacheRequest(0, Constant.FETCH_POSTS_API, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
try {
final String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
if (response == null) {
Toast.makeText(getActivity(), "Couldn't fetch the store items! Pleas try again.", Toast.LENGTH_LONG).show();
loading = false;
return;
}
JSONObject postObj = new JSONObject(jsonString);
System.out.println("post full data... : " + postObj);
if (postObj.getBoolean("Status")) {
try {
postLoader.setVisibility(View.GONE);
JSONArray arrayResponse = postObj.optJSONArray("Data");
int dataArrLength = arrayResponse.length();
if(dataArrLength == 0){
Toast.makeText(getActivity(), "No posts available at this time, you can create yout own post by clicking on mic button", Toast.LENGTH_SHORT).show();
}
postListGlobal.clear();
Log.d(TAG, "Total Posts count: "+dataArrLength);
for(int i=0; i<dataArrLength; i++) {
try {
JSONObject dataListObj = arrayResponse.optJSONObject(i);
System.out.println("post full data... : " + dataListObj);
JSONObject postDetailObj = dataListObj.optJSONObject("post_detail");
JSONObject followDtatusObj = dataListObj.optJSONObject("follow_status");
JSONArray postFilesArr = dataListObj.optJSONArray("post_files");
JSONObject userDatasObj = postDetailObj.optJSONObject("user");
String userId = userDatasObj.optString("id");
String userName = userDatasObj.optString("email");
String userImage = userDatasObj.optString("email");
boolean followStatus = followDtatusObj.optBoolean("follow");
String postId = postDetailObj.optString("id");
String postTitle = postDetailObj.optString("post_title");
String postDescription = postDetailObj.optString("post_description");
String postCoverUrl = postDetailObj.optString("post_coverurl", "1");
String postViewType = postDetailObj.optString("view_type", "1");
String postAllowComment = postDetailObj.optString("allow_comments", "1");
String postAllowDownload = postDetailObj.optString("allow_download", "1");
String postTotalPost = postDetailObj.optString("total_post", "1");
String postPostSection = postDetailObj.optString("post_section", "image");
String postActiveStatus = postDetailObj.optString("is_active", "1");
String postTotalViews = postDetailObj.optString("total_watched","0");
String postTotalShare = postDetailObj.optString("total_share","0");
String postTotalDownload = postDetailObj.optString("total_download","0");
String postTotalReaction = postDetailObj.optString("total_reaction","0");
String postTotalLike = postDetailObj.optString("total_like","0");
String postTotalSmile = postDetailObj.optString("smile_reaction","0");
String postTotalLaugh = postDetailObj.optString("laugh_reaction","0");
String postTotalSad = postDetailObj.optString("sad_reaction","0");
String postTotalLove = postDetailObj.optString("love_reaction","0");
String postTotalShock = postDetailObj.optString("shock_reaction","0");
int totalPostFiles = Integer.parseInt(postTotalPost);
int postArrLength = postFilesArr.length();
String postImageUrl = null;
String postMusicUrl = null;
String commonUrl = "http://serverName.com/";
if(postArrLength >= 1){
JSONObject dataFilesListObj = postFilesArr.optJSONObject(0);
// System.out.println("post files full data... : " + dataFilesListObj);
String postFileId = dataFilesListObj.optString("id");
postImageUrl = dataFilesListObj.optString("image_file_path");
postMusicUrl = dataFilesListObj.optString("music_file_path");
System.out.println("post files full data... : " + dataFilesListObj);
}
System.out.println("post files full data... : " + commonUrl+postMusicUrl);
System.out.println("post files full data... : " + commonUrl+postImageUrl);
PostList postList = new PostList();
postList.setId(postId);
postList.setTitle(postTitle);
postList.setTotalPost(""+dataArrLength);
postList.setTotalView(postTotalViews);
postList.setTotalReaction(postTotalReaction);
postList.setMusicPath(commonUrl+postMusicUrl);
postList.setImagePath(commonUrl+postImageUrl);
if(postImageUrl == null){
postList.setImagePath("https://amazonBucket.s3.location.amazonaws.com/images/pic1.jpg");
}
postList.setUserId(userId);
postList.setUserName(userName);
postList.setPostDataObject(arrayResponse);
postListGlobal.add(postList);
Log.d(TAG, "Total Posts: "+dataListObj);
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "Post Data Error1: "+e);
Toast.makeText(getActivity(), "File now found", Toast.LENGTH_LONG).show();
loading = false;
}
}
} catch (Exception e){
e.printStackTrace();
Log.d(TAG, "Post Data Error2: "+e);
Toast.makeText(getActivity(), R.string.server_error, Toast.LENGTH_LONG).show();
loading = false;
}
}else{
try {
Toast.makeText(getActivity(), new JSONObject(jsonString).getString("Message"), Toast.LENGTH_LONG).show();
} catch (JSONException ex) {
ex.printStackTrace();
Log.d(TAG, "Post Data Error3: "+ex);
Toast.makeText(getActivity(), R.string.server_error, Toast.LENGTH_SHORT).show();
}
loading = false;
}
// refreshing recycler view
homeFragmentAdapter.removeNull();
homeFragmentAdapter.addData(postListGlobal);
homeFragmentAdapter.notifyDataSetChanged();
// save in local memory
// saveArrayList(postListGlobal, "postListGlobal");
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "Post Data Error4: "+e);
}
loading = true;
homeFragmentAdapter.notifyDataSetChanged();
swipeMore.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "onErrorResponse: "+ error, Toast.LENGTH_SHORT).show();
swipeMore.setRefreshing(false);
loading = true;
homeFragmentAdapter.notifyDataSetChanged();
postLoader.setVisibility(View.VISIBLE);
loading = false;
Log.d(TAG, "Post Data Error5: "+error);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
String finalToken = "Bearer "+token;
params.put("Authorization", finalToken);
params.put("Content-Type", "application/json");
return params;
}
};
// Add the request to the RequestQueue.
queue.add(cacheRequest);
}
private class CacheRequest extends Request<NetworkResponse> {
private final Response.Listener<NetworkResponse> mListener;
private final Response.ErrorListener mErrorListener;
public CacheRequest(int method, String url, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.mListener = listener;
this.mErrorListener = errorListener;
}
#Override
protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response);
if (cacheEntry == null) {
cacheEntry = new Cache.Entry();
}
final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background
final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely
long now = System.currentTimeMillis();
final long softExpire = now + cacheHitButRefreshed;
final long ttl = now + cacheExpired;
cacheEntry.data = response.data;
cacheEntry.softTtl = softExpire;
cacheEntry.ttl = ttl;
String headerValue;
headerValue = response.headers.get("Date");
if (headerValue != null) {
cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
}
headerValue = response.headers.get("Last-Modified");
if (headerValue != null) {
cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);
}
cacheEntry.responseHeaders = response.headers;
return Response.success(response, cacheEntry);
}
#Override
protected void deliverResponse(NetworkResponse response) {
mListener.onResponse(response);
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
Log.d(TAG, "Post Data volleyError: "+volleyError);
return super.parseNetworkError(volleyError);
}
#Override
public void deliverError(VolleyError error) {
mErrorListener.onErrorResponse(error);
}
}
}
and Adapter Class
package com.example.ProjectName;
public class HomeFragmentAdapter extends RecyclerView.Adapter <HomeFragmentAdapter.HomeViewHolder>{
// private ArrayList<Integer> dataList;
private List<PostList> postListGlobal;
int VIEW_TYPE_LOADING;
int VIEW_TYPE_ITEM;
Context context;
private RecyclerViewItemListener callback;
FFmpeg ffmpeg;
String callingPage;
public HomeFragmentAdapter(List<PostList> postListGlobal, RecyclerViewItemListener callback, String callingPage) {
this.postListGlobal = postListGlobal;
this.callback = callback;
this.callingPage = callingPage;
// setHasStableIds(true);
}
#NonNull
#Override
public HomeFragmentAdapter.HomeViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View root = null;
context = parent.getContext();
root = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_home_tile_list, parent, false);
return new DataViewHolder(root);
}
#Override
public void onBindViewHolder(#NonNull HomeFragmentAdapter.HomeViewHolder holder, int position) {
if (holder instanceof DataViewHolder) {
final PostList postList = postListGlobal.get(position);
holder.postTitle.setText(postList.getTitle());
holder.postWatch.setText(postList.getTotalView());
holder.postReaction.setText(postList.getTotalReaction());
String imageUrl = postList.getImagePath();
// String imageUrl = Constant.SERVER_URL+"/"+postList.getImagePath();
String musicUrl = postList.getMusicPath();
// String musicUrl = Constant.SERVER_URL+"/"+postList.getMusicPath();
Log.d(TAG, "Post url: "+imageUrl+" -- "+musicUrl);
// int totalMusicTime = getDurationVal(musicUrl, "second");
holder.postTime.setText(postList.getTotalPost());
holder.thumbnail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
callback.onItemClicked(position);
Log.d("homeView", "screenName : "+callingPage);
if(callingPage.equals("home")){
Log.d("homeView", "screenName : "+position);
Intent intent = new Intent(context, MainViewActivity.class);
intent.putExtra("loginFrom", "homeView");
intent.putExtra("postDataObj", postList.getPostDataObject().toString());
intent.putExtra("postPosition", ""+position);
intent.putExtra("tabId", "1");
context.startActivity(intent);
}
}
});
Drawable mDefaultBackground = context.getResources().getDrawable(R.drawable.influencers);
CircularProgressDrawable circularProgressDrawable = new CircularProgressDrawable(context);
circularProgressDrawable.setStrokeWidth(5f);
Glide.with(context)
.load(imageUrl)
.listener(new RequestListener<Drawable>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
// progressBar.setVisibility(View.GONE);
return false;
}
#Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
// progressBar.setVisibility(View.GONE);
return false;
}
})
.error(mDefaultBackground)
.into(holder.thumbnail);
}else{
//Do whatever you want. Or nothing !!
}
}
#Override
public int getItemCount() {
return postListGlobal.size();
}
class DataViewHolder extends HomeViewHolder {
public DataViewHolder(View itemView) {
super(itemView);
}
}
class ProgressViewHolder extends HomeViewHolder {
public ProgressViewHolder(View itemView) {
super(itemView);
}
}
class HomeViewHolder extends RecyclerView.ViewHolder {
public TextView postTitle, postTime, postWatch, postReaction;
public ImageView thumbnail;
public HomeViewHolder(View itemView) {
super(itemView);
postTitle = itemView.findViewById(R.id.post_title);
postTime = itemView.findViewById(R.id.total_time);
postWatch = itemView.findViewById(R.id.total_watch);
postReaction = itemView.findViewById(R.id.total_reaction);
thumbnail = itemView.findViewById(R.id.thumbnail);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public void addNullData() {
}
public void removeNull() {
notifyItemRemoved(postListGlobal.size());
}
public void addData(List<PostList> postLists) {
postListGlobal.addAll(postLists);
notifyDataSetChanged();
}
}
After trying everything, I was still not able to resolve the issue. Any help/suggestions are welcome. Let me know If I left out any needed code--if so I can update it here.

`postListGlobal.add(postList);` below this line add ` homeFragmentAdapter.notifyDataSetChanged();` and remove ` homeFragmentAdapter.removeNull(); homeFragmentAdapter.addData(postListGlobal);homeFragmentAdapter.notifyDataSetChanged();` this code.Because in this case list added twice without notifying datasetchange check with your code by removing this.

postListGlobal.clear(); just clear tha arraylist before add .

postListGlobal.clear() before adding new list to the adapter.
And then notifyDataSetChanged() to let adapter know of the changes.

Related

Recycler view swaps items when i scroll them

I am developing the chatbot app. I am using the RecycleView to render the chat of user and bot. I have to show the user listview or text response depend upon his query. All is working until my RecyclerView get's scroll. Whenever my RecyclerView gets scroll it changes the item position. I search a lot and applied every solution but not able to solve my issue.
here is my activity.java
public class HomeActivity extends AppCompatActivity implements AIListener,
View.OnClickListener {
private RecyclerView recyclerView;
private ChatAdapter mAdapter;
LinearLayoutManager layoutManager;
private ArrayList<Message> messageArrayList;
private EditText inputMessage;
private RelativeLayout btnSend;
Boolean flagFab = true;
PaytmPGService service = null;
Map<String, String> paytmparam = new HashMap<>();
PrefManager prefManager;
private AIService aiService;
AIDataService aiDataService;
AIRequest aiRequest;
Gson gson;
String food_dish = " ";
double price = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
inputMessage = findViewById(R.id.editText_ibm);
btnSend = findViewById(R.id.addBtnibm);
recyclerView = findViewById(R.id.recycler_view_ibm);
messageArrayList = new ArrayList<>();
mAdapter = new ChatAdapter(this,messageArrayList);
prefManager = new PrefManager(this);
GsonBuilder gsonBuilder = new GsonBuilder();
gson = gsonBuilder.create();
layoutManager = new LinearLayoutManager(this);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setItemAnimator(new DefaultItemAnimator());
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
int msgCount = mAdapter.getItemCount();
int lastVisiblePosition = layoutManager.findLastCompletelyVisibleItemPosition();
if (lastVisiblePosition == -1 ||
(positionStart >= (msgCount - 1) &&
lastVisiblePosition == (positionStart - 1))) {
recyclerView.scrollToPosition(positionStart);
}
}
});
recyclerView.setAdapter(mAdapter);
this.inputMessage.setText("");
final AIConfiguration configuration = new AIConfiguration("cabc4b7b9c20409aa7ffb1b3d5fe1243",
AIConfiguration.SupportedLanguages.English,
AIConfiguration.RecognitionEngine.System);
aiService = AIService.getService(this, configuration);
aiService.setListener(this);
aiDataService = new AIDataService(configuration);
aiRequest = new AIRequest();
btnSend.setOnClickListener(this);
inputMessage.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
ImageView fab_img = findViewById(R.id.fab_img_ibm);
Bitmap img = BitmapFactory.decodeResource(getResources(), R.drawable.ic_send_white_24dp);
Bitmap img1 = BitmapFactory.decodeResource(getResources(), R.drawable.ic_mic_white_24dp);
if (s.toString().trim().length() != 0 && flagFab) {
ImageViewAnimatedChange(HomeActivity.this, fab_img, img);
flagFab = false;
} else if (s.toString().trim().length() == 0) {
ImageViewAnimatedChange(HomeActivity.this, fab_img, img1);
flagFab = true;
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void ImageViewAnimatedChange(Context c, final ImageView v, final Bitmap new_image) {
final Animation anim_out = AnimationUtils.loadAnimation(c, R.anim.zoom_out);
final Animation anim_in = AnimationUtils.loadAnimation(c, R.anim.zoom_in);
anim_out.setAnimationListener(new Animation.AnimationListener()
{
#Override public void onAnimationStart(Animation animation) {}
#Override public void onAnimationRepeat(Animation animation) {}
#Override public void onAnimationEnd(Animation animation)
{
v.setImageBitmap(new_image);
anim_in.setAnimationListener(new Animation.AnimationListener() {
#Override public void onAnimationStart(Animation animation) {}
#Override public void onAnimationRepeat(Animation animation) {}
#Override public void onAnimationEnd(Animation animation) {}
});
v.startAnimation(anim_in);
}
});
v.startAnimation(anim_out);
}
#Override
public void onClick(View v) {
final String inputmessage = this.inputMessage.getText().toString().trim();
if(!inputmessage.equals("")){
new AsyncTask<String, Void, AIResponse>(){
private AIError aiError;
#Override
protected AIResponse doInBackground(final String... params) {
final AIRequest request = new AIRequest();
String query = params[0];
if (!TextUtils.isEmpty(query))
request.setQuery(query);
try {
return aiDataService.request(request);
} catch (final AIServiceException e) {
aiError = new AIError(e);
return null;
}
}
#Override
protected void onPostExecute(final AIResponse response) {
if (response != null) {
onResult(response);
} else {
onError(aiError);
}
}
}.execute(inputmessage);
}else {
aiService.startListening();
}
inputMessage.setText("");
}
#Override
public void onResult(AIResponse response) {
int itemNumber = 0;
Log.d("dialogeflow response",response.toString());
try {
JSONObject AIResponse = new JSONObject(gson.toJson(response));
Log.d("json response",AIResponse.toString());
final JSONObject result = AIResponse.getJSONObject("result");
JSONArray contexts = result.getJSONArray("contexts");
final JSONObject fulfillment = result.getJSONObject("fulfillment");
if(contexts.length()>0) {
for(int i = 0;i<contexts.length();i++) {
JSONObject context_items = contexts.getJSONObject(i);
JSONObject paramters = context_items.getJSONObject("parameters");
if (paramters.has("Cuisine")) {
prefManager.setCuisinetype(paramters.getString("Cuisine"));
} else if (paramters.has("Restaurants_name")) {
prefManager.setRestaurant_name(paramters.getString("Restaurants_name"));
}
if (paramters.has("number") && !paramters.getString("number").equals("") && paramters.has("Food_Dishes") && !paramters.getString("Food_Dishes").equals("")) {
itemNumber = Integer.parseInt(paramters.getString("number"));
if (itemNumber <= 2 && price !=0) {
price = 300 + (int) (Math.random() * ((1400 - 300) + 1));
} else {
price = 600 + (int) (Math.random() * ((2200 - 600) + 1));
}
food_dish = paramters.getString("Food_Dishes");
}
}
}
final double finalPrice = price;
final int finalItemNumber = itemNumber;
if(!result.getString("resolvedQuery").matches("payment is done successfully")) {
Message usermsg = new Message();
usermsg.setMessage(result.getString("resolvedQuery"));
usermsg.setId("1");
messageArrayList.add(usermsg);
mAdapter.notifyDataSetChanged();
if (fulfillment.has("speech")) {
Log.d("response of speech", fulfillment.getString("speech"));
if (!fulfillment.getString("speech").equals("") && fulfillment.getString("speech") != null) {
final String speech = fulfillment.getString("speech");
if (fulfillment.getString("speech").matches("Redirecting you to the Pay-Tm site")) {
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
outMessage.setMessage(speech);
outMessage.setId("2");
messageArrayList.add(outMessage);
mAdapter.notifyDataSetChanged();
getpaytm_params((int) price);
}
}, 2000);
} else {
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
if (speech.contains("Your total bill is ₹")) {
Log.d("price", String.valueOf(price));
outMessage.setMessage("Please Confirm your order:- \n" +finalItemNumber +" "+food_dish+" from "+prefManager.getRestaurant_name()+" at Flat No: 20,Galaxy Apartment,Airport Authority Colony,Andheri,Mumbai,Maharashtra 400 047 \n Your total bill is ₹"+price+". \n Do you want to pay by Wallet or by PayTm");
}else{
outMessage.setMessage(speech);
}
outMessage.setId("2");
messageArrayList.add(outMessage);
Log.d("messgae",outMessage.getMessage());
mAdapter.notifyDataSetChanged();
}
}, 2000);
}
} else {
final JSONArray msg = fulfillment.getJSONArray("messages");
for (int i = 0; i < msg.length(); i++) {
if (i == 0) {
Message outMessage = new Message();
JSONObject speechobj = msg.getJSONObject(i);
JSONArray speech = speechobj.getJSONArray("speech");
Log.d("response of speech", speech.getString(0));
outMessage.setMessage(speech.getString(0));
outMessage.setId("2");
messageArrayList.add(outMessage);
} else {
final int itemposition = i;
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
try {
JSONObject speechobj = msg.getJSONObject(itemposition);
JSONArray speech = speechobj.getJSONArray("speech");
Log.d("response of speech", speech.getString(0));
outMessage.setMessage(speech.getString(0));
outMessage.setId("2");
messageArrayList.add(outMessage);
mAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, 5000);
}
}
}
}
}else{
if (!fulfillment.getString("speech").equals("") && fulfillment.getString("speech") != null) {
final String speech = fulfillment.getString("speech");
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
outMessage.setMessage(speech);
outMessage.setId("2");
messageArrayList.add(outMessage);
mAdapter.notifyDataSetChanged();
}
},2000);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(AIError error) {
}
#Override
public void onAudioLevel(float level) {
}
#Override
public void onListeningStarted() {
btnSend.setBackground(getDrawable(R.drawable.recording_bg));
}
#Override
public void onListeningCanceled() {
btnSend.setBackground(getDrawable(R.drawable.stedy_recording));
}
#Override
public void onListeningFinished() {
btnSend.setBackground(getDrawable(R.drawable.stedy_recording));
}
}`
my ChatAdapter.java class
public class ChatAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private int BOT = 100;
private int BOT_Restaurant_ListView = 101;
private int USER = 102;
private Activity activity;
private PrefManager prefManager;
private int itemposition = -1;
private int menu_itemposition = -1;
private List<Restaurant_List_Model> restaurant_list;
private ArrayList<Message> messageArrayList;
private RestaurantListViewAdapter restaurantListViewAdapter;
private TextToSpeech tts ;
public ChatAdapter(Activity activity, ArrayList<Message> messageArrayList) {
this.activity = activity;
this.messageArrayList = messageArrayList;
tts = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR){
tts.setLanguage(Locale.ENGLISH);
}
}
});
prefManager = new PrefManager(activity.getApplicationContext());
setHasStableIds(true);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemview;
if(viewType == BOT){
itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.bot_msg_view,parent,false);
}else if(viewType == BOT_Restaurant_ListView){
itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.bot_msg_restaurant_listview,parent,false);
}else {
itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_msg_view,parent,false);
}
return new ViewHolder(itemview);
}
#Override
public int getItemViewType(int position) {
Message message = messageArrayList.get(position);
if(message.getId()!=null && message.getId().equals("2")){
if(message.getMessage().contains("restaurants") || message.getMessage().contains("restaurant")) {
return BOT_Restaurant_ListView;
}else {
return BOT;
}
}else{
return USER;
}
}
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, int position) {
int pic_int = 1;
String filename = null;
final Message message = messageArrayList.get(position);
message.setMessage(message.getMessage());
if (holder.getItemViewType() == BOT_Restaurant_ListView) {
Log.d("inside bot listview msg", String.valueOf(BOT_Restaurant_ListView ));
Log.d("adapter position", String.valueOf(holder.getAdapterPosition()));
if(itemposition<holder.getAdapterPosition()){
itemposition = holder.getAdapterPosition();
Log.d("itemposition",String.valueOf(itemposition));
String jsonFileContent;
Log.d("cuisine value", prefManager.getCuisinetype());
if (message.getMessage().contains("restaurants")) {
if(!prefManager.getCuisinetype().equals("") && prefManager.getCuisinetype() != null){
Log.d("restauratn has drawn", "greate");
try {
restaurant_list = new ArrayList<>();
restaurantListViewAdapter = new RestaurantListViewAdapter(activity, restaurant_list);
((ViewHolder) holder).retaurant_listView.setVisibility(View.VISIBLE);
((ViewHolder) holder).retaurant_listView.setAdapter(restaurantListViewAdapter);
Log.d("cuisine value", prefManager.getCuisinetype());
if(message.getMessage().contains("Here are restaurants near you")){
String [] restaurant_Array ={
"indian","french","mexican","italian"
};
int randomNumber = (int) Math.floor(Math.random()*restaurant_Array.length);
filename = restaurant_Array[randomNumber];
Log.d("filename",filename);
jsonFileContent = readFile(activity.getResources().getIdentifier(filename, "raw", activity.getPackageName()));
}else {
filename = prefManager.getCuisinetype().toLowerCase() + "_restaurants";
Log.d("filename", filename);
jsonFileContent = readFile(activity.getResources().getIdentifier(filename, "raw", activity.getPackageName()));
}
JSONObject restaurantfile = new JSONObject(jsonFileContent);
JSONArray jsonArray = restaurantfile.getJSONArray("restaurants");
for (int i = 0; i < jsonArray.length(); i++) {
ImageRoundCorner imageRoundCorner = new ImageRoundCorner();
JSONObject restaurantList = jsonArray.getJSONObject(i);
Restaurant_List_Model restaurant_list_obj = new Restaurant_List_Model();
restaurant_list_obj.setName(restaurantList.getString("name"));
restaurant_list_obj.setLocation(restaurantList.getString("location"));
restaurant_list_obj.setImage_of_item(imageRoundCorner.getRoundedCornerBitmap(BitmapFactory.decodeResource(activity.getResources(), activity.getResources().getIdentifier("restaurant_" + pic_int, "drawable", activity.getPackageName()))));
pic_int++;
restaurant_list_obj.setRating(restaurantList.getLong("rating"));
restaurant_list.add(restaurant_list_obj);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
} else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
prefManager.setCuisinetype("");
pic_int = 1;
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
restaurantListViewAdapter.notifyDataSetChanged();
}
}else if(message.getMessage().contains("Here are some famous food items from "+prefManager.getRestaurant_name()+" restaurant")){
try {
Log.d("menu has draw","greate");
restaurant_list = new ArrayList<>();
restaurantListViewAdapter = new RestaurantListViewAdapter(activity, restaurant_list);
((ViewHolder) holder).retaurant_listView.setAdapter(restaurantListViewAdapter);
((ViewHolder) holder).retaurant_listView.setVisibility(View.VISIBLE);
Log.d("restaurant name value", prefManager.getRestaurant_name());
jsonFileContent = readFile(R.raw.restaurant_menu);
JSONObject menu_cuisine = new JSONObject(jsonFileContent);
ImageRoundCorner imageRoundCorner = new ImageRoundCorner();
if (menu_cuisine.has(prefManager.getRestaurant_name())) {
JSONObject restaurant_menu = menu_cuisine.getJSONObject("Dominos");
Log.d("Chili's American menu", restaurant_menu.toString());
JSONArray menu = restaurant_menu.getJSONArray("menu");
for (int j = 0; j < menu.length(); j++) {
JSONObject menu_obj = menu.getJSONObject(j);
Restaurant_List_Model restaurant_list_obj = new Restaurant_List_Model();
restaurant_list_obj.setName(menu_obj.getString("name"));
restaurant_list_obj.setLocation(menu_obj.getString("cuisine_type"));
restaurant_list_obj.setImage_of_item(imageRoundCorner.getRoundedCornerBitmap(BitmapFactory.decodeResource(activity.getResources(), activity.getResources().getIdentifier("menu_" + pic_int, "drawable", activity.getPackageName()))));
//restaurant_list_obj.setImage_of_item(imageRoundCorner.getRoundedCornerBitmap(BitmapFactory.decodeResource(activity.getResources(), activity.getResources().getIdentifier("menu_" + pic_int, "drawable", activity.getPackageName()))));
pic_int++;
restaurant_list_obj.setRating(menu_obj.getLong("rating"));
restaurant_list.add(restaurant_list_obj);
}
restaurantListViewAdapter.notifyDataSetChanged();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
} else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
pic_int = 1;
prefManager.setRestaurant_name("");
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Log.d("user_message",message.getMessage());
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
}else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
pic_int = 1;
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
((ViewHolder) holder).retaurant_listView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
v.onTouchEvent(event);
return true;
}
});
}
} if(holder.getItemViewType()==BOT) {
Log.d("adapter position", String.valueOf(holder.getAdapterPosition()));
Log.d("inside bot msg", String.valueOf(BOT));
((ViewHolder) holder).bot_msg.setText(message.getMessage());
if(itemposition<holder.getAdapterPosition()) {
itemposition = holder.getAdapterPosition();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
} else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
}
}if(holder.getItemViewType() == USER) {
((ViewHolder) holder).user_message.setText(message.getMessage());
}
}
#Override
public void onViewRecycled(#NonNull RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
if(holder.isRecyclable()){
Log.d("inside onViewRecycled","great");
// itemposition = holder.getAdapterPosition();
}
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public int getItemCount() {
return messageArrayList.size();
}
private String readFile(int id) throws IOException
{
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(activity.getResources().openRawResource(id)));
String content = "";
String line;
while ((line = reader.readLine()) != null)
{
content = content + line;
}
return content;
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView user_message,bot_msg;
private ListView retaurant_listView;
ViewHolder(View itemView) {
super(itemView);
bot_msg = itemView.findViewById(R.id.bot_message);
user_message = itemView.findViewById(R.id.message);
retaurant_listView = itemView.findViewById(R.id.restaurant_items_list_ibm);
}
}
}
Please help me out with this issue.
In gif, you can see the lower list is swap with the upper list and then return back

I used PagerAdapter for sliding images its not notifying properly

I used PagerAdapter for sliding images and i added a favorite button too in that sliding image. After clicking favorite button its not getting notified properly image not turns to unfavorite icon.
it is for loading api
private class PremiumProjectLoad extends AsyncTask<String, Void, JSONObject> {
JSONParser jsonParser = new JSONParser();
String url= ApiLinks.PremiumProject;
ProgressHUD mProgressHUD;
protected void onPreExecute(){
mProgressHUD = ProgressHUD.show(getActivity(),null, true);
super.onPreExecute();
}
protected JSONObject doInBackground(String... arg0) {
HashMap<String,String> params=new HashMap<>();
try {
params.put("languageID",CommonStrings.languageID);
params.put("cityID",CommonStrings.cityID);
if(session.isLoggedIn()){
params.put("userID",UserLogin.get(SessionManager.KEY_CUSTOMER_ID));
}
JSONObject json = jsonParser.SendHttpPosts(url,"POST",params);
if (json != null) {
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
if(json!=null) {
String Status=json.optString("status");
String Message=json.optString("message");
CommonImagePath=json.optString("imagepath");
PremiumDataArray.clear();
if(Status.equals("ok")){
JSONArray DataArray=json.optJSONArray("data");
if(DataArray!=null && DataArray.length()>0) {
for (int i = 0; i < DataArray.length(); i++) {
JSONObject DataObj = DataArray.optJSONObject(i);
String projectID = DataObj.optString("projectID");
String projectName = DataObj.optString("projectName");
String propertyUnitPriceRange = DataObj.optString("propertyUnitPriceRange");
String projectOfMonthImage = DataObj.optString("projectOfMonthImage");
String propertyUnitBedRooms = DataObj.optString("propertyUnitBedRooms");
String projectBuilderName = DataObj.optString("projectBuilderName");
String propertyTypeName = DataObj.optString("propertyTypeName");
String purpose = DataObj.optString("purpose");
String projectBuilderAddress = DataObj.optString("projectBuilderAddress");
String projectFavourite = DataObj.optString("projectFavourite");
PremiumData premiumData = new PremiumData();
premiumData.setProjectID(projectID);
premiumData.setProjectName(projectName);
premiumData.setPropertyUnitPriceRange(propertyUnitPriceRange);
premiumData.setProjectOfMonthImage(projectOfMonthImage);
premiumData.setPropertyUnitBedRooms(propertyUnitBedRooms);
premiumData.setProjectBuilderName(projectBuilderName);
premiumData.setPropertyTypeName(propertyTypeName);
premiumData.setPurpose(purpose);
premiumData.setProjectBuilderAddress(projectBuilderAddress);
premiumData.setProjectFavourite(projectFavourite);
PremiumDataArray.add(premiumData);
}
LoopViewPager viewpager = (LoopViewPager) homeView.findViewById(R.id.viewpager);
CircleIndicator indicator = (CircleIndicator) homeView.findViewById(R.id.indicator);
// if(pagerAdapter==null)
pagerAdapter = new PremiumProjectAdapter(getActivity(), PremiumDataArray);
viewpager.setAdapter(pagerAdapter);
indicator.setViewPager(viewpager);
// pagerAdapter.notifyDataSetChanged();
}
}
else {
Toast.makeText(getActivity(),Message, Toast.LENGTH_LONG).show();
}
}
mProgressHUD.dismiss();
}
}
pager adapter
public class PremiumProjectAdapter extends PagerAdapter {
private final Random random = new Random();
private ArrayList<PremiumData> mSize;
Context mContext;
LayoutInflater mLayoutInflater;
String ProjectID;
String path=CommonImagePath+"/uploads/projectOfMonth/orginal/";
// public PremiumProjectAdapter() {
// }
public PremiumProjectAdapter(Context contexts, ArrayList<PremiumData> count) {
mSize = count;
mContext=contexts;
}
#Override public int getCount() {
return mSize.size();
}
#Override public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override public void destroyItem(ViewGroup view, int position, Object object) {
view.removeView((View) object);
}
#Override public Object instantiateItem(ViewGroup view, final int position) {
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = mLayoutInflater.inflate(R.layout.home_premium_layout, view, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.premium_ProImage);
TextView ProjectName = (TextView) itemView.findViewById(R.id.premium_ProName);
TextView ProjectUnitPrice = (TextView) itemView.findViewById(R.id.premium_UnitPrice);
TextView ProjectUnitBedroom = (TextView) itemView.findViewById(R.id.premium_UnitBedrooms);
TextView ProjectAddress = (TextView) itemView.findViewById(R.id.premium_ProAddress);
ImageView unshortlisted = (ImageView) itemView.findViewById(R.id.unshortlisted);
ImageView shortlisted = (ImageView) itemView.findViewById(R.id.shortlisted);
final PremiumData data = mSize.get(position);
if (data.getProjectFavourite() != null) {
if (data.getProjectFavourite().equals("ShortListed")) {
shortlisted.setVisibility(View.VISIBLE);
unshortlisted.setVisibility(View.GONE);
} else {
shortlisted.setVisibility(View.GONE);
unshortlisted.setVisibility(View.VISIBLE);
}
}
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
ProjectUnitPrice.setText(Html.fromHtml(data.getPropertyUnitPriceRange(), Html.FROM_HTML_MODE_COMPACT));
}else{
ProjectUnitPrice.setText(Html.fromHtml(data.getPropertyUnitPriceRange()));
}
ImageLoader.getInstance().displayImage(path+data.getProjectOfMonthImage(), imageView);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
if(!data.getProjectName().equals("null") && data.getProjectName().length()>30){
String s = data.getProjectName().substring(0, 25);
String subString = s + "...";
ProjectName.setText(subString);
}
else{
ProjectName.setText(data.getProjectName());
}
ProjectUnitBedroom.setText(data.getPropertyUnitBedRooms());
ProjectAddress.setText(data.getProjectBuilderAddress());
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent DetailsAction=new Intent(mContext, DetailsActivity.class);
DetailsAction.putExtra("projectID",data.getProjectID());
DetailsAction.putExtra("purpose",data.getPurpose());
mContext.startActivity(DetailsAction);
}
});
unshortlisted.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!session.isLoggedIn()){
Intent toLogin=new Intent(mContext, LoginActivity.class);
CommonStrings.FromSearchIndex="true";
mContext.startActivity(toLogin);
}else{
ProjectID=data.getProjectID();
new ShortlistProject().execute();
}
}
});
shortlisted.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProjectID=data.getProjectID();
new UnShortlistProject().execute();
}
});
view.addView(itemView);
return itemView;
}
private class ShortlistProject extends AsyncTask<String, Void, JSONObject> {
JSONParser jsonParser = new JSONParser();
String url=ApiLinks.AddShortListProject;
ProgressHUD mProgressHUD;
protected void onPreExecute(){
mProgressHUD = ProgressHUD.show(mContext,null, true);
super.onPreExecute();
}
protected JSONObject doInBackground(String... arg0) {
HashMap<String,String> params=new HashMap<>();
try {
params.put("languageID",CommonStrings.languageID);
params.put("userID",User.get(SessionManager.KEY_CUSTOMER_ID));
params.put("projectID",ProjectID);
params.put("userType",User.get(SessionManager.KEY_USERTYPE_ID));
JSONObject json = jsonParser.SendHttpPosts(url,"POST",params);
if (json != null) {
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
if(json!=null) {
String status=json.optString("status");
String message=json.optString("message");
if(status.equals("ok")){
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
//SearchFragment.getInstance().onResume();
HomeFragment.getInstance().async_premium();
}else{
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
}
}
mProgressHUD.dismiss();
}
}
private class UnShortlistProject extends AsyncTask<String, Void, JSONObject> {
JSONParser jsonParser = new JSONParser();
String url=ApiLinks.RemoveShortListProject;
ProgressHUD mProgressHUD;
protected void onPreExecute(){
mProgressHUD = ProgressHUD.show(mContext,null, true);
super.onPreExecute();
}
protected JSONObject doInBackground(String... arg0) {
HashMap<String,String> params=new HashMap<>();
try {
params.put("userID",User.get(SessionManager.KEY_CUSTOMER_ID));
params.put("projectID",ProjectID);
params.put("userType",User.get(SessionManager.KEY_USERTYPE_ID));
JSONObject json = jsonParser.SendHttpPosts(url,"POST",params);
if (json != null) {
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
if(json!=null) {
String status=json.optString("status");
String message=json.optString("message");
if(status.equals("ok")){
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
// HomeFragment.getInstance().async_Premium();
HomeFragment.getInstance().async_premium();
}else{
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
}
}
mProgressHUD.dismiss();
}
}
As far as i am able to understand your question you want favorite and unfavorite functionality by adapter . Please use this code below to achieve that :
public class CustomGridAdapterFoodDrink extends BaseAdapter {
private Context mContext;
private ProgressDialog loading;
ArrayList<FoodDrink> foodDrinkArrayList = new ArrayList<>();
SharedPreferences pref;
String userId;
String like_dislike_value = "Like";
String likeValueStr = "1";
boolean like = true;
int positionVal = 444;
HashMap<Integer,Boolean> state = new HashMap<>();
public CustomGridAdapterFoodDrink(Context c, ArrayList<FoodDrink> foodDrinkArrayList) {
mContext = c;
this.foodDrinkArrayList = foodDrinkArrayList;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return foodDrinkArrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid_single, null);
TextView projectNamtTxtView = (TextView) grid.findViewById(R.id.projectName);
TextView totalOfferText = (TextView) grid.findViewById(R.id.TotalOffers);
ImageView merchantImage = (ImageView) grid.findViewById(R.id.merchantImage);
final ImageView like_dislike_icon = (ImageView) grid.findViewById(R.id.like_dislike_icon);
totalOfferText.setText(foodDrinkArrayList.get(position).getOffers());
projectNamtTxtView.setText(foodDrinkArrayList.get(position).getProject_name());
Glide.with(mContext)
.load(foodDrinkArrayList.get(position).getProject_photo())
.centerCrop()
.placeholder(R.drawable.review_pro_pic1)
.crossFade()
.into(merchantImage);
like_dislike_icon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
userId = pref.getString("userId", null);
/* if(state.size()> 0){
like = state.get(position);*/
if (!like) {
like = true;
/* state.put(position,like);*/
like_dislike_icon.setImageResource(R.mipmap.like_it_act);
likeDislike2(foodDrinkArrayList.get(position).getID(), "1");
} else {
like = false;
/* state.put(position,like);*/
like_dislike_icon.setImageResource(R.mipmap.like_it);
likeDislike2(foodDrinkArrayList.get(position).getID(), "0");
}
/* } else {
like = true;
state.put(position,like);
like_dislike_icon.setImageResource(R.mipmap.like_it_act);
likeDislike2(foodDrinkArrayList.get(position).getID(), "1");
}*/
// if(positionVal !=position) {
// likeValueStr ="1";
// positionVal = position;
// likeDislike(foodDrinkArrayList.get(position).getID(), likeValueStr, like_dislike_icon);
// }
// else {
// likeValueStr ="0";
// likeDislike(foodDrinkArrayList.get(position).getID(), likeValueStr, like_dislike_icon);
// }
}
});
} else {
grid = (View) convertView;
}
return grid;
}
private void likeDislike(String merchantId, final String like_dislike, final ImageView imageView) {
loading = ProgressDialog.show(mContext, "Loading ", "Please wait...", true, true);
AsyncHttpClient client = new AsyncHttpClient();
String url = getlikeUrl(userId, merchantId, like_dislike);
client.setMaxRetriesAndTimeout(5, 20000);
client.post(url, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String responseString) {
try {
JSONObject _object = new JSONObject(responseString);
String status = _object.getString("success");
String msg = _object.getString("response");
if ("true".equalsIgnoreCase(status)) {
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
if (msg.equalsIgnoreCase("Like")) {
imageView.setImageResource(R.mipmap.like_it_act);
} else {
imageView.setImageResource(R.mipmap.like_it);
}
} else {
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
}
loading.dismiss();
// AppUtility.showToast(SignUp.this, message);
} catch (JSONException e) {
e.printStackTrace();
new Global().saveReport("abc", e.getStackTrace(), e.toString());
}
loading.dismiss();
}
#Override
public void onFailure(int statusCode, Throwable error, String content) {
}
});
}
private String getlikeUrl(String userId, String merchantId, String like_dislike) {
String url = "";
try {
url = NetworkURL.URL
+ "likeMerchant"
+ "?user_id=" + URLEncoder.encode(new Global().checkNull(userId), "UTF-8")
+ "&merchant_id=" + URLEncoder.encode(new Global().checkNull(merchantId), "UTF-8")
+ "&like_dislike=" + URLEncoder.encode(new Global().checkNull(like_dislike), "UTF-8")
;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
new Global().saveReport("abc", e.getStackTrace(), e.toString());
}
return url;
}
private void likeDislike2(String merchantId, final String like_dislike) {
loading = ProgressDialog.show(mContext, "Loading ", "Please wait...", true, true);
AsyncHttpClient client = new AsyncHttpClient();
String url = getlikeUrl(userId, merchantId, like_dislike);
client.setMaxRetriesAndTimeout(5, 20000);
client.post(url, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String responseString) {
try {
JSONObject _object = new JSONObject(responseString);
String status = _object.getString("success");
String msg = _object.getString("response");
if ("true".equalsIgnoreCase(status)) {
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
}
loading.dismiss();
// AppUtility.showToast(SignUp.this, message);
} catch (JSONException e) {
e.printStackTrace();
new Global().saveReport("abc", e.getStackTrace(), e.toString());
}
loading.dismiss();
}
#Override
public void onFailure(int statusCode, Throwable error, String content) {
}
});
}
}

How to do Filter listview in android?

How to do the Filter concept from Below design? I here by attached two screen designs.
DashBoard Fragment -> Having Listview with Base adapter.
The above ListView code is given Below
DashBoardRefactor
public class DashBoardRefactor extends Fragment {
public static ProgressDialog progress;
public static List<DashListModel> dashRowList1 = new ArrayList<DashListModel>();
public static View footerView;
// #Bind(R.id.dashListView)
public static ListView dashListView;
int preCount = 2, scroll_Inc = 10, lastCount;
boolean flag = true;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dashboard_fragment, container, false);
ButterKnife.bind(this, v);
setHasOptionsMenu(true);
progress = new ProgressDialog(getActivity());
dashListView = (ListView) v.findViewById(R.id.dashListView);
footerView = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.dashboard_list_footer, null, false);
dashListView.addFooterView(footerView);
footerView.setVisibility(View.GONE);
dashRowList1.clear();
dashboardViewTask();
dashListView.setOnScrollListener(new EndlessScrollListener(getActivity(), dashListView, footerView));
return v;
}
public void dashboardViewTask() {
progress.setMessage("Loading...");
progress.setCanceledOnTouchOutside(false);
progress.setCancelable(false);
progress.show();
// footerView.setVisibility(View.VISIBLE);
Map<String, String> params = new HashMap<String, String>();
Log.e("candidate_id", "candidate_id---->" + SessionStores.getBullHornId(getActivity()));
params.put("candidate_id", SessionStores.getBullHornId(getActivity()));
params.put("employmentPreference", SessionStores.getEmploymentPreference(getActivity()));
params.put("page", "1");
new DashBoardTask(getActivity(), params, dashListView, footerView);
}
#Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
if (menu != null) {
menu.removeItem(R.id.menu_notify);
}
inflater.inflate(R.menu.menu_options, menu);
MenuItem item = menu.findItem(R.id.menu_filter);
item.setVisible(true);
getActivity().invalidateOptionsMenu();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.his__menu_accept:
Toast.makeText(getActivity(), "clicked dashboard menu accept", Toast.LENGTH_LONG).show();
return true;
case R.id.menu_filter:
// click evnt for filter
Toast.makeText(getActivity(), "clicked dashboard filter", Toast.LENGTH_LONG).show();
Intent filter_intent = new Intent(getActivity(), DashBoardFilterScreen.class);
startActivity(filter_intent);
getActivity().overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onPause() {
super.onPause();
// dashboardViewTask();
}
}
DashBoardTask:
public class DashBoardTask {
public static String candidateIdNo;
public static Integer isBookmarked;
public ListAdapter dashListAdapter;
ListView dashListView;
View footerView;
String fromdate_formated = "";
String todate_formated = "";
private Context context;
private JSONObject jObject = null;
private String result, authorizationKey;
private Map<String, String> params;
public DashBoardTask(Context context, Map<String, String> params, ListView dashListView, View footerView) {
this.context = context;
Log.e("context ", "DashBoardTask: " + context);
this.dashListView = dashListView;
Dashboard.dashRowList.clear();
this.params = params;
this.footerView = footerView;
ResponseTask();
}
private void ResponseTask() {
authorizationKey = Constants.ACCESS_TOKEN;
new ServerResponse(ApiClass.getApiUrl(Constants.DASHBOARD_VIEW)).getJSONObjectfromURL(ServerResponse.RequestType.POST, params, authorizationKey, context, "", new VolleyResponseListener() {
#Override
public void onError(String message) {
if (DashBoardRefactor.progress.isShowing()) {
DashBoardRefactor.progress.dismiss();
}
}
#Override
public void onResponse(String response) {
String dateEnd = "", startDate = "";
result = response.toString();
try {
jObject = new JSONObject(result);
if (jObject != null) {
Integer totalJobList = jObject.getInt("page_count");
Integer total = jObject.getInt("total");
Integer count = jObject.getInt("count");
Integer start = jObject.getInt("start");
if (footerView.isShown() && count == 0) {
footerView.setVisibility(View.GONE);
}
Integer Status = jObject.getInt("status");
if (Status == 1) {
SessionStores.savetotalJobList(totalJobList, context);
JSONArray dataObject = jObject.getJSONArray("data");
Dashboard.dashRowList.clear();
for (int i = 0; i < dataObject.length(); i++) {
Log.e("length", "lenght----->" + dataObject.length());
JSONObject jobDetail = dataObject.getJSONObject(i);
Log.e("jobDetail", "jobDetail----->" + jobDetail);
Integer goalsName = jobDetail.getInt("id");
String compnyTitle = jobDetail.getString("title");
String description = jobDetail.getString("description");
Integer salary = jobDetail.getInt("salary");
String dateAdded = jobDetail.getString("dateAdded");
if (jobDetail.getString("startDate") != null && !jobDetail.getString("startDate").isEmpty() && !jobDetail.getString("startDate").equals("null")) {
startDate = jobDetail.getString("startDate");
} else {
Log.e("Task Null", "Task Null----startDate->");
}
if (jobDetail.getString("dateEnd") != null && !jobDetail.getString("dateEnd").isEmpty() && !jobDetail.getString("dateEnd").equals("null")) {
dateEnd = jobDetail.getString("dateEnd");
} else {
Log.e("Task Null", "Task Null----->");
}
isBookmarked = jobDetail.getInt("isBookmarked");
Integer startSalary = jobDetail.getInt("customFloat1");
Integer endSalary = jobDetail.getInt("customFloat2");
JSONObject cmpanyName = jobDetail.getJSONObject("clientCorporation");
String compnyNamede = cmpanyName.getString("name");
String city = jobDetail.getString("customText1");
JSONObject candidateId = jobDetail.getJSONObject("clientContact");
candidateIdNo = candidateId.getString("id");
DashListModel dashListItem = new DashListModel();
dashListItem.setDashCompanyName(compnyNamede);
dashListItem.setDashJobDescription(description);
dashListItem.setDashJobPosition(compnyTitle);
dashListItem.setDashJobCity(city);
// dashListItem.setDashJobState(state);
dashListItem.setDashSalary(startSalary.toString());
dashListItem.setDashJobAvailableDate(dateAdded);
dashListItem.setDashId(goalsName.toString());
dashListItem.setDashIsBookMarked(isBookmarked.toString());
dashListItem.setDashEndSalary(endSalary.toString());
dashListItem.setToDate(dateEnd);
////////////////////////////////////
String fromDate = null, toDate = null, postedDate = null;
if (startDate.length() > 11) {
Log.e("11", "11---->");
fromDate = Utils.convertFromUnixDateAdded(startDate);
} else if (startDate.length() == 10) {
Log.e("10", "10----->");
fromDate = Utils.convertFromUnix(startDate);
}
if (dateEnd.length() > 11) {
Log.e("11", "11---->");
toDate = Utils.convertFromUnixDateAdded(dateEnd);
} else if (dateEnd.length() == 10) {
Log.e("10", "10----->");
toDate = Utils.convertFromUnix(dateEnd);
}
if (dateAdded.length() > 11) {
Log.e("11", "11---->");
postedDate = Utils.convertFromUnixDateAdded(dateAdded);
} else if (dateAdded.length() == 10) {
Log.e("10", "10----->");
postedDate = Utils.convertFromUnix(dateAdded);
}
try {
if (!fromDate.isEmpty() || !fromDate.equalsIgnoreCase("null")) {
String[] fromDateSplit = fromDate.split("/");
String fromMonth = fromDateSplit[0];
String fromDat = fromDateSplit[1];
String fromYear = fromDateSplit[2];
String fromMonthName = new DateFormatSymbols().getMonths()[Integer.parseInt(fromMonth) - 1];
fromdate_formated = fromMonthName.substring(0, 3) + " " + fromDat + getDayOfMonthSuffix(Integer.parseInt(fromDat));
Log.e("fromdate", "fromdate---->" + fromDate);
Log.e("toDate", "toDate---->" + toDate);
Log.e("fromMonth", "fromMonth---->" + fromMonth);
Log.e("fromDat", "fromDat---->" + fromDat);
Log.e("fromYear", "fromYear---->" + fromYear);
}
if (!toDate.isEmpty() || !toDate.equalsIgnoreCase("null")) {
String[] toDateSplit = toDate.split("/");
String toMonth = toDateSplit[0];
String toDat = toDateSplit[1];
String toYear = toDateSplit[2];
String toMonthName = new DateFormatSymbols().getMonths()[Integer.parseInt(toMonth) - 1];
todate_formated = toMonthName.substring(0, 3) + " " + toDat + getDayOfMonthSuffix(Integer.parseInt(toDat)) + " " + toYear;
Log.e("________________", "-------------------->");
Log.e("toMonth", "toMonth---->" + toMonth);
Log.e("toDat", "toDat---->" + toDat);
Log.e("toYear", "toYear---->" + toYear);
Log.e("________________", "-------------------->");
Log.e("toMonthName", "toMonthName---->" + toMonthName);
}
} catch (Exception e) {
e.printStackTrace();
}
dashListItem.setPostedDate(postedDate);
dashListItem.setFromDate(fromdate_formated);
dashListItem.setEndDate(todate_formated);
/////////////////////////////////////////
// Dashboard.dashRowList.add(dashListItem);
DashBoardRefactor.dashRowList1.add(dashListItem);
}
// get listview current position - used to maintain scroll position
int currentPosition = dashListView.getFirstVisiblePosition();
dashListAdapter = new DashListAdapter(context, DashBoardRefactor.dashRowList1, dashListView);
dashListView.setAdapter(dashListAdapter);
((BaseAdapter) dashListAdapter).notifyDataSetChanged();
if (currentPosition != 0) {
// Setting new scroll position
dashListView.setSelectionFromTop(currentPosition + 1, 0);
}
} else if (Status==0 && count==0 && start==0){
String Message = jObject.getString("message");
Utils.ShowAlert(context, Message);
}
if (footerView.isShown()) {
footerView.setVisibility(View.GONE);
}
//progress.dismiss();
if (DashBoardRefactor.progress.isShowing()) {
try {
DashBoardRefactor.progress.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
}
DashListModel:
public class DashListModel {
private String dashCompanyName;
private String dashJobPosition;
private String dashJobPostedDate;
private String dashJobDescription;
private String dashSalary;
private String dashJobCity;
private String dashJobState;
private String dashJobAvailableDate;
private String dashId, dashIsBookmarked;
private String dashEndSalary;
private String toDate;
private String postedDate, fromdate, enddate;
public String getDashCompanyName() {
return dashCompanyName;
}
public void setDashCompanyName(String dashCompanyName) {
this.dashCompanyName = dashCompanyName;
}
public String getDashJobPosition() {
return dashJobPosition;
}
public void setDashJobPosition(String dashJobPosition) {
this.dashJobPosition = dashJobPosition;
}
public String getDashJobDescription() {
return dashJobDescription;
}
public void setDashJobDescription(String dashJobDescription) {
this.dashJobDescription = dashJobDescription;
}
public String getDashJobPostedDate() {
return dashJobPostedDate;
}
public void setDashJobPostedDate(String dashJobPostedDate) {
this.dashJobPostedDate = dashJobPostedDate;
}
public String getDashSalary() {
return dashSalary;
}
public void setDashSalary(String dashSalary) {
this.dashSalary = dashSalary;
}
public String getDashJobCity() {
return dashJobCity;
}
public void setDashJobCity(String dashJobCity) {
this.dashJobCity = dashJobCity;
}
/* public String getDashJobState() {
return dashJobState;
}
public void setDashJobState(String dashJobState) {
this.dashJobState = dashJobState;
}*/
public String getDashJobAvailableDate() {
return dashJobAvailableDate;
}
public void setDashJobAvailableDate(String dashJobAvailableDate) {
this.dashJobAvailableDate = dashJobAvailableDate;
}
public String getDashId() {
return dashId;
}
public void setDashId(String dashId) {
this.dashId = dashId;
}
public String getDashIsBookmarked() {
return dashIsBookmarked;
}
public void setDashIsBookMarked(String dashIsBookmarked) {
this.dashIsBookmarked = dashIsBookmarked;
}
public String getDashEndSalary() {
return dashEndSalary;
}
public void setDashEndSalary(String dashEndSalary) {
this.dashEndSalary = dashEndSalary;
}
public String getToDate() {
return toDate;
}
public void setToDate(String toDate) {
this.toDate = toDate;
}
public String getPostedDate() {
return postedDate;
}
public void setPostedDate(String postedDate) {
this.postedDate = postedDate;
}
public String getFromDate() {
return fromdate;
}
public void setFromDate(String fromdate) {
this.fromdate = fromdate;
}
public String getEndDate() {
return enddate;
}
public void setEndDate(String enddate) {
this.enddate = enddate;
}
DashListAdapter:
package com.peoplecaddie.adapter;
public class DashListAdapter extends BaseAdapter {
public static ListView dashListView;
Context c;
private LayoutInflater inflater;
private List<DashListModel> dashRowList;
public DashListAdapter(Context c, List<DashListModel> dashRowList, ListView dashListView) {
this.c = c;
this.dashListView = dashListView;
this.dashRowList = dashRowList;
}
#Override
public int getCount() {
return this.dashRowList.size();
}
#Override
public Object getItem(int position) {
return dashRowList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder dashHolder;
if (inflater == null)
inflater = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.dashboard_jobdetails_list, null);
final DashListModel dashModel = dashRowList.get(position);
dashHolder = new ViewHolder(convertView);
dashHolder.dash_company_name.setText(dashModel.getDashCompanyName());
dashHolder.dash_position_name.setText(dashModel.getDashJobPosition());
dashHolder.dash_posted_date.setText(dashModel.getPostedDate());
dashHolder.dash_job_description.setText(Utils.stripHtml(dashModel.getDashJobDescription()));
dashHolder.dash_salary.setText(dashModel.getDashSalary() + " - " + dashModel.getDashEndSalary());
dashHolder.dash_available_date.setText(dashModel.getFromDate() + " - " + dashModel.getEndDate());
dashHolder.book_jobCity.setText(dashModel.getDashJobCity());
if (dashModel.getDashIsBookmarked().equalsIgnoreCase("1")) {
dashHolder.bookmark_img.setImageResource(R.drawable.bookmark);
} else if (dashModel.getDashIsBookmarked().equalsIgnoreCase("0")) {
dashHolder.bookmark_img.setImageResource(R.drawable.blue_tag_img);
}
dashHolder.bookmark_img.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (dashModel.getDashIsBookmarked().equalsIgnoreCase("0")) {
dashModel.setDashIsBookMarked("1");
Map<String, String> params = new HashMap<String, String>();
params.put("candidate_id", SessionStores.getBullHornId(c));
params.put("joborder_id", dashModel.getDashId());
BackGroundTasks bookmark_add_bg_tasks = new BackGroundTasks(c, new JSONObject(params), Constants.BOOKMARK_ADD_TAG);
bookmark_add_bg_tasks.ResponseTask(new BackGroundTasks.VolleyCallbackOnEdit() {
#Override
public void onSuccess(String result) {
String resp_resultsd = result;
Log.e("insidecallback", " bookmark_add_bg_tasks----->" + resp_resultsd);
// finish();
dashHolder.bookmark_img.setImageResource(R.drawable.bookmark);
notifyDataSetChanged();
}
});
} else if (dashModel.getDashIsBookmarked().equalsIgnoreCase("1")) {
dashModel.setDashIsBookMarked("0");
Log.e("imgchange", " imgchange");
Map<String, String> params = new HashMap<String, String>();
params.put("candidate_id", SessionStores.getBullHornId(c));
params.put("joborder_id", dashModel.getDashId());
BackGroundTasks bookmark_delete_bg_tasks = new BackGroundTasks(c, new JSONObject(params), Constants.BOOKMARK_DELETE_TAG);
bookmark_delete_bg_tasks.ResponseTask(new BackGroundTasks.VolleyCallbackOnEdit() {
#Override
public void onSuccess(String result) {
String resp_resultsd = result;
Log.e("insidecallback", " bookmark_delete_bg_tasks----->" + resp_resultsd);
// finish();
dashHolder.bookmark_img.setImageResource(R.drawable.blue_tag_img);
notifyDataSetChanged();
}
});
}
}
});
return convertView;
}
static class ViewHolder {
#Bind(R.id.book_company_name)
TextView dash_company_name;
private RelativeLayout.LayoutParams viewLayParams;
public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
Clarification:
How do to Filter while click the Filter Button On DashBoard Fragment. Please Suggest the way. I here by attached My Filter design also.
Dashboard Fragment--> Filter Button-> Filter screen-> the Filtered results should view on DashBoard Fragment.
Once click the apply Button Based on the input from Filter screen it filters the list view the result comes from back end team. I have to display that result on Dashboard Fragment.
Kindly please clarify this Filter concept.

How to implement Scroll Listener in android

I am using OnScrolListener to add items to a ListView in my app .Scrolling is working fine, but i am facing an error . when I scroll to bottom,data add to list ,but position start from top .Please help me
public class Hotel_list_activity extends AppCompatActivity implements View.OnClickListener {
Global global;
ListView hotel_list;
SharedPreferences mpref;
SharedPreferences.Editor ed;
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
TextView checkIn, checkout, number_of_persons_text, number_of_room_text;
LinearLayout hotel_list_back_image;
boolean isLoading = false;
Bundle translateBundle;
int count, Page_inc = 1;
int next;
#TargetApi(Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hotel_list_activity);
global = (Global) getApplicationContext();
mpref = getSharedPreferences("com.example.brightroots.flight_app", Context.MODE_PRIVATE);
init();
startAnim();
GetHotel();
//initList();
hotel_list.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView arg0, int scrollState) {
// If scroll state is touch scroll then set userScrolled
// true
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
isLoading = true;
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// Now check if userScrolled is true and also check if
// the item is end then update list view and set
// userScrolled to false
if (isLoading
&& firstVisibleItem + visibleItemCount == totalItemCount) {
isLoading = false;
loadMore();
}
}
});
}
private void loadMore() {
Log.e("count_value", count + "");
Log.e("count_Page", Page_inc + "");
Page_inc = 2;
if (Page_inc <= count) {
GetHotel();
Log.e("countttttttt_gg", Page_inc + "");
Page_inc = Page_inc + 1;
Log.e("Page_iceeee", Page_inc + "");
isLoading = false;
} else {
/* Page_inc=1;
GetHotel();*/
}
}
//================================================================================= findviewbyid
private void init() {
hotel_list = (ListView) findViewById(R.id.hotel_list_list_view);
checkIn = (TextView) findViewById(R.id.Enter_date1);
checkout = (TextView) findViewById(R.id.Enter_date2);
number_of_persons_text = (TextView) findViewById(R.id.number_of_persons_text);
number_of_room_text = (TextView) findViewById(R.id.number_of_room_text);
hotel_list_back_image = (LinearLayout) findViewById(R.id.hotel_list_back_image);
number_of_persons_text.setText(mpref.getString("adult", ""));
number_of_room_text.setText(mpref.getString("room", ""));
hotel_list_back_image.setOnClickListener(this);
String date = mpref.getString("checkin", "");
String date_out = mpref.getString("checkout", "");
DateFormat targetFormat = new SimpleDateFormat("MMM dd,yyyy");
DateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd");
Date d = null;
Date dd = null;
try {
d = originalFormat.parse(date);
dd = originalFormat.parse(date_out);
} catch (ParseException e) {
e.printStackTrace();
}
String formattedDate = targetFormat.format(d); // 201208
String formattedDate1 = targetFormat.format(dd); // 201208
Log.e("Change format", formattedDate);
Log.e("Change format", formattedDate1);
checkIn.setText(formattedDate);
checkout.setText(formattedDate1);
}
//========================================================================================hotel name
private void GetHotel() {
String url = "http://api.wego.com/hotels/api/search/show/" + global.getSearch() + "?currency_code=" + mpref.getString("currency_code", "") + "&page=" + Page_inc + "&refresh=true&key=12345&ts_code=123";
Log.e("show", url);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Log.e("Response_____>>", response);
stopAnim();
JSONObject job = null;
try {
job = new JSONObject(response);
String totalcount = job.getString("total_count");
count = Integer.parseInt(job.getString("count"));
String current_page = job.getString("current_page");
JSONArray jo = job.getJSONArray("hotels");
// Log.e("hhhh", "hhhh");
;
for (int i = 0; i < jo.length(); i++) {
JSONObject obj = jo.getJSONObject(i);
HashMap<String, String> hmap = new HashMap<String, String>();
hmap.put("id", obj.getString("id"));
hmap.put("name", obj.getString("name"));
hmap.put("address", obj.getString("address"));
hmap.put("image", obj.getString("image"));
hmap.put("stars", obj.getString("stars"));
//dataItems.add(String.valueOf(hmap));
list.add(hmap);
}
Log.e("dataItemmmmm", list + "");
global.sethoteldetail(list);
// adapter = new Hotel_List_adapter(Hotel_list_activity.this, list);
hotel_list.setAdapter(new Hotel_List_adapter(Hotel_list_activity.this, list));
} catch (JSONException e1) {
e1.printStackTrace();
stopAnim();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Log.e("Response ERROR_____>>", error.toString());
stopAnim();
//pdia.dismiss();
Toast.makeText(Hotel_list_activity.this, "No Internet Connection", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Custom Adapter
public class Hotel_List_adapter extends BaseAdapter {
Context c;
ArrayList<HashMap<String, String>> list;
LayoutInflater inflater;
public Hotel_List_adapter(Context c, ArrayList<HashMap<String, String>> list) {
this.c=c;
this.list=list;
inflater=LayoutInflater.from(c);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder = new Holder();
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_hotel_list,null);
holder.name=(TextView)convertView.findViewById(R.id.name);
holder.address =(TextView)convertView.findViewById(R.id.address);
holder.img=(ImageView) convertView.findViewById(R.id.img);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
holder.name.setText(list.get(position).get("name"));
holder.address.setText(list.get(position).get("address"));
String image_string = list.get(position).get("image");//stars
if (image_string.equalsIgnoreCase("null")){
Log.e("no imG", "NO");
holder.img.setImageResource(R.drawable.no_image);
}
else
{
Glide.with(c).load(image_string).into(holder.img);
}
return convertView;
}
class Holder
{
TextView name, address;
}
}
What do you want? You want to scroll List after update List it reached at Top not at same List State? Is it Right?
Please Check this
private void scrollMyListViewToBottom() {
myListView.post(new Runnable() {
#Override
public void run() {
// Select the last row so it will scroll into view...
myListView.setSelection(myListAdapter.getCount() - 1);
}
});
}
check this Please.

How can I use LoadMore in RecyclerView?

I load some json data from server and I show them in my app.I use RecyclerView.
I want load 10 items for first time and load 10 other items with scroll.
How can I do it?
I am using this tutorial and this point I cant match tutorial to my code
recyclerview load more
Update
this is my code in activity
public class NewsActivity extends AppCompatActivity {
//--------------------------------
private ProgressDialog pDialog;
//----------------------------------
private String urlJsonArray="http://kazeroon.mosbate16.com/news/news.php";
private static String TAG = ListActivity.class.getSimpleName();
static List<News> mNews = new ArrayList<>();
private int page=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//-------------
pDialog = new ProgressDialog(this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
//----------------
if (isOnline()==true) {
makeJsonArrayRequest_News();
}else
Toast.makeText(getApplicationContext(),
"برای دریافت اطلاعات به اینترنت نیاز دارید.",
Toast.LENGTH_LONG).show();
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
private void makeJsonArrayRequest_News() {
showpDialog();
RequestQueue MyRequestQueue = Volley.newRequestQueue(NewsActivity.this);
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, urlJsonArray, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//This code is executed if the server responds, whether or not the response contains data.
//The String 'response' contains the server's response.
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
News news = new News();
JSONObject jsonObj = jsonArray.getJSONObject(i);
String id = jsonObj.getString("id");
String title = jsonObj.getString("title");
String shortcontent = jsonObj.getString("shortcontent");
String longcontent = jsonObj.getString("longcontent");
String publicationdate = jsonObj.getString("publicationdate");
String pic = jsonObj.getString("pic");
String diffdate = jsonObj.getString("diffdate");
String src = jsonObj.getString("src");
String link = jsonObj.getString("link");
news.setId(id);
news.setTitle(title);
news.setShortContent(shortcontent);
news.setLongContent(longcontent);
news.setPublicationDate(publicationdate);
news.setPic(pic);
news.setDiffDate(diffdate);
news.setSrc(src);
news.setLink(link);
mNews.add(news);
}
RecyclerView recyclerViewlist = (RecyclerView) findViewById(R.id.newsList);
//tarif layout maneger baraye tarif noe nemayesh
recyclerViewlist.setLayoutManager(new LinearLayoutManager(NewsActivity.this));
//tarif class adapter recyclview
final RVAdapterNews ad = new RVAdapterNews(NewsActivity.this, mNews, recyclerViewlist);
recyclerViewlist.setAdapter(ad);
ad.setOnLoadMoreListener(new ir.kazeroonsara.kazeroon.OnLoadMoreListener() {
#Override
public void onLoadMore() {
Log.e("haint", "Load More");
mNews.add(null);
ad.notifyItemInserted(mNews.size() - 1);
//Load more data for reyclerview
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Log.e("haint", "Load More 2");
//Remove loading item
mNews.remove(mNews.size() - 1);
ad.notifyItemRemoved(mNews.size());
//Load data
//-----------------------------------------------------------------------------------------------
RequestQueue MyRequestQueue = Volley.newRequestQueue(NewsActivity.this);
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, urlJsonArray, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//This code is executed if the server responds, whether or not the response contains data.
//The String 'response' contains the server's response.
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
News news = new News();
JSONObject jsonObj = jsonArray.getJSONObject(i);
String id = jsonObj.getString("id");
String title = jsonObj.getString("title");
String shortcontent = jsonObj.getString("shortcontent");
String longcontent = jsonObj.getString("longcontent");
String publicationdate = jsonObj.getString("publicationdate");
String pic = jsonObj.getString("pic");
String diffdate = jsonObj.getString("diffdate");
String src = jsonObj.getString("src");
String link = jsonObj.getString("link");
news.setId(id);
news.setTitle(title);
news.setShortContent(shortcontent);
news.setLongContent(longcontent);
news.setPublicationDate(publicationdate);
news.setPic(pic);
news.setDiffDate(diffdate);
news.setSrc(src);
news.setLink(link);
mNews.add(news);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),
"ارتباط با سرور برقرار نشد،آخرین اطلاعات دریافتی نمایش داده می شود",
Toast.LENGTH_LONG).show(); }
hidepDialog();
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
Toast.makeText(getApplicationContext(),
"مشکلی در دریافت اطلاعات وجود دارد",
Toast.LENGTH_LONG).show();
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
page=page+1;
MyData.put("page", String.valueOf(page));
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
//----------------------------------------------------------------------------------------------
ad.notifyDataSetChanged();
ad.setLoaded();
}
}, 5000);
}
});
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),
"ارتباط با سرور برقرار نشد،آخرین اطلاعات دریافتی نمایش داده می شود",
Toast.LENGTH_LONG).show(); }
hidepDialog();
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
Toast.makeText(getApplicationContext(),
"مشکلی در دریافت اطلاعات وجود دارد",
Toast.LENGTH_LONG).show();
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("page", String.valueOf(page));
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
public interface OnLoadMoreListener {
void onLoadMore();
}
}
and this is my code adapter
public class RVAdapterNews extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
//consteraktor ra misazim
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
private OnLoadMoreListener mOnLoadMoreListener;
private boolean isLoading;
private int visibleThreshold = 5;
private int lastVisibleItem, totalItemCount;
private Context context;
private LayoutInflater inflater;
List<News> mNews;
News news=new News();
private RecyclerView mRecyclerViewlist;
public RVAdapterNews(final NewsActivity context, List<News> mNews,RecyclerView recyclerViewlist){
this.context=context;
this.inflater=LayoutInflater.from(context);
this.mNews=mNews;
this.mRecyclerViewlist=recyclerViewlist;
//-------------------------------------------------
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerViewlist.getLayoutManager();
mRecyclerViewlist.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
if (mOnLoadMoreListener != null) {
mOnLoadMoreListener.onLoadMore();
}
isLoading = true;
}
}
});
}
#Override
public int getItemViewType(int position) {
//return super.getItemViewType(position);
return mNews.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
//--------------------------------------------------------MyViewHolder----------------------------------------------
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//bayad aval yek layout besazim - recycler_layout
//layout ro moarefi mikonim
//View v=inflater.inflate(R.layout.rvnews_layout,parent,false);
// vh=new MyViewHolder(v);
//return vh;
if (viewType == VIEW_TYPE_ITEM) {
View view = LayoutInflater.from(context).inflate(R.layout.rvnews_layout, parent, false);
MyViewHolder vh=new MyViewHolder(view);
return vh;
} else if (viewType == VIEW_TYPE_LOADING) {
View view = LayoutInflater.from(context).inflate(R.layout.layout_loading_item, parent, false);
LoadingViewHolder vh2=new LoadingViewHolder(view);
return vh2;
}
return null;
}
//--------------------------------MyViewHolder holder------------------------------------------------------------
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
//itemhaei ke bayad neshan dadeh shavad bayad inja vared shavad
if (holder instanceof MyViewHolder) {
news = mNews.get(position);
final MyViewHolder myViewHolder = (MyViewHolder) holder;
myViewHolder.newsTitle.setText(news.getTitle());
//----------------------
long seconds = Long.parseLong(news.getDiffDate());
//int day = (int) TimeUnit.SECONDS.toDays(seconds);
//long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
//long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
//long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);
long minute = seconds / 60;
long hours = minute / 60;
int day = (int) hours / 24;
int week = day / 7;
int month = day / 30;
int year = day / 365;
if (seconds < 60)
myViewHolder.newsDatePublication.setText(seconds + " ثانیه قبل");
else if (seconds >= 60 && seconds < 3600)
myViewHolder.newsDatePublication.setText(minute + " دقیقه قبل");
else if (seconds >= 3600 && seconds < 86400)
myViewHolder.newsDatePublication.setText(hours + " ساعت قبل");
else if (seconds >= 86400 && seconds < 604800)
myViewHolder.newsDatePublication.setText(day + " روز قبل");
else if (seconds >= 604800 && seconds < 2629743)
myViewHolder.newsDatePublication.setText(week + " هفته قبل");
else if (seconds >= 2629743 && seconds < 31556926)
myViewHolder.newsDatePublication.setText(month + " ماه قبل");
else
myViewHolder.newsDatePublication.setText(year + " سال قبل");
//----------------------
//holder.newsDatePublication.setText(newsPublicationDateItems.get(position));
Uri uri = Uri.parse(news.getPic());
Picasso.with(context).load(uri).resize(200, 200).centerCrop().into(myViewHolder.newsPic, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
myViewHolder.newsPic.setImageResource(R.mipmap.ic_default_list);
}
});
myViewHolder.cvNews.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
News news = mNews.get(position);
Intent intent = new Intent(context, NewsViewActivity.class);
intent.putExtra("id", news.getId());
intent.putExtra("title", news.getTitle());
intent.putExtra("shortContent", news.getShortContent());
intent.putExtra("longContent", news.getLongContent());
intent.putExtra("datePublication", news.getPublicationDate());
intent.putExtra("pic", news.getPic());
intent.putExtra("src", news.getSrc());
intent.putExtra("link", news.getLink());
context.startActivity(intent);
}
});
}else if (holder instanceof LoadingViewHolder) {
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
loadingViewHolder.progressBar.setIndeterminate(true);
}
}
#Override
public int getItemCount() {
//tedad itemhara baraye nemayesh midahim
//return mNews.size();
return mNews == null ? 0 : mNews.size();
}
class LoadingViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
public LoadingViewHolder(View itemView) {
super(itemView);
progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar1);
}
}
class MyViewHolder extends RecyclerView.ViewHolder {
//bayad ajzaye layout ro tarif konim
ImageView newsPic;
TextView newsTitle;
TextView newsShortContent;
TextView newsLongContent;
TextView newsDatePublication;
CardView cvNews;
public MyViewHolder(View itemView) {
super(itemView);
newsPic=(ImageView) itemView.findViewById(R.id.ivNewsPic);
newsTitle= (TextView) itemView.findViewById(R.id.txtNewsTitle);
newsDatePublication = (TextView) itemView.findViewById(R.id.txtNewsDatePublication);
cvNews = (CardView) itemView.findViewById(R.id.CVNews);
}
}
public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
this.mOnLoadMoreListener = mOnLoadMoreListener;
}
public void setLoaded() {
isLoading = false;
}
}
enter image description here
You can follow this website : recyclerview load more
At the and of tutorial you should see a video about working sample
code for activity
public class NewsActivity extends AppCompatActivity {
//--------------------------------
private ProgressDialog pDialog;
//----------------------------------
private String urlJsonArray="http://...../test.php";
private static String TAG = ListActivity.class.getSimpleName();
static List<News> mNews = new ArrayList<>();
private int page=0;
RVAdapterNews ad;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//---------------------------------------
ActionBar mActionBar = getSupportActionBar();
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
LinearLayout actionBarLayout = (LinearLayout)getLayoutInflater().inflate(R.layout.actionbar, null);
TextView actionBarTitleview = (TextView)actionBarLayout.findViewById(R.id.tvTitleActionbar);
//----daryafte lable activity
ActivityInfo activityInfo = null;
try {
activityInfo = getPackageManager().getActivityInfo(
getComponentName(), PackageManager.GET_META_DATA);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
String title = activityInfo.loadLabel(getPackageManager())
.toString();
//-------------------------------------
actionBarTitleview.setText(title);
ActionBar.LayoutParams params = new ActionBar.LayoutParams(
ActionBar.LayoutParams.MATCH_PARENT,
ActionBar.LayoutParams.MATCH_PARENT,
Gravity.RIGHT);
mActionBar.setCustomView(actionBarLayout, params);
mActionBar.setDisplayHomeAsUpEnabled(false);
//------------------------------------------
//-------------
pDialog = new ProgressDialog(this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
//----------------
if (isOnline()==true) {
makeJsonArrayRequest_News();
}else
Toast.makeText(getApplicationContext(),
"برای دریافت اطلاعات به اینترنت نیاز دارید.",
Toast.LENGTH_LONG).show();
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
private void makeJsonArrayRequest_News() {
showpDialog();
RequestQueue MyRequestQueue = Volley.newRequestQueue(NewsActivity.this);
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, urlJsonArray, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//This code is executed if the server responds, whether or not the response contains data.
//The String 'response' contains the server's response.
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
News news = new News();
JSONObject jsonObj = jsonArray.getJSONObject(i);
String id = jsonObj.getString("id");
String title = jsonObj.getString("title");
String shortcontent = jsonObj.getString("shortcontent");
String longcontent = jsonObj.getString("longcontent");
String publicationdate = jsonObj.getString("publicationdate");
String pic = jsonObj.getString("pic");
String diffdate = jsonObj.getString("diffdate");
String src = jsonObj.getString("src");
String link = jsonObj.getString("link");
news.setId(id);
news.setTitle(title);
news.setShortContent(shortcontent);
news.setLongContent(longcontent);
news.setPublicationDate(publicationdate);
news.setPic(pic);
news.setDiffDate(diffdate);
news.setSrc(src);
news.setLink(link);
mNews.add(news);
}
RecyclerView recyclerViewlist = (RecyclerView) findViewById(R.id.newsList);
//tarif layout maneger baraye tarif noe nemayesh
recyclerViewlist.setLayoutManager(new LinearLayoutManager(NewsActivity.this));
//tarif class adapter recyclview
ad = new RVAdapterNews(NewsActivity.this, mNews, recyclerViewlist);
recyclerViewlist.setAdapter(ad);
ad.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
Log.e("haint", "Load More");
mNews.add(null);
ad.notifyItemInserted(mNews.size() - 1);
//Load more data for reyclerview
Log.e("haint", "Load More 2");
//Remove loading item
//mNews.remove(mNews.size() - 1);
//ad.notifyItemRemoved(mNews.size());
//ad.notifyDataSetChanged();
//Load data
//-----------------------------------------------------------------------------------------------
RequestQueue MyRequestQueue = Volley.newRequestQueue(NewsActivity.this);
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, urlJsonArray, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//This code is executed if the server responds, whether or not the response contains data.
//The String 'response' contains the server's response.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
}
},3000);
Toast.makeText(getApplicationContext(), "بارگزاری اخبار بیشتر انجام شد", Toast.LENGTH_SHORT).show();
//Remove loading item
mNews.remove(mNews.size() - 1);
ad.notifyItemRemoved(mNews.size());
//ad.notifyDataSetChanged();
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
News news = new News();
JSONObject jsonObj = jsonArray.getJSONObject(i);
String id = jsonObj.getString("id");
String title = jsonObj.getString("title");
String shortcontent = jsonObj.getString("shortcontent");
String longcontent = jsonObj.getString("longcontent");
String publicationdate = jsonObj.getString("publicationdate");
String pic = jsonObj.getString("pic");
String diffdate = jsonObj.getString("diffdate");
String src = jsonObj.getString("src");
String link = jsonObj.getString("link");
news.setId(id);
news.setTitle(title);
news.setShortContent(shortcontent);
news.setLongContent(longcontent);
news.setPublicationDate(publicationdate);
news.setPic(pic);
news.setDiffDate(diffdate);
news.setSrc(src);
news.setLink(link);
mNews.add(news);
}
ad.setLoaded();
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),
"ارتباط با سرور برقرار نشد،آخرین اطلاعات دریافتی نمایش داده می شود",
Toast.LENGTH_LONG).show(); }
hidepDialog();
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
Toast.makeText(getApplicationContext(),
"مشکلی در دریافت اطلاعات وجود دارد",
Toast.LENGTH_LONG).show();
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
page=page+1;
MyData.put("page", String.valueOf(page));
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
ad.notifyDataSetChanged();
// ad.setLoaded();
}
});
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),
"ارتباط با سرور برقرار نشد،آخرین اطلاعات دریافتی نمایش داده می شود",
Toast.LENGTH_LONG).show(); }
hidepDialog();
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
Toast.makeText(getApplicationContext(),
"مشکلی در دریافت اطلاعات وجود دارد",
Toast.LENGTH_LONG).show();
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("page", String.valueOf(page));
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
code for adapter
public class RVAdapterNews extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
//consteraktor ra misazim
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
private OnLoadMoreListener mOnLoadMoreListener;
private boolean isLoading;
private int visibleThreshold = 5;
private int lastVisibleItem, totalItemCount;
private Context context;
private LayoutInflater inflater;
List<News> mNews;
News news=new News();
private RecyclerView mRecyclerViewlist;
public RVAdapterNews(final NewsActivity context, List<News> mNews,RecyclerView recyclerViewlist){
this.context=context;
this.inflater=LayoutInflater.from(context);
this.mNews=mNews;
this.mRecyclerViewlist=recyclerViewlist;
//-------------------------------------------------
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerViewlist.getLayoutManager();
mRecyclerViewlist.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
if (mOnLoadMoreListener != null) {
mOnLoadMoreListener.onLoadMore();
}
isLoading = true;
}
}
});
}
#Override
public int getItemViewType(int position) {
//return super.getItemViewType(position);
return mNews.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//bayad aval yek layout besazim - recycler_layout
//layout ro moarefi mikonim
//View v=inflater.inflate(R.layout.rvnews_layout,parent,false);
// vh=new MyViewHolder(v);
//return vh;
if (viewType == VIEW_TYPE_ITEM) {
View view = LayoutInflater.from(context).inflate(R.layout.rvnews_layout, parent, false);
MyViewHolder vh=new MyViewHolder(view);
return vh;
} else if (viewType == VIEW_TYPE_LOADING) {
View view = LayoutInflater.from(context).inflate(R.layout.layout_loading_item, parent, false);
LoadingViewHolder vh2=new LoadingViewHolder(view);
return vh2;
}
return null;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
//itemhaei ke bayad neshan dadeh shavad bayad inja vared shavad
if (holder instanceof MyViewHolder) {
news = mNews.get(position);
final MyViewHolder myViewHolder = (MyViewHolder) holder;
myViewHolder.newsTitle.setText(news.getTitle());
//----------------------
long seconds = Long.parseLong(news.getDiffDate());
//int day = (int) TimeUnit.SECONDS.toDays(seconds);
//long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
//long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
//long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);
long minute = seconds / 60;
long hours = minute / 60;
int day = (int) hours / 24;
int week = day / 7;
int month = day / 30;
int year = day / 365;
if (seconds < 60)
myViewHolder.newsDatePublication.setText(seconds + " ثانیه قبل");
else if (seconds >= 60 && seconds < 3600)
myViewHolder.newsDatePublication.setText(minute + " دقیقه قبل");
else if (seconds >= 3600 && seconds < 86400)
myViewHolder.newsDatePublication.setText(hours + " ساعت قبل");
else if (seconds >= 86400 && seconds < 604800)
myViewHolder.newsDatePublication.setText(day + " روز قبل");
else if (seconds >= 604800 && seconds < 2629743)
myViewHolder.newsDatePublication.setText(week + " هفته قبل");
else if (seconds >= 2629743 && seconds < 31556926)
myViewHolder.newsDatePublication.setText(month + " ماه قبل");
else
myViewHolder.newsDatePublication.setText(year + " سال قبل");
//----------------------
//holder.newsDatePublication.setText(newsPublicationDateItems.get(position));
Uri uri = Uri.parse(news.getPic());
Picasso.with(context).load(uri).resize(200, 200).centerCrop().into(myViewHolder.newsPic, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
myViewHolder.newsPic.setImageResource(R.mipmap.ic_default_list);
}
});
myViewHolder.cvNews.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
News news = mNews.get(position);
Intent intent = new Intent(context, NewsViewActivity.class);
intent.putExtra("id", news.getId());
intent.putExtra("title", news.getTitle());
intent.putExtra("shortContent", news.getShortContent());
intent.putExtra("longContent", news.getLongContent());
intent.putExtra("datePublication", news.getPublicationDate());
intent.putExtra("pic", news.getPic());
intent.putExtra("src", news.getSrc());
intent.putExtra("link", news.getLink());
context.startActivity(intent);
}
});
}else if (holder instanceof LoadingViewHolder) {
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
loadingViewHolder.progressBar.setIndeterminate(true);
}
}
#Override
public int getItemCount() {
//tedad itemhara baraye nemayesh midahim
//return mNews.size();
return mNews == null ? 0 : mNews.size();
}
class LoadingViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
public LoadingViewHolder(View itemView) {
super(itemView);
progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar1);
}
}
class MyViewHolder extends RecyclerView.ViewHolder {
//bayad ajzaye layout ro tarif konim
ImageView newsPic;
TextView newsTitle;
TextView newsShortContent;
TextView newsLongContent;
TextView newsDatePublication;
CardView cvNews;
public MyViewHolder(View itemView) {
super(itemView);
newsPic=(ImageView) itemView.findViewById(R.id.ivNewsPic);
newsTitle= (TextView) itemView.findViewById(R.id.txtNewsTitle);
newsDatePublication = (TextView) itemView.findViewById(R.id.txtNewsDatePublication);
cvNews = (CardView) itemView.findViewById(R.id.CVNews);
}
}
public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
this.mOnLoadMoreListener = mOnLoadMoreListener;
}
public void setLoaded() {
isLoading = false;
}
}
JsonArrayRequest req = new JsonArrayRequest(urlJsonArray,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
for (int i = 0; i < response.length(); i++) {
News news = new News();
JSONObject person = (JSONObject) response.get(i);
String id = person.getString("id");
String title = person.getString("title");
String shortcontent = person.getString("shortcontent");
String longcontent = person.getString("longcontent");
String publicationdate = person.getString("publicationdate");
String pic = person.getString("pic");
String diffdate=person.getString("diffdate");
String src=person.getString("src");
String link=person.getString("link");
news.setId(id);
news.setTitle(title);
news.setShortContent(shortcontent);
news.setLongContent(longcontent);
news.setPublicationDate(publicationdate);
news.setPic(pic);
news.setDiffDate(diffdate);
news.setSrc(src);
news.setLongContent(link);
mNews.add(news);
}
RecyclerView recyclerViewlist=(RecyclerView) findViewById(R.id.newsList);
//tarif class adapter recyclview
RVAdapterNews ad=null;
if(ad==null)
{
ad=new RVAdapterNews(NewsActivity.this,mNews);
recyclerViewlist.setAdapter(ad);
//tarif layout maneger baraye tarif noe nemayesh
recyclerViewlist.setLayoutManager(new LinearLayoutManager(NewsActivity.this));
}
else
{
ad.Add(mActivity, mNews);
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"error"`enter code here`,
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
//Toast.makeText(getApplicationContext(),
// error.getMessage(), Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),
"error",
Toast.LENGTH_LONG).show();
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
.
.
IN Adapter make a method Add like below
private ArrayList<News> newsall;
public RVAdapterNews(Activity mActivity, ArrayList<News> news) {
this.mActivity = mActivity;
newsall.addAll(news);
notifyDataSetChanged();
}

Categories

Resources