Recycler view swaps items when i scroll them - android

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

Related

RecyleView showing all items duplicates

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.

Recylerview items that are visible are not getting updated when notifyDataSetChanged() is called

I am having a recycler view whose vies of the items that are visible are not getting updated, when notifyDataSetChanged() is called. The items that are invisible are getting updated without any problem.
I have seen that this has been a problem with listview as given here:
List view not refreshing already visible items
But I am not knowing what to do with recycler view.
In my recycler view adapter I add views dynamically according to my code.
Here is my code:
public class Nearby_Viewpager_Stops extends Fragment {
private final String TAG = "Nearby Stops";
View mRootview = null;
RecyclerView mRecyclerView;
MKLoader mProgressBar;
Context mContext;
TextView mNoStopsTV;
Nearby_Stops_Adapter mStops_adapter;
List<BusArrivalPOJO> mBusArrivalPOJOList = new ArrayList<>();
List<List<BusArrivalPOJO>> mBusArrivalDetailsPOJOList = new ArrayList<>();
LinearLayoutManager mLayoutManager;
Handler mHandler;
Handler mHandlerForOnStop;
boolean resumed = true;
private static final int REFRESH_TIME = 30;
int lengthOfStopsList;
boolean isNoStops_available_nearby = false;
boolean isFirstTimeCalled;
boolean isRunningFirstTime;
#Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
if (mRootview == null) {
mRootview = inflater.inflate(R.layout.nearby_viewpager_stops, container, false);
mRecyclerView = (RecyclerView) mRootview.findViewById(R.id.recycler_view);
mProgressBar = (MKLoader) mRootview.findViewById(R.id.progressBar);
mNoStopsTV = (TextView) mRootview.findViewById(R.id.no_nearby_stops_text);
}
mLayoutManager = new LinearLayoutManager(mContext);
mRecyclerView.setLayoutManager(mLayoutManager);
mStops_adapter = new Nearby_Stops_Adapter(mBusArrivalPOJOList, mBusArrivalDetailsPOJOList);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setAdapter(mStops_adapter);
return mRootview;
}
private class GetNearbyStops extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
isNoStops_available_nearby = false;
mProgressBar.setVisibility(View.VISIBLE);
mBusArrivalPOJOList.clear();
pos = mLayoutManager.findFirstVisibleItemPosition();
mStops_adapter.notifyDataSetChanged();
}
#Override
protected Void doInBackground(Void... voids) {
String urlString = "https://api.tfl.gov.uk/StopPoint?radius=2000&stopTypes=NaptanRailStation,NaptanBusCoachStation,NaptanFerryPort,NaptanPublicBusCoachTram&useStopPointHierarchy=true" +
"&modes=bus&lat="+ Constants.latitude+"&lon="+Constants.longitude+"&categories=facility&app_id=" + Constants.app_id_tfl + "&app_key=" + Constants.app_key_tfl;
Log.v(TAG, urlString);
HttpURLConnection urlConnection = null;
BufferedReader bufferedReader;
String line;
InputStream inputStream;
StringBuilder json_result = new StringBuilder();
try {
System.setProperty("http.keepAlive", "false");
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(2000);
urlConnection.setConnectTimeout(2000);
urlConnection.setRequestMethod("GET");
inputStream = new BufferedInputStream(urlConnection.getInputStream());
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while ((line = bufferedReader.readLine()) != null) {
json_result.append(line);
}
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage());
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
getDataFromJSON(json_result.toString());
return null;
}
private void getDataFromJSON(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray stopPoints = jsonObject.getJSONArray("stopPoints");
if (stopPoints.length() <= 20 && stopPoints.length() != 0) {
lengthOfStopsList = stopPoints.length();
} else if (stopPoints.length() == 0) {
lengthOfStopsList = 0;
isNoStops_available_nearby = true;
}
for (int i = 0; i< lengthOfStopsList; i++) {
JSONObject jsonObject1 = stopPoints.getJSONObject(i);
int distance = Math.round(jsonObject1.getInt("distance")/60);
Double lat = jsonObject1.getDouble("lat");
Double lon = jsonObject1.getDouble("lon");
String commonName = jsonObject1.getString("commonName");
JSONArray lineGroup = jsonObject1.getJSONArray("lineGroup");
new GetBusArrivals().execute(lineGroup, new LatLng(lat, lon), distance);
String naptanID;
for (int j=0; j< lineGroup.length(); j++) {
JSONObject jsonObject2 = lineGroup.getJSONObject(j);
if (jsonObject2.has("naptanIdReference")) {
naptanID = jsonObject2.getString("naptanIdReference");
BusArrivalPOJO busArrivalPOJO = new
BusArrivalPOJO(commonName, distance, new LatLng(lat, lon), naptanID);
mBusArrivalPOJOList.add(busArrivalPOJO);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
mStops_adapter.notifyDataSetChanged();
}
});
}
}
}
} catch (JSONException e) {
Log.e(TAG, e.getLocalizedMessage());
if (getActivity()!=null)
getActivity().runOnUiThread(new Runnable() {
public void run() {
new GetNearbyStops().execute();
}
});
}
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (isNoStops_available_nearby) {
mProgressBar.setVisibility(View.GONE);
mNoStopsTV.setVisibility(View.VISIBLE);
} else {
mProgressBar.setVisibility(View.VISIBLE);
mNoStopsTV.setVisibility(View.GONE);
}
}
}
int pos;
private class GetBusArrivals extends AsyncTask<Object, Void, Void> {
/**
* It represents the position of the first visible position of recycler view
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
if (isFirstTimeCalled) {
if (getActivity() != null)
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
mBusArrivalDetailsPOJOList.clear();
mStops_adapter.notifyDataSetChanged();
}
});
isFirstTimeCalled = false;
}
}
LatLng latLng;
String stopID;
int distance;
#Override
protected Void doInBackground(Object... strings) {
JSONArray lineGroup = (JSONArray) strings[0];
latLng = (LatLng) strings[1];
distance = (int) strings[2];
try {
for (int j=0; j< lineGroup.length(); j++) {
JSONObject jsonObject2 = lineGroup.getJSONObject(j);
if (jsonObject2.has("naptanIdReference")) {
stopID = jsonObject2.getString("naptanIdReference");
String urlString = "https://api.tfl.gov.uk/StopPoint/"+stopID+"/Arrivals?app_id="
+ Constants.app_id_tfl + "&app_key=" + Constants.app_key_tfl;
HttpURLConnection urlConnection = null;
BufferedReader bufferedReader;
String line;
InputStream inputStream;
StringBuilder json_result = new StringBuilder();
try {
Log.v(TAG, urlString);
System.setProperty("http.keepAlive", "false");
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(2000);
urlConnection.setConnectTimeout(2000);
urlConnection.setRequestMethod("GET");
inputStream = new BufferedInputStream(urlConnection.getInputStream());
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while ((line = bufferedReader.readLine()) != null) {
json_result.append(line);
}
List<BusArrivalPOJO> busArrivalPOJOs = getDataFromJSON(json_result.toString(), latLng, distance);
if (busArrivalPOJOs != null) {
mBusArrivalDetailsPOJOList.add(busArrivalPOJOs);
Log.v("length", "leng"+mBusArrivalDetailsPOJOList.size());
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if (mProgressBar.getVisibility() == View.VISIBLE)
mProgressBar.setVisibility(View.GONE);
if (mBusArrivalDetailsPOJOList.size() < 5) {
mRecyclerView.setAdapter(mStops_adapter);
} else
mStops_adapter.notifyDataSetChanged();
}
});
}
}
} catch (Exception e) {
j= j-1;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
}
} catch (JSONException e) {
Log.e(TAG, e.getLocalizedMessage());
}
return null;
}
private List<BusArrivalPOJO> getDataFromJSON(String json, LatLng latLng, int distance) {
List<BusArrivalPOJO> busArrivalPOJOList = new ArrayList<>();
try {
Log.v(TAG, json);
JSONArray jsonArray = new JSONArray(json);
for (int i=0; i< jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if (jsonObject.has("exceptionType") && jsonObject.getString("exceptionType").contentEquals("EntityNotFoundException")) {
return null;
} else {
String lineName = jsonObject.getString("lineName");
String platformName = jsonObject.getString("platformName");
String destinationName = jsonObject.getString("destinationName");
int timeToArrivalToStation = jsonObject.getInt("timeToStation");
String stationName = jsonObject.getString("stationName");
String naptanId = jsonObject.getString("naptanId");
BusArrivalPOJO busArrivalPOJO = new BusArrivalPOJO(lineName, platformName, destinationName,
timeToArrivalToStation, stationName, latLng, distance, naptanId);
busArrivalPOJOList.add(busArrivalPOJO);
}
}
} catch (JSONException e) {
Log.e(TAG, e.getLocalizedMessage());
}
return busArrivalPOJOList;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (pos< mBusArrivalPOJOList.size()-5 && mBusArrivalPOJOList.size()-5 == mBusArrivalDetailsPOJOList.size()
|| mBusArrivalDetailsPOJOList.size() == mBusArrivalPOJOList.size()) {
}
if (MainActivity.menuItem != null && MainActivity.menuItem.getActionView() != null) {
MainActivity.menuItem.getActionView().clearAnimation();
MainActivity.menuItem.setActionView(null);
}
}
}
#Override
public void onResume() {
super.onResume();
mHandler = new Handler();
resumed = true;
isRunningFirstTime = true;
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
isFirstTimeCalled = true;
new GetNearbyStops().execute();
mHandler.postDelayed(this, REFRESH_TIME * 1000);
}
}, 1000);
}
}
Here is the code for my recycler view adapter:
class Nearby_Stops_Adapter extends RecyclerView.Adapter {
private List<List<BusArrivalPOJO>> mBusArrivalPOJOListFullDetails = new ArrayList<>();
private List<BusArrivalPOJO> mBusArrivalPOJOList = new ArrayList<>();
Context mContext;
private LinearLayout mLinearLayout;
private static HashSet<String> isRemainingTimesOpen = new HashSet<>();
private final String TAG = "NearbyStopsAda";
Nearby_Stops_Adapter(List<BusArrivalPOJO> busArrivalPOJOList,List<List<BusArrivalPOJO>> busArrivalPOJOList1 ) {
mBusArrivalPOJOList = busArrivalPOJOList;
mBusArrivalPOJOListFullDetails = busArrivalPOJOList1;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rootView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.nearby_stops_adapter,parent,false);
mContext = parent.getContext();
mLinearLayout = (LinearLayout) rootView.findViewById(R.id.linear_layout);
TextView mStationName = (TextView) rootView.findViewById(R.id.stationName);
mStationName.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL));
MKLoader progressBar = (MKLoader) rootView.findViewById(R.id.progressBar);
TextView timeToWalkToStation = (TextView) rootView.findViewById(R.id.timeToTravel);
CardView cardView = (CardView) rootView.findViewById(R.id.cardView);
return new Nearby_Stops_Adapter.ViewHolder(rootView, mStationName, timeToWalkToStation, cardView, progressBar);
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
if (mBusArrivalPOJOList.size() > 0) {
((ViewHolder) holder).stationNameTV.setText(mBusArrivalPOJOList.get(position).getStationName());
String time = mBusArrivalPOJOList.get(position).getTimeToWalkToStation() + " min";
((ViewHolder) holder).timeToWalkToStation.setText(time);
}
if (mBusArrivalPOJOListFullDetails.size()>0) {
mLinearLayout.removeAllViews();
for (int a=0; a< mBusArrivalPOJOListFullDetails.size() ;a++) {
if (mBusArrivalPOJOList.get(position).getStationID()
.contentEquals(mBusArrivalPOJOListFullDetails.get(a).get(0).getStationID())) {
if (!mBusArrivalPOJOListFullDetails.get(a).get(0).getPlatformName().contentEquals("null"))
if (!((ViewHolder) holder).stationNameTV.getText().toString().contains("::"))
((ViewHolder) holder).stationNameTV.append(" :: "+mBusArrivalPOJOListFullDetails.get(a).get(0).getPlatformName());
for (int j=0; j< mBusArrivalPOJOListFullDetails.get(a).size() ;j++) {
Collections.sort(mBusArrivalPOJOListFullDetails.get(a), new Comparator<BusArrivalPOJO>() {
#Override
public int compare(BusArrivalPOJO busArrivalPOJO, BusArrivalPOJO t1) {
return busArrivalPOJO.getTimeToArrival() - t1.getTimeToArrival();
}
});
}
Set<String> uniqueBusNamesSet = new HashSet<>();
for (int m = 0; m< mBusArrivalPOJOListFullDetails.get(a).size() ;m++) {
uniqueBusNamesSet.add(mBusArrivalPOJOListFullDetails.get(a).get(m).getBusName());
}
ArrayList<Multimap<String, Integer>> allBusesForParticularStation = new ArrayList<>();
for (String key: uniqueBusNamesSet) {
Multimap<String, Integer> busWithTimes = ArrayListMultimap.create();
for (int s=0; s< mBusArrivalPOJOListFullDetails.get(a).size() ;s++) {
if (key.contentEquals(mBusArrivalPOJOListFullDetails.get(a).get(s).getBusName())) {
busWithTimes.put(key +"::"+ mBusArrivalPOJOListFullDetails.get(a).get(s).getDestinationName()
, mBusArrivalPOJOListFullDetails.get(a).get(s).getTimeToArrival());
}
}
allBusesForParticularStation.add(busWithTimes);
}
((ViewHolder) holder).progressBar.setVisibility(View.GONE);
for (int t=0 ; t< allBusesForParticularStation.size() ;t++) {
Multimap<String, Integer> map = allBusesForParticularStation.get(t);
for (String key: map.keySet()) {
List<Integer> values = new ArrayList<>(map.get(key));
RelativeLayout relativeLayout = new RelativeLayout(mContext);
relativeLayout.setPadding(16, 16, 16, 16);
LinearLayout linearLayoutForBusName = new LinearLayout(mContext);
linearLayoutForBusName.setOrientation(LinearLayout.VERTICAL);
final TextView busNameTV = new TextView(mContext);
busNameTV.setText(key.split("::")[0]);
busNameTV.setTypeface(Typeface.create("sans-serif-normal", Typeface.NORMAL));
busNameTV.setTextColor(ContextCompat.getColor(mContext,R.color.colorTextPrimary));
final TextView destinationNameTV = new TextView(mContext);
destinationNameTV.setText(key.split("::")[1]);
destinationNameTV.setTextSize(12);
destinationNameTV.setTextColor(ContextCompat.getColor(mContext,R.color.colorTextSecondary));
linearLayoutForBusName.addView(busNameTV);
linearLayoutForBusName.addView(destinationNameTV);
LinearLayout linearLayoutForTimes = new LinearLayout(mContext);
linearLayoutForTimes.setOrientation(LinearLayout.VERTICAL);
RelativeLayout timeRelativeLayout = new RelativeLayout(mContext);
timeRelativeLayout.setId(R.id.time_relativeLayout_id);
LinearLayout timeArrowLinearLayout = new LinearLayout(mContext);
timeArrowLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
timeArrowLinearLayout.setId(R.id.time_id);
timeArrowLinearLayout.setGravity(Gravity.CENTER_VERTICAL);
timeArrowLinearLayout.setPadding(6,6,6,6);
RelativeLayout.LayoutParams timeArrowLP = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
timeArrowLP.addRule(RelativeLayout.RIGHT_OF, R.id.time_tv);
timeArrowLP.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
timeArrowLinearLayout.setLayoutParams(timeArrowLP);
//Recent Time text view
TextView timeTV = new TextView(mContext);
int timeSec = values.get(0);
int timeInMin = Math.round(timeSec / 60);
if (timeInMin == 0) {
String timeText = "due";
timeTV.setText(timeText);
} else {
String timeInMinText = timeInMin + " min";
timeTV.setText(timeInMinText);
}
timeTV.setTextColor(ContextCompat.getColor(mContext, R.color.textColorAccent));
timeTV.setPadding(0,0,16,0);
final TextView remainingTimesTV = new TextView(mContext);
remainingTimesTV.setTextColor(ContextCompat.getColor(mContext, R.color.colorTextSecondary));
remainingTimesTV.setTextSize(11);
remainingTimesTV.setVisibility(View.GONE);
for (int l=1; l< values.size() && l < 4; l++) {
String tempTime;
if (l == 3 || l == values.size() - 1) {
tempTime = values.get(l) / 60 + " min";
}
else
tempTime = values.get(l)/60 + " min, ";
remainingTimesTV.append(tempTime);
}
RelativeLayout.LayoutParams remainingTimeLayoutParams = new RelativeLayout.LayoutParams
(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
remainingTimeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
remainingTimeLayoutParams.addRule(RelativeLayout.BELOW, R.id.time_id);
remainingTimesTV.setLayoutParams(remainingTimeLayoutParams);
timeArrowLinearLayout.addView(timeTV);
if (values.size() > 1) {
//Down arrow button
final ImageView imageButton = new ImageView(mContext);
imageButton.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.arrow_down));
if (isRemainingTimesOpen != null) {
for (String openedRowKey : isRemainingTimesOpen) {
if (openedRowKey.contains(busNameTV.getText().toString()) &&
openedRowKey.contains(destinationNameTV.getText().toString()) &&
openedRowKey.contains(((ViewHolder) holder).stationNameTV.getText().toString())) {
remainingTimesTV.setVisibility(View.VISIBLE);
imageButton.setImageResource(R.drawable.arrow_top);
}
}
}
timeArrowLinearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (remainingTimesTV.getVisibility() == View.GONE) {
isRemainingTimesOpen.add(busNameTV.getText().toString()
+destinationNameTV.getText().toString()
+(((ViewHolder) holder).stationNameTV.getText().toString()));
remainingTimesTV.setVisibility(View.VISIBLE);
imageButton.setImageResource(R.drawable.arrow_down);
imageButton.animate().rotation(180).start();
} else {
remainingTimesTV.setVisibility(View.GONE);
imageButton.setImageResource(R.drawable.arrow_top);
imageButton.animate().rotation(-180).start();
}
}
});
timeArrowLinearLayout.addView(imageButton);
}
RelativeLayout.LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layoutParams2.addRule(RelativeLayout.CENTER_VERTICAL);
timeRelativeLayout.setLayoutParams(layoutParams2);
timeRelativeLayout.addView(timeArrowLinearLayout);
timeRelativeLayout.addView(remainingTimesTV);
View horLine = new View(mContext);
RelativeLayout.LayoutParams layoutParams3 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
1);
horLine.setLayoutParams(layoutParams3);
horLine.setBackgroundColor(ContextCompat.getColor(mContext, R.color.horizontal_line));
horLine.setPadding(0,5,0,5);
relativeLayout.addView(linearLayoutForBusName);
relativeLayout.addView(timeRelativeLayout);
((ViewHolder) holder).cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
mLinearLayout.addView(relativeLayout);
if (t < uniqueBusNamesSet.size()-1) {
mLinearLayout.addView(horLine);
}
}
}
}
}
}
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemCount() {
return mBusArrivalPOJOList.size();
}
private class ViewHolder extends RecyclerView.ViewHolder {
TextView stationNameTV;
TextView timeToWalkToStation;
CardView cardView;
MKLoader progressBar;
ViewHolder(View view, TextView stationNameTV, TextView timeToWalkToStation, CardView cardView,
MKLoader progressBar) {
super(view);
this.stationNameTV = stationNameTV;
this.timeToWalkToStation = timeToWalkToStation;
this.cardView = cardView;
this.progressBar = progressBar;
}
}
}
You are adjusting the UI in the background.
Use the method onPostExecute() from AsyncTask to adjust your UI.
In this code, you are not invoking notifyDataSetChanged() when adding items to mBusArrivalPOJOList (for example, check getDataFromJson() for GetNearbyStops class) or I am not able to find where you are invoking it. Please make sure that you are invoking notifyDataSetChanged() immediately after changing the objects you send to adapter be it adding (one item, multiple items) or removing (one item or multiple items) or clearing.

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 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();
}

Not getting the correct data on clicking the LISTVIEW

I have 3 list in my fragment i.e. list 1,list2 and list3. And all are interdependent.I'm using AsyncTask for showing these list.
When i click on list 1 its shows some data on list 3 and so on when i clik on list 2 it shows data on list3.
Now the problem is there is a next button,if i don't click on list 2 and press next it does not show the correct data.
list 2 returns null and thus does not functional correct.
Below is the code
public class Browse extends Fragment {
ActionBar actionBar;
ListView listView1, listView2, listView3;
ArrayList<String> englishList = new ArrayList<String>();
ArrayList<String> hindiList = new ArrayList<String>();
ArrayList<String> alist1 = new ArrayList<String>();
ArrayList<String> alist2 = new ArrayList<String>();
String response, reply;
TextView tv2;
Browse_Adapter ListAdapter, ListAdapter1;
Browse_Adapter2 adpter2;
LinearLayout linera_t_Layout_1;
boolean result = false;
TextView prev, next;
int pageno = 0, epp;
String txt;
protected String resourceType;
String s;
Context context;
File dbFile1_,dbFile2_,dbFile;
ProgressDialog loadingDialog;
public String DB1 = "sk1.db";
public String DB2 = "sk2.db";
String global,list1_global="a";
Boolean list_flag;
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.browse, container, false);
actionBar=getActivity().getActionBar();
MainActivity.state="browse";
context=getActivity().getBaseContext();
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US")) {
actionBar.setTitle(getResources().getString(R.string.browse_en));
} else {
actionBar.setTitle(getResources().getString(R.string.browse_hi));
}
/* PREVIOUS AND NEXT TEXTVIEWS CLICKLISTENERS */
prev = (TextView) rootView.findViewById(R.id.prev);
next = (TextView) rootView.findViewById(R.id.next);
// listView 1
listView1 = (ListView) rootView.findViewById(R.id.listView1);
// listView 2
listView2 = (ListView) rootView.findViewById(R.id.listView2);
// listView 3
listView3 = (ListView) rootView.findViewById(R.id.listView3);
listView1.setChoiceMode(1);
listView2.setChoiceMode(1);
listView3.setChoiceMode(1);
View view = inflater.inflate(R.layout.browse, null);
resourceType = (String) view.getTag();
if (resourceType.equals("large")) {
epp = 25;
} else if (resourceType.equals("normal"))
{
epp = 17;
} else if (resourceType.equals("small"))
{
epp = 12;
}
if (!InternetConnection.isInternetOn(context))
{
s= Environment.getExternalStorageDirectory() .toString();
dbFile1_ = new File(s,"sk1.db");
if(!filter.accept(dbFile1_)){
final AlertDialog.Builder alertbox = new AlertDialog.Builder(getActivity());
alertbox.setTitle("Shabdkosh Dictionary");
alertbox.setMessage("Internet connection is not available.");
alertbox.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
}
});
alertbox.show();
}
else{
listView1.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
final TextView textView = (TextView) view
.findViewById(R.id.text);
if (alist1.size() > 0) {
alist1.clear();
}
if (alist2.size() > 0) {
alist2.clear();
}
prev.setVisibility(View.GONE);
pageno = 0;
textView.setBackgroundColor(getResources().getColor(R.color.text_color));
int DELAY = 200;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
textView.setBackgroundColor(getResources().getColor(
R.color.White));
}
}, DELAY);
txt = textView.getText().toString();
list_flag=true;
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US")) {
new brs(getActivity()).execute();
//new brs_wd(getActivity(),pageno,list1_global).execute();
} else {
new brs(getActivity()).execute();
//new brs_wd(getActivity(),pageno,list1_global).execute();
}
}
});
}
}
else{
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
final TextView textView = (TextView) view
.findViewById(R.id.text);
if (alist1.size() > 0) {
alist1.clear();
}
if (alist2.size() > 0) {
alist2.clear();
}
prev.setVisibility(View.GONE);
pageno = 0;
textView.setBackgroundColor(getResources().getColor(R.color.text_color));
int DELAY = 200;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
textView.setBackgroundColor(getResources().getColor(
R.color.White));
}
}, DELAY);
txt = textView.getText().toString();
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US")) {
list_flag=true;//
new brs(getActivity()).execute();
} else {
new brs(getActivity()).execute();
}
}
});
}
prev.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
list_flag=false;
prev.setTextColor((getResources().getColor(R.color.more_changed)));
int DELAY = 200;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
prev.setTextColor((getResources().getColor(R.color.text_color)));
}
}, DELAY);
if (alist2.size() > 0) {
alist2.clear();
}
if (pageno > 0) {
pageno = pageno - 1;
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US")) {
new brs_wd(getActivity(),pageno,global).execute();
} else {
new brs_wd(getActivity(),pageno,global).execute();
}
}
else {
prev.setVisibility(View.GONE);
}
}
});
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
list_flag=false;//
next.setTextColor((getResources().getColor(R.color.more_changed)));
int DELAY = 200;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
next.setTextColor((getResources().getColor(R.color.text_color)));
}
}, DELAY);
prev.setVisibility(View.VISIBLE);
prev.setText("<<Prev");
if (alist2.size() > 0) {
alist2.clear();
}
pageno = pageno + 1;
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US")) {
new brs_wd(getActivity(),pageno,global).execute();
} else {
new brs_wd(getActivity(),pageno,global).execute();
}
}
});
englishList.addAll(Arrays.asList("A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
"T", "U", "V", "W", "X", "Y", "Z"));
hindiList.addAll(Arrays.asList("अ", "आ", "इ", "ई", "उ", "ऊ", "à¤", "à¤",
"ओ", "औ", "अà¤", "आà¤", "ऋ", "क", "ख", "ग", "घ", "ङ", "च", "छ",
"ज", "à¤", "ञ", "ट", "ठ", "ड", "ढ", "ण", "त", "थ", "द", "ध",
"न", "प", "फ", "ब", "भ", "म", "य", "र", "ल", "व", "श", "ष",
"स", "ह", "कà¥à¤·" , "तà¥à¤°","जà¥à¤ž"));
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US"))
{try{
Browse_Adapter listAdapter1 = new Browse_Adapter(context,
R.layout.browse_list_item, englishList);
if(listAdapter1!=null)
listView1.setAdapter(listAdapter1);}
catch(Exception e){e.printStackTrace();}
} else {
Browse_Adapter listAdapter1 = new Browse_Adapter(context,
R.layout.browse_list_item, hindiList);
if(listAdapter1!=null)
listView1.setAdapter(listAdapter1);
}
listView2.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos,long id)
{
String item = (String)parent.getItemAtPosition(pos);
global=item;
if (alist2.size() > 0)
{
alist2.clear();
}
pageno = 0;
final TextView textView = (TextView) view
.findViewById(R.id.text_browsword);
textView.setTextColor(getResources().getColor(
R.color.text_color));
int DELAY = 200;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
textView.setTextColor(getResources().getColor(
R.color.White));
}
}, DELAY);
//list1_global=alist1.get(0);
list_flag=false;
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US")) {
new brs_wd(getActivity(),pageno,item).execute();
} else {
new brs_wd(getActivity(),pageno,item).execute();
}
}
});
listView3.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
final TextView textView = (TextView) view
.findViewById(R.id.text_browsword);
if (InternetConnection.isInternetOn(context)) {
SearchData_DTO.setSearchData_DTO(new SearchData()
.getSearched(textView.getText().toString(),
context));
} else {
SearchData_DTO.setSearchData_DTO(new SearchDataDB()
.getSearchedDB(textView.getText().toString(),
context));
}
Intent i = new Intent(context, Search.class);
i.putExtra("selected", textView.getText().toString().replace("(m)", "").replace("(f)", "") .replace("(n)", ""));
startActivity(i);
}
});
setHasOptionsMenu(true);
return rootView;
}
public void onPrepareOptionsMenu(Menu menu)
{
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US"))
{
menu.removeItem(R.id.English);
menu.removeItem(R.id.Gujarati);
menu.removeItem(R.id.Punjabi);
menu.removeItem(R.id.Bengali);
menu.removeItem(R.id.Marathi);
menu.removeItem(R.id.Talugu);
menu.removeItem(R.id.Tamil);
} else
{
menu.removeItem(R.id.Hindi);
menu.removeItem(R.id.Gujarati);
menu.removeItem(R.id.Punjabi);
menu.removeItem(R.id.Bengali);
menu.removeItem(R.id.Marathi);
menu.removeItem(R.id.Talugu);
menu.removeItem(R.id.Tamil);
}
return;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
item.collapseActionView();
if (R.id.Hindi == item.getItemId()) {
android.support.v4.app.FragmentManager fragmentManager = getChildFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, new Browse());
fragmentTransaction.commit();
}
if (R.id.English == item.getItemId()) {
android.support.v4.app.FragmentManager fragmentManager = getChildFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, new Browse());
fragmentTransaction.commit();
}
return super.onOptionsItemSelected(item);
}
public boolean browseLetter(final String query, final Context context,final String lang, final String tl)
{
if (InternetConnection.isInternetOn(context))
{
try {
response = CustomHttpClient.executeHttpGet(BROWSE_URL+ "sl=" + lang + "&tl=" + tl+ "&t=1&epp=0&p=1&e=" + query);
if (response != null) {
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
alist1.add(arr.getString(i));
}
result = true;
Log.v("--------list1----------", alist1.toString());
}
} catch (Exception e) {
Log.e("/////////////////////////Exception in LIST1 ", e.toString());
}
return true;
} else
{
if (!InternetConnection.isInternetOn(context)) {
s = Environment.getExternalStorageDirectory().toString();
dbFile1_ = new File(s, "sk1.db");
dbFile2_ = new File(s, "sk2.db");
if(dbFile1_.exists()||dbFile2_.exists())
{
/* do something */
alist1 = new ArrayList<String>(new SearchDataDB().ltwo(context,query, lang));
}
else
{
final AlertDialog.Builder alertbox = new AlertDialog.Builder(getActivity());
alertbox.setTitle("Error");
alertbox.setMessage("Internet connection is not available.");
alertbox.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
}
});
alertbox.show();
}
}
try{
Browse_Adapter2 listAdapter2 = new Browse_Adapter2(context,R.layout.browse_list_item, alist1);
if(listAdapter2!=null)
listView2.setAdapter(listAdapter2);
result = true;
}
catch(Exception e){e.printStackTrace();}
}
return result;
}
public String browseWord(final String query, final Context context,final String lang, final String tl, final int epp, final int p,String letter)
{
if (InternetConnection.isInternetOn(context))
{
try {
response = CustomHttpClient.executeHttpGet(BROWSE_WORD+ "sl=" + lang + "&tl=" + tl + "&t=2&epp="+ epp + "&p=" + p + "&e=" + query);//
if (response != null) {
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
alist2.add(arr.getString(i));
}
}
} catch (Exception e)
{
Log.e("/////////////////////////Exception in LIST2 ", e.toString());
}
return response;
} else {
if (!InternetConnection.isInternetOn(context))
{
alist2 = new ArrayList<String>(new SearchDataDB().bword(context, query, lang));
try{
Browse_Adapter2 listAdapter3 = new Browse_Adapter2(context,R.layout.browse_list_item, alist2);
if(listAdapter3!=null)
listView3.setAdapter(listAdapter3);}
catch(Exception e)
{
e.printStackTrace();
}
txt = query;
if (alist2.size() < epp) {
next.setText("");
}
if (pageno == 0)
prev.setVisibility(View.GONE);
}
}
return response;
}
FileFilter filter = new FileFilter() {
#Override
public boolean accept(File pathname) {
if(pathname.isFile()){
return true;
}
else{
return false;
}
}
};
class brs extends AsyncTask<Object ,Object ,Object >
{
//context=getActivity().getBaseContext();
Activity context;
public brs(Activity context)
{
loadingDialog = new ProgressDialog(context);
this.context=context;
}
#Override
protected void onPreExecute()
{
//loadingDialog= new ProgressDialog(getActivity().getBaseContext());
loadingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
loadingDialog.setMessage("Please wait...");
loadingDialog.setCancelable(false);
loadingDialog.show();
super.onPreExecute();
};
#Override
protected Object doInBackground(Object... params)
{
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US"))
{
return browseLetter(txt,context, "en", "hi");
}
else
{
return browseLetter(txt,context, "hi", "en");
}
}
protected void onPostExecute(Object result)
{
try{
if(alist1!=null)
{
//list1_global=alist1.get(0);
Log.v("---------------list1--------------", "list1"+alist1);
Browse_Adapter2 listAdapter2 = new Browse_Adapter2(context,R.layout.browse_list_item, alist1);
if(listAdapter2!=null)
listView2.setAdapter(listAdapter2);}
else{
Log.v("--------------list1--------------", "list1"+alist1);
}
//loadingDialog.dismiss();
}
catch(Exception e)
{
e.printStackTrace();
}
new brs_wd(getActivity(),pageno,list1_global).execute();
//loadingDialog.dismiss();
}
}
class brs_wd extends AsyncTask<Object ,Object ,String>
{
int pg;
Activity context;
String list2word;
public brs_wd(Activity context,int page_no,String list2word)
{
//loadingDialog = new ProgressDialog(context);
this.context=context;
this.pg=page_no;
if(list_flag)
{
this.list2word=txt;
}
else{
this.list2word=list2word;
}
}
#Override
protected void onPreExecute()
{
/*//loadingDialog= new ProgressDialog(getActivity().getBaseContext());
loadingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
loadingDialog.setMessage("Please wait...");
loadingDialog.setCancelable(false);
loadingDialog.show();*/
super.onPreExecute();
};
#Override
protected String doInBackground(Object... params)
{
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US"))
{
return browseWord(list2word, context, "en", "hi", epp, pg,list2word);
}
else
{
return browseWord(list2word, context, "hi", "en", epp, pg,list2word);
}
}
protected void onPostExecute(String query)
{
try{
Log.d("-------------List2--------", alist2+"");
if(alist2!=null){
Browse_Adapter2 listAdapter3 = new Browse_Adapter2(context, R.layout.browse_list_item, alist2);
if(listAdapter3!=null)
listView3.setAdapter(listAdapter3);
txt = query;
if (alist2.size() < epp) {
next.setText("");
} else {
next.setText("Next>>");
}
if (pageno == 0)
prev.setVisibility(View.GONE);}
else{
Log.d("-------------------List2--------------", "empty"+alist2);
}
}
catch(Exception e)
{
e.printStackTrace();
}
loadingDialog.dismiss();
}
}
}
help me for this.

Categories

Resources