Can't swipe in SwipeRefresh layout when there is no data - android

I am using RecyclerView with SwipeRefreshLayout in my app. The problem is that when my RecyclerView have data, I can swipe the layout. But when there's no data in RecyclerView, I can't swipe.
Anyone can solve this problem?
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.student_fragment_tutorial_upcoming, container, false);
tvNoData = (TextView) view.findViewById(R.id.tvNoData);
bdn = getArguments();
year = bdn.getString(TutorialStudentFragment.YEARNAME);
Toast.makeText(getContext(), year, Toast.LENGTH_SHORT).show();
networkUtil = new NetworkUtil();
conStatus = networkUtil.getConnectivityStatusString(getContext());
mdbHelper = new DatabaseHelper(getContext());
copyData = new CopyDatabase(getContext());
recyclerTutorial = (RecyclerView) view.findViewById(R.id.recyclerTutorial);
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipelayoutTutorial);
swipeRefreshLayout.setColorSchemeResources(R.color.blue, R.color.orange, R.color.green);
if (conStatus.equals("wifi") || conStatus.equals("mobile_data")) {
onRefresh();
} else {
//swipeRefreshLayout.setRefreshing(true);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
if (mdbHelper.getAllTutorialInfo(year, tutorialType).size() == 0) {
tvNoData.setText("There is no upcoming tutorial for now");
tvNoData.setVisibility(View.VISIBLE);
} else {
tvNoData.setVisibility(View.INVISIBLE);
loadTutorialCard(mdbHelper.getAllTutorialInfo(year, tutorialType));
}
//swipeRefreshLayout.setRefreshing(false);
}
});
}
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getContext(), 1);
recyclerTutorial.setLayoutManager(mLayoutManager);
recyclerTutorial.addItemDecoration(new GridSpacingItemDecoration(1, dpToPx(10), true));
recyclerTutorial.setItemAnimator(new DefaultItemAnimator());
Animation fadeIn = AnimationUtils.loadAnimation(getContext(), R.anim.fade_in);
Animation fadeOut = AnimationUtils.loadAnimation(getContext(), R.anim.fade_out);
recyclerTutorial.setAnimation(fadeIn);
recyclerTutorial.addOnItemTouchListener(new RecyclerTouchListener(getContext(), recyclerTutorial, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
/* tutorialArrayList = mdbHelper.getAllTutorialInfo(year);
Tutorial tutorial = tutorialArrayList.get(position);
Bundle bdn = new Bundle();*/
Toast.makeText(getContext(), position + " clicked", Toast.LENGTH_SHORT).show();
}
#Override
public void onLongClick(View view, int position) {
}
}));
swipeRefreshLayout.setOnRefreshListener(this);
return view;
}
public void getTutorialData() {
swipeRefreshLayout.setRefreshing(true);
networkUtil = new NetworkUtil();
conStatus = networkUtil.getConnectivityStatusString(getContext());
if (conStatus.equals("wifi") || conStatus.equals("mobile_data")) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, select_tutorial_url,
new Response.Listener<String>() {
ArrayList<Tutorial> tutorialArrayList = new ArrayList<>();
#Override
public void onResponse(String response) {
int count = 0;
if (response.length() > 0) {
while (count < response.length()) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(count);
int id = Integer.parseInt(jsonObject.getString("id"));
// String codeStatus =jsonObject.getString("code");
Tutorial tutorial = new Tutorial(id, jsonObject.getString("class_name"), jsonObject.getString("subject"), jsonObject.getString("lesson"), jsonObject.getString("exam_date"), jsonObject.getString("exam_time"), jsonObject.getString("published"));
if (checkTutorialListWithDate(tutorial)) {
tutorialArrayList.add(tutorial);
}
Log.i("Class :", tutorial.getsClass());
Log.i("Subject :", tutorial.getSubject());
Log.i("Lesson :", tutorial.getLesson());
} catch (JSONException e) {
e.printStackTrace();
}
count++;
}
} else {
Toast.makeText(getContext(), String.valueOf(response.length()), Toast.LENGTH_SHORT).show();
}
swipeRefreshLayout.setRefreshing(false);
loadTutorialCard(tutorialArrayList);
if (tutorialArrayList.size() == 0) {
tvNoData.setVisibility(View.VISIBLE);
tvNoData.setText("There is no upcoming tutorial for now");
} else {
tvNoData.setVisibility(View.INVISIBLE);
}
workingWithLocalDatabase(tutorialArrayList, mdbHelper.getAllTutorialInfo(year, tutorialType));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
swipeRefreshLayout.setRefreshing(false);
NetworkUtil.checkInternetConnection(error, getContext(), swipeRefreshLayout);
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("studentYear", year);
return params;
}
};
Mysingleton.getInstance(getContext()).addToRequestque(stringRequest);
} else {
swipeRefreshLayout.setRefreshing(false);
networkUtil.showNetError(getContext(), swipeRefreshLayout);
}
}
public void onRefresh() {
getTutorialData();
}

Related

when i change the fragment and come back to the previous fragment by swaping its not showing anything

I have 4 fragments and each fragment has recyclerview.
the fragments are attached to the tabs. when i move from one fragment to another and came back to the previous fragment is not showing any data.
These are my two fragments files.
recentFragment.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
// return inflater.inflate(R.layout.fragment_recent, container, false);
listItems = new ArrayList<>();
loadRecyclerViewData();
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_recent, container, false);
rvRecent = (RecyclerView) v.findViewById(R.id.rvRecent);
progressBar =(ProgressBar) v.findViewById(R.id.porgress);
rvRecent.setHasFixedSize(true);
JobAdapter jobAdapter = new JobAdapter(listItems,getContext());
manager = new LinearLayoutManager(getActivity());
rvRecent.setLayoutManager(manager);
rvRecent.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(#NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if(newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL){
isScrolling = true;
}
}
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
currentItems = manager.getChildCount();
totalItems = manager.getItemCount();
scrollOutItems = manager.findFirstVisibleItemPosition();
if(isScrolling && (currentItems + scrollOutItems == totalItems)){
//fetch data
isScrolling = false;
loadMoreData();
}
}
});
return v;
}
//test
private void loadRecyclerViewData() {
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading data...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET
, URL_DATA, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("employees");
if(jsonArray.length()<counter_2){
counter_2 = jsonArray.length();
//set flag for data completion
}
for(int i = counter_1; i<counter_2; i++){
JSONObject obj = jsonArray.getJSONObject(i);
ListItem item = new ListItem(
obj.getString("name"),
obj.getString("firstappearance"),
obj.getString("imageurl")
);
listItems.add(item);
counter_1 = counter_1 + 1;
}
adapter = new JobAdapter(listItems,getContext()); //check
rvRecent.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void loadMoreData() {
progressBar.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
StringRequest stringRequest = new StringRequest(Request.Method.GET
, URL_DATA, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("employees");
if(jsonArray.length()>counter_2 * 2){
counter_2 = counter_2 * 2;
}else{
counter_2 = jsonArray.length();
//set flag for data completion
}
for(int i = counter_1; i<counter_2; i++){
JSONObject obj = jsonArray.getJSONObject(i);
ListItem item = new ListItem(
obj.getString("name"),
obj.getString("firstappearance"),
obj.getString("imageurl")
);
listItems.add(item);
counter_1 = counter_1 + 1;
}
// adapter = new JobAdapter(listItems,getApplicationContext());
// rvJob.setAdapter(adapter);
adapter.notifyDataSetChanged();
progressBar.setVisibility(View.GONE);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
},2000);
}
NotificationsFragment.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
listItems = new ArrayList<>();
loadRecyclerViewData();
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_notifications, container, false);
rvNotifications = (RecyclerView) v.findViewById(R.id.rvNotifications);
progressBar =(ProgressBar) v.findViewById(R.id.porgress);
rvNotifications.setHasFixedSize(true);
JobAdapter jobAdapter = new JobAdapter(listItems,getContext());
manager = new LinearLayoutManager(getActivity());
rvNotifications.setLayoutManager(manager);
rvNotifications.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(#NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if(newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL){
isScrolling = true;
}
}
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
currentItems = manager.getChildCount();
totalItems = manager.getItemCount();
scrollOutItems = manager.findFirstVisibleItemPosition();
if(isScrolling && (currentItems + scrollOutItems == totalItems)){
//fetch data
isScrolling = false;
loadMoreData();
}
}
});
return v;
}
private void loadRecyclerViewData() {
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading data...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET
, URL_DATA, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("employees");
if(jsonArray.length()<counter_2){
counter_2 = jsonArray.length();
//set flag for data completion
}
for(int i = counter_1; i<counter_2; i++){
JSONObject obj = jsonArray.getJSONObject(i);
ListItem item = new ListItem(
obj.getString("name"),
obj.getString("firstappearance"),
obj.getString("imageurl")
);
listItems.add(item);
counter_1 = counter_1 + 1;
}
adapter = new JobAdapter(listItems,getContext()); //check
rvNotifications.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void loadMoreData() {
progressBar.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
StringRequest stringRequest = new StringRequest(Request.Method.GET
, URL_DATA, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("employees");
if(jsonArray.length()>counter_2 * 2){
counter_2 = counter_2 * 2;
}else{
counter_2 = jsonArray.length();
//set flag for data completion
}
for(int i = counter_1; i<counter_2; i++){
JSONObject obj = jsonArray.getJSONObject(i);
ListItem item = new ListItem(
obj.getString("name"),
obj.getString("firstappearance"),
obj.getString("imageurl")
);
listItems.add(item);
counter_1 = counter_1 + 1;
}
JobAdapter(listItems,getApplicationContext());
adapter.notifyDataSetChanged();
progressBar.setVisibility(View.GONE);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
},2000);
}
Main2Activity.java
public class Main2Activity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
tabLayout = findViewById(R.id.tabLayout_id);
viewPager = findViewById(R.id.viewPager_id);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
//adding fragments
adapter.AddFragment(new RecentFragment(),"Recent");
adapter.AddFragment(new JobsFragment(),"Jobs");
adapter.AddFragment(new NotificationsFragment(),"Notifications");
adapter.AddFragment(new RecentFragment(),"Results");
//adapter setup
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_recent_24dp);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_jobs_24dp);
tabLayout.getTabAt(2).setIcon(R.drawable.ic_notifications_black_24dp);
tabLayout.getTabAt(3).setIcon(R.drawable.ic_results_24dp);
}
}
Add
viewPager.setOffscreenPageLimit(3)
After
viewPager = findViewById(R.id.viewPager_id);

application blank after move to another fragment using bottom navigation view

I tried to build an app that have 5 fragment that displayed using bottom navigation view. I use volley to get the data from database. i have a problem with calling the data. at fragment A. i call the web service and got some data and then display it using recyclerview. But if i move to another fragment ( lets say fragment B) and went back to the fragment A. the data is lost and it just show the standard ui like search widget,spinner widget. All i want to ask is :
where should i put the code to call web service for all my fragment. On the activity that handle the fragment or just on the fragment?
why volley doesn't call data again when i back to the fragment?
this is the code of my mainactivity that contain bottom navigation view with 5 fragments:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isNetworkStatusAvialable (getApplicationContext())) {
bottomNavigationView=(BottomNavigationView)findViewById(R.id.main_nav);
frameLayout=(FrameLayout) findViewById(R.id.main_frame);
herbal= new herbal();
crude = new crude();
database=new database();
analysis=new analysis();
compound=new compound();
setFragment(herbal);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId())
{
case R.id.nav_herbal:
setFragment(herbal);
return true;
case R.id.nav_crude:
setFragment(crude);
return true;
case R.id.nav_database:
setFragment(database);
return true;
case R.id.nav_analysis:
setFragment(analysis);
return true;
case R.id.nav_compound:
setFragment(compound);
return true;
default:
return false;
}
}
});
} else {
Toast.makeText(getApplicationContext(), "internet is not avialable", Toast.LENGTH_SHORT).show();
}
}
private boolean isNetworkStatusAvialable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null)
{
NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
if(netInfos != null)
if(netInfos.isConnected())
return true;
}
return false;
}
private void setFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame,fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
this is the example in my fragment which calling web service and then display it using recycler view:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_herbal, container, false);
herbalModels = new ArrayList<>();
kampoModels = new ArrayList<>();
searchHerbal = (EditText) rootView.findViewById(R.id.search_herbal);
searchHerbal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchHerb();
}
});
loadData = (ProgressBar) rootView.findViewById(R.id.loadRecyclerView);
RequestQueue queue = MySingleton.getInstance(this.getActivity().getApplicationContext()).getRequestQueue();
sortData(rootView);
get20DataJamu();
get20DataKampo();
StartRecyclerViewJamu(rootView);
return rootView;
}
private void searchHerb() {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
searchHerbs searchHerbs = new searchHerbs();
ft.replace(R.id.main_frame, searchHerbs);
ft.commit();
}
private void StartRecyclerViewKampo(View rootView) {
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview_herbal);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
// use a linear layout manager
mRecyclerView.setLayoutManager(mLayoutManager);
kampoAdapter = new kampoAdapter(mRecyclerView, getActivity(), kampoModels);
mRecyclerView.setAdapter(kampoAdapter);
kampoAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
kampoModels.add(null);
kampoAdapter.notifyItemInserted(kampoModels.size() - 1);
handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
kampoModels.remove(kampoModels.size() - 1);
kampoAdapter.notifyItemRemoved(kampoModels.size());
//add items one by one
int start = kampoModels.size();
int end = start + 20;
loadMoreKampo(start, end);
}
}, 5000);
}
});
}
private void loadMoreKampo(final int start, final int end) {
String url = "https://jsonplaceholder.typicode.com/photos";
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.d(TAG, "Onresponse" + jsonArray.toString());
for (int i = start; i < end; i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Log.d(TAG,"jsonobject"+jsonObject);
kampoModels.add(
new kampoModel(
jsonObject.getString("title"),
"Khasiat",
jsonObject.getString("albumId"),
jsonObject.getString("id"),
jsonObject.getString("thumbnailUrl")
)
);
kampoAdapter.notifyItemInserted(kampoModels.size());
} catch (JSONException e) {
}
}
kampoAdapter.setLoaded();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "Onerror" + volleyError.toString());
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(request);
}
private void get20DataKampo() {
String url = "https://jsonplaceholder.typicode.com/photos";
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.d(TAG, "Onresponsekampo" + jsonArray.toString());
Log.d(TAG, "lengthresponse" + jsonArray.length());
for (int i = 0; i < 20; i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Log.d(TAG,"jsonobject"+jsonObject);
kampoModels.add(
new kampoModel(
jsonObject.getString("title"),
"Khasiat",
jsonObject.getString("albumId"),
jsonObject.getString("id"),
jsonObject.getString("thumbnailUrl")
)
);
} catch (JSONException e) {
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "Onerrorkampo" + volleyError.toString());
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(request);
}
private void StartRecyclerViewJamu(final View rootView) {
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview_herbal);
mRecyclerView.setVisibility(View.GONE);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
// use a linear layout manager
mRecyclerView.setLayoutManager(mLayoutManager);
// create an Object for Adapter
mAdapter = new herbalAdapter(mRecyclerView, getActivity(), herbalModels);
mRecyclerView.setAdapter(mAdapter);
loadData.setVisibility(View.GONE);
mRecyclerView.setVisibility(View.VISIBLE);
mAdapter.notifyDataSetChanged();
mAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
//add null , so the adapter will check view_type and show progress bar at bottom
herbalModels.add(null);
mAdapter.notifyItemInserted(herbalModels.size() - 1);
handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// remove progress item
herbalModels.remove(herbalModels.size() - 1);
mAdapter.notifyItemRemoved(herbalModels.size());
//add items one by one
int start = herbalModels.size();
int end = start + 20;
loadMoreJamu(start, end);
}
}, 5000);
}
});
}
private void get20DataJamu() {
String url = "https://jsonplaceholder.typicode.com/posts";
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.d(TAG, "Onresponse" + jsonArray.toString());
Log.d(TAG, "lengthonresponse" + jsonArray.length());
for (int i = 0; i < 20; i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Log.d(TAG,"jsonobject"+jsonObject);
herbalModels.add(
new herbalModel(
jsonObject.getString("title"),
"Khasiat",
jsonObject.getString("userId"),
jsonObject.getString("id"),
jsonObject.getString("body")
)
);
} catch (JSONException e) {
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "Onerror" + volleyError.toString());
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(request);
}
private void loadMoreJamu(final int start, final int end) {
String url = "https://jsonplaceholder.typicode.com/posts";
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.d(TAG, "Onresponse" + jsonArray.toString());
for (int i = start; i < end; i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Log.d(TAG,"jsonobject"+jsonObject);
herbalModels.add(
new herbalModel(
jsonObject.getString("title"),
"Khasiat",
jsonObject.getString("userId"),
jsonObject.getString("id"),
jsonObject.getString("body")
)
);
mAdapter.notifyItemInserted(herbalModels.size());
} catch (JSONException e) {
}
}
mAdapter.setLoaded();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "Onerror" + volleyError.toString());
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(request);
}
private void sortData(final View rootView) {
final Spinner spinner = (Spinner) rootView.findViewById(R.id.filter_herbal);
// Create an ArrayAdapter using the string array and a default spinner layout
List<categoriesHerbal> itemList = new ArrayList<categoriesHerbal>();
itemList.add(
new categoriesHerbal(
"1",
"Jamu"
)
);
itemList.add(
new categoriesHerbal(
"2",
"Kampo"
)
);
ArrayAdapter<categoriesHerbal> spinnerAdapter = new ArrayAdapter<categoriesHerbal>(getActivity(), android.R.layout.simple_spinner_item, itemList);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Specify the layout to use when the list of choices appears
// Apply the adapter to the spinner
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
categoriesHerbal selectedValue = (categoriesHerbal) parent.getItemAtPosition(position);
String categories = (String) selectedValue.getCategories();
String idCategories = (String) selectedValue.getIdCategories();
StartRecyclerViewJamu(rootView);
} else {
categoriesHerbal selectedValue = (categoriesHerbal) parent.getItemAtPosition(position);
String categories = (String) selectedValue.getCategories();
String idCategories = (String) selectedValue.getIdCategories();
StartRecyclerViewKampo(rootView);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
move your data code in separate class and call it wherever needed.
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId())
{
case R.id.nav_herbal:
setFragment(herbal);
return true;
case R.id.nav_crude:
setFragment(crude);
return true;
case R.id.nav_database:
setFragment(database);
return true;
case R.id.nav_analysis:
setFragment(analysis);
return true;
case R.id.nav_compound:
setFragment(compound);
return true;
/*default:
return false;*/ //no need for this one
}
return true; /*you forget'it*/
}

I need to display data on top of a RecyclerView after refreshing in reverse order

Recycle view load list and reached at top by mList.add(0,actor) but i want to reverse the list.
also i chnaged my code like this,
mLayoutManager.setReverseLayout(true);
mList.add(0,actor);
Here is my recycleview info, This is my recyclview api code InfoJson() here:
public class GatekeeperInfoActivity extends BaseActivity implements View.OnClickListener , MyComplaintListner {
private RecyclerView mRecyclerView;
private GateInfoAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<GateInfoPojo> mList;
Context ctx;
String visitor_id,id,cid;
M_Shared_Pref m_shared_pref;
ImageView back_button, img;
private MyDialog dialog;
TextView complaint,subject,msg,from_name_txt;
ImageView attach;
String from_id,from_name,from_mobile;
String id_rwa,new_id;
public static final int DISMISS_TIMEOUT = 2000;
LinearLayout ll_no_data;
int limit =0;
int limit_refresh;
static int nums;
private appconfig.EndlessRecyclerOnScrollListener scrollListener;
LinearLayoutManager linearLayoutManager;
public int overallXScrol = 0;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rwa_view_info);
ctx = GatekeeperInfoActivity.this;
dialog = new MyDialog(this);
m_shared_pref = new M_Shared_Pref(GatekeeperInfoActivity.this);
visitor_id = m_shared_pref.getPrefranceStringValue(App_Info.Visitor_ID);
id = m_shared_pref.getPrefranceStringValue(App_Info.Flat_User_Id);
cid = m_shared_pref.getPrefranceStringValue(App_Info.Flat_User_Id_cid);
Bundle bundle = this.getIntent().getExtras();
from_id = bundle.getString("id");
from_name = bundle.getString("name");
from_mobile = bundle.getString("mobile");
id_rwa = getIntent().getStringExtra("id_rwa");
if (from_id != null && !from_id.isEmpty() && !from_id.equals("null"))
{ new_id = from_id; }
else{ new_id = id_rwa; }
System.out.println("check:check"+from_id+":"+id_rwa);
///// using this new_id
mList = new ArrayList<GateInfoPojo>();
mRecyclerView = findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new GateInfoAdapter(mList, ctx);
ll_no_data = findViewById(R.id.ll_no_data);
mAdapter.setMyClickListener(this);
/* button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
limit_refresh = nums+limit;
limit = limit_refresh;
if(nums>=20){
// item_progress_bar.setVisibility(View.VISIBLE);
InfoJson();
}
}
});*/
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (!recyclerView.canScrollVertically(-1)) {
// Toast.makeText(GatekeeperInfoActivity.this, "Last", Toast.LENGTH_LONG).show();
limit_refresh = nums+limit;
limit = limit_refresh;
if(nums>=20){
// item_progress_bar.setVisibility(View.VISIBLE);
InfoJson();
}
}
}
});
img = findViewById(R.id.pic);
from_name_txt = findViewById(R.id.from_name_txt);
attach = findViewById(R.id.attach);
msg = findViewById(R.id.msg);
complaint = findViewById(R.id.complaint);
subject = findViewById(R.id.subject);
back_button = findViewById(R.id.back_button);
back_button.setOnClickListener(this);
attach.setOnClickListener(this);
if(NetWorkCheck.checkConnection(GatekeeperInfoActivity.this)){
mList.clear();
InfoJson();
}
else{
TastyToast.makeText(getApplicationContext(), "Internet connection is disable", TastyToast.LENGTH_LONG, TastyToast.WARNING);
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.back_button:
finish();
break;
case R.id.attach:
if(msg.getText().toString().length()>0){
submitReply(msg.getText().toString(),new_id);
}
else{
TastyToast.makeText(getApplicationContext(), "Enter Message", TastyToast.LENGTH_LONG, TastyToast.INFO);
}
break;
}
}
public void InfoJson() {
dialog.ShowProgressDialog();
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.Base_Url+"AllChatWithUser.php?", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
dialog.CancelProgressDialog();
JSONObject obj = new JSONObject(response);
String error = obj.getString("error");
nums = obj.getInt("nums");
System.out.println("limit_limit_num"+nums);
if(nums>=1) {
if (error.equals("true")) {
from_name_txt.setText("GateKeeper : " + obj.getString("names"));
JSONArray tower = obj.getJSONArray("Flat");
for (int i = 0; i < tower.length(); i++) {
JSONObject jsonnew = tower.getJSONObject(i);
GateInfoPojo actor = new GateInfoPojo();
String id = jsonnew.getString("id");
String Reply_From = jsonnew.getString("reply_from");
String message = jsonnew.getString("message");
String reply_date = jsonnew.getString("send_time");
String usertype = jsonnew.getString("usertype");
actor.setId(id);
actor.setReply_from(Reply_From);
actor.setMessage(message);
actor.setSend_time(reply_date);
actor.setUsertype(usertype);
if(limit==0){
mList.add(actor);
}
else{
mList.add(0,actor);
}
mAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.getLayoutManager().scrollToPosition(nums - 1);
}
}
}
else
{
mRecyclerView.setVisibility(View.GONE);
ll_no_data.setVisibility(View.VISIBLE);
// TastyToast.makeText(getApplicationContext(), obj.getString("msg"), TastyToast.LENGTH_LONG, TastyToast.ERROR);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
dialog.CancelProgressDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("empid", new_id);
params.put("fid", id);
params.put("usertype", "FlatUser");
params.put("limit", String.valueOf(limit));
Log.e("params", String.valueOf(params));
return params;
}
};
requestQueue.add(stringRequest);
}
#Override
public void onItemClick(View v, Object bean, String feed, String rating,String comp_spinner) {
String complaint_id = ((GateInfoPojo) bean).getId();
// submitComplaintInfo(complaint_id,feed,rating,comp_spinner);
}
#Override
public void onItemClickActivity(View v, Object bean) {
String complaint_id = ((GateInfoPojo) bean).getId();
}
public void submitReply(final String msg1,final String new_id) {
dialog.ShowProgressDialog();
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.Base_Url+"ChatWithUser.php?", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
dialog.CancelProgressDialog();
JSONObject obj = new JSONObject(response);
String error = obj.getString("error");
if (error.equals("true"))
{
// TastyToast.makeText(getApplicationContext(), obj.getString("msg"), TastyToast.LENGTH_LONG, TastyToast.SUCCESS);
msg.setText("");
InfoJson();
mList.clear();
}
else
{
TastyToast.makeText(getApplicationContext(), obj.getString("msg"), TastyToast.LENGTH_LONG, TastyToast.ERROR);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
dialog.CancelProgressDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("fid", id);
params.put("empid", new_id);
params.put("usertype", "FlatUser");
params.put("message", msg1);
Log.e("params", String.valueOf(params));
return params;
}
};
requestQueue.add(stringRequest);
}
}
But this is not working its add to top but not reverse the api data bottom to top.
Any help would be appreciated.
You can reverse the array list by -
Collections.reverse(mList);
After that setAdapter() or notifyDataSetChanged() according to your requirement.
public void InfoJson() {
dialog.ShowProgressDialog();
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.Base_Url+"AllChatWithUser.php?", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
dialog.CancelProgressDialog();
JSONObject obj = new JSONObject(response);
String error = obj.getString("error");
nums = obj.getInt("nums");
System.out.println("limit_limit_num"+nums);
if(nums>=1) {
if (error.equals("true")) {
from_name_txt.setText("GateKeeper : " + obj.getString("names"));
JSONArray tower = obj.getJSONArray("Flat");
for (int i = 0; i < tower.length(); i++) {
JSONObject jsonnew = tower.getJSONObject(i);
GateInfoPojo actor = new GateInfoPojo();
String id = jsonnew.getString("id");
String Reply_From = jsonnew.getString("reply_from");
String message = jsonnew.getString("message");
String reply_date = jsonnew.getString("send_time");
String usertype = jsonnew.getString("usertype");
actor.setId(id);
actor.setReply_from(Reply_From);
actor.setMessage(message);
actor.setSend_time(reply_date);
actor.setUsertype(usertype);
if(limit==0){
mList.add(actor);
}
else{
mList.add(0,actor);
}
}
Collections.reverse(mList);
mAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mAdapter);
// mRecyclerView.getLayoutManager().scrollToPosition(nums - 1);
}
}
else
{
mRecyclerView.setVisibility(View.GONE);
ll_no_data.setVisibility(View.VISIBLE);
// TastyToast.makeText(getApplicationContext(), obj.getString("msg"), TastyToast.LENGTH_LONG, TastyToast.ERROR);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
dialog.CancelProgressDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("empid", new_id);
params.put("fid", id);
params.put("usertype", "FlatUser");
params.put("limit", String.valueOf(limit));
Log.e("params", String.valueOf(params));
return params;
}
};
requestQueue.add(stringRequest);
}
Try adding the following code, both of them need to be true.
mLayoutManager.setStackFromEnd(true);
mLayoutManager.setReverseLayout(true);
From OnCreate() remove your setadapter as your list doesn't have data yet.
and in your onResponse() reverse your listdata before setting it
Collections.reverse(mList);
mAdapter = new GateInfoAdapter(mList, ctx);
mRecyclerView.setAdapter(mAdapter);

RecyclerView in ViewPager not refreshing from BlankFragment

I am trying to implement Ranking for city, country and Worldwide in my App while fetching data using Volley as JSON response and loading it in seperate ArrayList. My problem is that it loads data in arrayList but pagerAdapter.notifyDataSetChanged() does not reflect the new data until you manual rotate mobile orientation and onCreate() or onResume() is called automatically. Bellow is the code for RatingActivity.java. and BlankFragment.java to load cards(Recyclers).
RatingActivity.java
public class RatingActivity extends AppCompatActivity {
String user,aun, aps;
int lst=0;
public static ArrayList<String> emailst1, ranklst1, namelst1, ratinglst1;
public static ArrayList<String> emailst2, ranklst2, namelst2, ratinglst2;
public static ArrayList<String> emailst3, ranklst3, namelst3, ratinglst3;
public static PagerAdapter pagerAdapter;
TextView txtmyrank, txtmyname, txtmyrating;
public static int ran[]={0,0,0};
public static int tabpost;
public String[] usdtl={"","","",""};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rating);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
javalib jl = new javalib();
txtmyrank=(TextView)findViewById(R.id.txtmyrank);
txtmyname=(TextView)findViewById(R.id.txtmyname);
txtmyrating=(TextView)findViewById(R.id.txtmyrating);
aun = jl.HelloJNI();
aps = jl.HiJNI();
aps=aps.substring(0,aps.length()-1);
DBHelper db = new DBHelper(this);
//Log.e("Called","yeh");
SessionM session = new SessionM(this);
// get user data from session
HashMap<String, String> user;
user = session.getUserDetails();
String Usremail = user.get(SessionM.KEY_EMAIL);
usdtl = db.getUserDetail(Usremail);
String loc = usdtl[1];
emailst1 = new ArrayList<String>();
ranklst1 = new ArrayList<String>();
namelst1 = new ArrayList<String>();
ratinglst1 = new ArrayList<String>();
emailst2 = new ArrayList<String>();
ranklst2 = new ArrayList<String>();
namelst2 = new ArrayList<String>();
ratinglst2 = new ArrayList<String>();
emailst3 = new ArrayList<String>();
ranklst3 = new ArrayList<String>();
namelst3 = new ArrayList<String>();
ratinglst3 = new ArrayList<String>();
String[] address={"",""};
address[0]=loc.substring(0,loc.indexOf(','));
address[1]=loc.substring(loc.indexOf(',')+1,loc.length());
txtmyname.setText(usdtl[2]);
txtmyrating.setText(usdtl[3]);
//////////////////////////// update rank///////////////////////////////////////////////////////////////
String url = "http://abcd.net/getRank.php?uname=" + aun + "&password=" + aps + "&usrname=" + usdtl[0] +"&location1="+address[0]+"&location2="+address[1]+"&app=0";
Log.e("Url", url);
RequestQueue requestQueue = Volley.newRequestQueue(RatingActivity.this);
JsonArrayRequest jar4 = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Boolean isUpdate = response.getJSONObject(0).has("rank");
if (isUpdate == true) {
int lng = 0, il = 0;
lng = response.length();
while (il < lng) {
Log.e("Rank response", response.toString());
ran[il]=Integer.parseInt(response.getJSONObject(il).getString("rank"));
il++;
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
// Adding request to request queue
requestQueue.add(jar4);
url = "http://abcd.net/ctranking.php?uname=" + aun + "&password=" + aps + "&usrname=" + usdtl[0] +"&location="+address[0]+"&cpage=1&app=0";
requestQueue = Volley.newRequestQueue(RatingActivity.this);
JsonArrayRequest jar1 = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Boolean isUpdate = response.getJSONObject(0).has("username");
Boolean isId = response.getJSONObject(0).has("randno");
if (isUpdate == true) {
if (isId == true) {
int lng = 0, il = 0;
lng = response.length();
ranklst1 = new ArrayList<String>();
namelst1 = new ArrayList<String>();
ratinglst1 = new ArrayList<String>();
while (il < lng) {
ranklst1.add((il+1)+"");
emailst1.add(response.getJSONObject(il).getString("username"));
namelst1.add(response.getJSONObject(il).getString("name"));
ratinglst1.add(response.getJSONObject(il).getString("randno"));
il++;
}
lst++;
if(lst==3)
setList();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
// Adding request to request queue
requestQueue.add(jar1);
url = "http://abcd.net/cntranking.php?uname=" + aun + "&password=" + aps + "&usrname=" + usdtl[0] +"&location="+address[1]+"&cpage=1&app=0";
RequestQueue requestQueue2 = Volley.newRequestQueue(RatingActivity.this);
JsonArrayRequest jar2 = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Boolean isUpdate = response.getJSONObject(0).has("username");
Boolean isId = response.getJSONObject(0).has("randno");
if (isUpdate == true) {
if (isId == true) {
int lng = 0, il = 0;
lng = response.length();
ranklst2 = new ArrayList<String>();
namelst2 = new ArrayList<String>();
ratinglst2 = new ArrayList<String>();
while (il < lng) {
ranklst2.add((il+1)+"");
emailst2.add(response.getJSONObject(il).getString("username"));
namelst2.add(response.getJSONObject(il).getString("name"));
ratinglst2.add(response.getJSONObject(il).getString("randno"));
il++;
}
lst++;
if(lst==3)
setList();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
// Adding request to request queue
requestQueue2.add(jar2);
url = "http://abcd.net/wwranking.php?uname=" + aun + "&password=" + aps + "&usrname=" + usdtl[0] +"&cpage=1&app=0";
RequestQueue requestQueue3 = Volley.newRequestQueue(RatingActivity.this);
JsonArrayRequest jar3 = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Boolean isUpdate = response.getJSONObject(0).has("username");
Boolean isId = response.getJSONObject(0).has("randno");
if (isUpdate == true) {
if (isId == true) {
int lng = 0, il = 0;
lng = response.length();
ranklst3 = new ArrayList<String>();
namelst3 = new ArrayList<String>();
ratinglst3 = new ArrayList<String>();
while (il < lng) {
ranklst3.add((il+1)+"");
emailst3.add(response.getJSONObject(il).getString("username"));
namelst3.add(response.getJSONObject(il).getString("name"));
ratinglst3.add(response.getJSONObject(il).getString("randno"));
il++;
}
lst++;
if(lst==3)
setList();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
// Adding request to request queue
requestQueue3.add(jar3);
/////////////////////////////////////////////////////////////////////////////////////////////////////
}
public void setList(){
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
pagerAdapter =
new PagerAdapter(getSupportFragmentManager(), RatingActivity.this);
viewPager.setAdapter(pagerAdapter);
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
// Iterate over all tabs and set the custom view
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pagerAdapter.getTabView(i));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
switch(position){
case 0:
ran[0]=emailst1.indexOf(usdtl[0])+1;
break;
case 1:
ran[1]=emailst2.indexOf(usdtl[0])+1;
break;
case 2:
ran[2]=emailst3.indexOf(usdtl[0])+1;
break;
}
txtmyrank.setText(ran[position]+"");
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
class PagerAdapter extends FragmentPagerAdapter {
String tabTitles[] = new String[] { "શહેર", "દેશ", "વૈશ્વિક" };
Context context;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public Fragment getItem(int position) {
Bundle extra = new Bundle();
switch (position) {
case 0:
tabpost=1;
break;
case 1:
tabpost=2;
break;
case 2:
tabpost=3;
break;
}
extra.putString("position", tabpost+"");
BlankFragment bf = new BlankFragment();
bf.setArguments(extra);
return bf;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
public View getTabView(int position) {
View tab = LayoutInflater.from(RatingActivity.this).inflate(R.layout.custom_tab, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
}
}
Following is the code for BlankFragment.java
public class BlankFragment extends Fragment {
int tabpost;
Boolean userScrolled=false;
ArrayList<String> alstname, alstrank, alstrating;
public BlankFragment(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tabpost=Integer.parseInt(getArguments().getString("position"));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
final RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
rv.setHasFixedSize(true);
switch (tabpost) {
case 1:
alstname = RatingActivity.namelst1;
alstrank = RatingActivity.ranklst1;
alstrating = RatingActivity.ratinglst1;
break;
case 2:
alstname = RatingActivity.namelst2;
alstrank = RatingActivity.ranklst2;
alstrating = RatingActivity.ratinglst2;
break;
case 3:
alstname = RatingActivity.namelst3;
alstrank = RatingActivity.ranklst3;
alstrating = RatingActivity.ratinglst3;
break;
}
MyAdapter adapter = new MyAdapter(alstname, alstrank, alstrating);
rv.setAdapter(adapter);
final LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
userScrolled = true;
}
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
Log.e("dx, dy", dx+" "+dy);
int visibleItemCount = llm.getChildCount();
int totalItemCount = llm.getItemCount();
int pastVisiblesItems = llm.findFirstVisibleItemPosition();
if (userScrolled
&& (visibleItemCount + pastVisiblesItems) == totalItemCount) {
userScrolled = false;
///////////////// updating rank list////////////////////////////////////
switch (tabpost) {
case 1:
Log.e("Updating","Recycler View1"+tabpost);
updatelist(1, totalItemCount);
break;
case 2:
Log.e("Updating","Recycler View2"+tabpost);
updatelist(2, totalItemCount);
break;
case 3:
Log.e("Updating","Recycler View3"+tabpost);
updatelist(3, totalItemCount);
break;
}
/////////////////////////////////////////////////////////////////////////
}
}
});
rv.setLayoutManager(llm);
return rootView;
}
void updatelist(int post, int item){
javalib jl = new javalib();
String aun = jl.HelloJNI();
String aps = jl.HiJNI();
aps=aps.substring(0,aps.length()-1);
DBHelper db = new DBHelper(getContext());
//Log.e("Called","yeh");
SessionM session = new SessionM(getContext());
// get user data from session
HashMap<String, String> user;
user = session.getUserDetails();
String Usremail = user.get(SessionM.KEY_EMAIL);
String[] usdtl = db.getUserDetail(Usremail);
String loc = usdtl[1];
String[] address={"",""};
address[0]=loc.substring(0,loc.indexOf(','));
address[1]=loc.substring(loc.indexOf(',')+1,loc.length());
int page1;
if(item==0)
page1=1;
else
page1=(item-1)/3 + 2;
String url = "http://abcd.net/ctranking.php?uname=" + aun + "&password=" + aps + "&usrname=" + usdtl[0] +"&location="+address[0]+"&cpage="+page1+"&app=0";
Log.e("url", url);
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonArrayRequest jar1 = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Boolean isUpdate = response.getJSONObject(0).has("username");
Boolean isId = response.getJSONObject(0).has("randno");
if (isUpdate == true) {
if (isId == true) {
int lng = 0, il = 0;
lng = response.length();
while (il < lng) {
RatingActivity.ranklst1.add((RatingActivity.ranklst1.size()+1)+"");
RatingActivity.emailst1.add(response.getJSONObject(il).getString("username"));
RatingActivity.namelst1.add(response.getJSONObject(il).getString("name"));
RatingActivity.ratinglst1.add(response.getJSONObject(il).getString("randno"));
il++;
}
RatingActivity.pagerAdapter.notifyDataSetChanged();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
// Adding request to request queue
url = "http://abcd.net/cntranking.php?uname=" + aun + "&password=" + aps + "&usrname=" + usdtl[0] +"&location="+address[1]+"&cpage="+page1+"&app=0";
Log.e("url", url);
RequestQueue requestQueue2 = Volley.newRequestQueue(getContext());
JsonArrayRequest jar2 = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Boolean isUpdate = response.getJSONObject(0).has("username");
Boolean isId = response.getJSONObject(0).has("randno");
if (isUpdate == true) {
if (isId == true) {
int lng = 0, il = 0;
lng = response.length();
/*RatingActivity.ranklst2 = new ArrayList<String>();
RatingActivity.namelst2 = new ArrayList<String>();
RatingActivity.ratinglst2 = new ArrayList<String>();*/
while (il < lng) {
RatingActivity.ranklst2.add((RatingActivity.ranklst2.size()+1)+"");
RatingActivity.emailst2.add(response.getJSONObject(il).getString("username"));
RatingActivity.namelst2.add(response.getJSONObject(il).getString("name"));
RatingActivity.ratinglst2.add(response.getJSONObject(il).getString("randno"));
il++;
}
RatingActivity.pagerAdapter.notifyDataSetChanged();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
url = "http://abcd.net/wwranking.php?uname=" + aun + "&password=" + aps + "&usrname=" + usdtl[0] +"&cpage="+page1+"&app=0";
Log.e("url", url);
RequestQueue requestQueue3 = Volley.newRequestQueue(getContext());
JsonArrayRequest jar3 = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Boolean isUpdate = response.getJSONObject(0).has("username");
Boolean isId = response.getJSONObject(0).has("randno");
if (isUpdate == true) {
if (isId == true) {
int lng = 0, il = 0;
lng = response.length();
while (il < lng) {
RatingActivity.ranklst3.add((RatingActivity.ranklst3.size()+1)+"");
RatingActivity.emailst3.add(response.getJSONObject(il).getString("username"));
RatingActivity.namelst3.add(response.getJSONObject(il).getString("name"));
RatingActivity.ratinglst3.add(response.getJSONObject(il).getString("randno"));
il++;
}
RatingActivity.pagerAdapter.notifyDataSetChanged();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
switch (post) {
case 1: requestQueue.add(jar1);
break;
// Adding request to request queue
case 2:
requestQueue2.add(jar2);
break;
// Adding request to request queue
case 3: requestQueue3.add(jar3);
break;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
}
}

How to manage position in recycler view when scroll after notifydatasetchanged

Here is my code, I have to call method getServerResponse() for first time to get store in arraylist and when I scrolls down I have to call method getServerResponseScroll(). I got result and notify adapter but after scrolling down and up data changes position or may be not visible or get changed. I had created custom adapter for chat. Please help me how to sort out this kind of problem.
public class ChatDetailActivity extends AppCompatActivity {
String macAddress;
RecyclerView recyclerView;
Activity context;
ChatAdapter adapter;
EditText etText;
DatabaseAdapter db;
NetClient nc;
EditText edtSend;
Button btnSend;
DataPref mDataPref;
static int page = 0;
SwipeRefreshLayout mSwipeRefreshLayout;
JSONArray chatDetailListJsonArray;
String toId, channelId, toProfilePic, deviceToken, deviceOsType;
static ArrayList<ChatDetailModel> chatDetailModels = new ArrayList<ChatDetailModel>();
// User mchatUSer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_detail);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
recyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
edtSend = (EditText) findViewById(R.id.edtSend);
btnSend = (Button) findViewById(R.id.btnSend);
db = new DatabaseAdapter(this);
mDataPref = DataPref.getInstance(this);
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
macAddress = wInfo.getMacAddress();
etText = (EditText) findViewById(R.id.etText);
toId = getIntent().getStringExtra("toId");
channelId = getIntent().getStringExtra("channelId");
toProfilePic = getIntent().getStringExtra("toProfilePic");
deviceToken = getIntent().getStringExtra("deviceToken");
deviceOsType = getIntent().getStringExtra("deviceOsType");
getServerResponse(this);
connectionForSend();
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage();
}
});
}
void getServerResponse(final Context context){
StringRequest strReqNewsList = new StringRequest(Request.Method.POST, Constants.getChatDetailListUrl, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("GetNewsList Response POST " + response);
/*
if (progressDialog != null) {
if (progressDialog.isShowing())
progressDialog.dismiss();
}*/
String message = "";
try {
JSONObject jsonObjectResponse = new JSONObject(response);
String responseStatus = jsonObjectResponse.getString("status");
message = jsonObjectResponse.getString("message");
if (responseStatus.equals("true")) {
chatDetailListJsonArray = jsonObjectResponse.getJSONArray("data");
if(page==0) {
GetChat.getInstance(context).deleteAllTableData("tbl_chat_detail", channelId);
}
// JSONObject chatListJsonObject= new JSONObject(gson.toJson(chatListJsonArray));
ArrayList<ChatDetailModel> chatlistModels = new Gson()
.fromJson(chatDetailListJsonArray.toString(),
new TypeToken<List<ChatDetailModel>>() {
}.getType());
for (int i = 0; i < chatDetailListJsonArray.length(); i++) {
ChatDetailModel chatlistModel = chatlistModels.get(i);
chatlistModel.setChannel_id(channelId);
GetChat.getInstance(context).addChatDetailList(new JSONObject(new Gson().toJson(chatlistModel)));
}
JSONArray chatListJsonArray = GetChat.getInstance(ChatDetailActivity.this).getChatDetailListJsonArray(channelId);
chatDetailModels = new Gson().fromJson(chatListJsonArray.toString(), new TypeToken<List<ChatDetailModel>>() {
}.getType());
implemantation();
}
} catch (JSONException e) {
e.printStackTrace();
JSONArray chatListJsonArray = GetChat.getInstance(ChatDetailActivity.this).getChatDetailListJsonArray(channelId);
chatDetailModels = new Gson().fromJson(chatListJsonArray.toString(), new TypeToken<List<ChatDetailModel>>() {
}.getType());
implemantation();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
/* if (progressDialog != null) {
if (progressDialog.isShowing())
progressDialog.dismiss();
}*/
error.printStackTrace();
JSONArray chatListJsonArray = GetChat.getInstance(ChatDetailActivity.this).getChatDetailListJsonArray(channelId);
chatDetailModels = new Gson().fromJson(chatListJsonArray.toString(), new TypeToken<List<ChatDetailModel>>() {
}.getType());
implemantation();
// DatabaseAdapter.deleteDatabase(context);
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("to_id", toId);
params.put("from_id", mDataPref.getUserId());
params.put("page",page+"");
params.put("last_sync_date_time", "");
return params;
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
strReqNewsList.setRetryPolicy(new DefaultRetryPolicy(40 * 1000, 1, 1.0f));
AppController.getInstance(context).addToRequestQueue(strReqNewsList);
}
void getServerResponseScroll(final Context context) {
StringRequest strReqNewsList = new StringRequest(Request.Method.POST, Constants.getChatDetailListUrl, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("GetNewsList Response POST " + response);
String message = "";
try {
JSONObject jsonObjectResponse = new JSONObject(response);
String responseStatus = jsonObjectResponse.getString("status");
message = jsonObjectResponse.getString("message");
if (responseStatus.equals("true")) {
chatDetailListJsonArray = jsonObjectResponse.getJSONArray("data");
// JSONObject chatListJsonObject= new JSONObject(gson.toJson(chatListJsonArray));
ArrayList<ChatDetailModel> chatlistModels = new Gson()
.fromJson(chatDetailListJsonArray.toString(),
new TypeToken<List<ChatDetailModel>>() {
}.getType());
for (int i = 0; i < chatDetailListJsonArray.length(); i++) {
ChatDetailModel chatlistModel = chatlistModels.get(i);
chatlistModel.setChannel_id(channelId);
GetChat.getInstance(context).addChatDetailList(new JSONObject(new Gson().toJson(chatlistModel)));
}
JSONArray chatListJsonArray = GetChat.getInstance(ChatDetailActivity.this).getChatDetailListJsonArray(channelId);
// chatDetailModels.clear();
ArrayList<ChatDetailModel> chatDetailModels1 = new ArrayList<ChatDetailModel>();
chatDetailModels1 = new Gson().fromJson(chatListJsonArray.toString(), new TypeToken<List<ChatDetailModel>>() {
}.getType());
chatDetailModels.clear();
chatDetailModels.addAll(chatDetailModels1);
mSwipeRefreshLayout.setRefreshing(false);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
/* if (progressDialog != null) {
if (progressDialog.isShowing())
progressDialog.dismiss();
}*/
error.printStackTrace();
// DatabaseAdapter.deleteDatabase(context);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("to_id", toId);
params.put("from_id", mDataPref.getUserId());
params.put("page", page + "");
params.put("last_sync_date_time", "");
return params;
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
strReqNewsList.setRetryPolicy(new DefaultRetryPolicy(40 * 1000, 1, 1.0f));
AppController.getInstance(context).addToRequestQueue(strReqNewsList);
}
void implemantation() {
RecyclerView.LayoutManager manager = new LinearLayoutManager(this.getApplicationContext());
recyclerView.setLayoutManager(manager);
adapter = new ChatAdapter(this.getApplicationContext(), chatDetailModels);
recyclerView.setAdapter(adapter);
recyclerView.scrollToPosition(chatDetailModels.size() - 1);
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent i = new Intent(ChatDetailActivity.this, ProfilesDetailActivity.class);
// i.putExtra("profileId",ChatlistModel.get(position).getId());
startActivity(i);
}
#Override
public void onItemLongClick(View view, int position) {
}
}));
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
page++;
getServerResponseScroll(ChatDetailActivity.this);
}
});
}
// Adapter for chat
public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ViewHolder> {
private ArrayList<ChatDetailModel> chatDetailModels;
private Context context;
public ChatAdapter(Context context, ArrayList<ChatDetailModel> chatDetailModels) {
this.context = context;
this.chatDetailModels = chatDetailModels;
}
#Override
public ChatAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.chat_lsit_row, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
if (chatDetailModels.get(position).getFrom_username().equalsIgnoreCase(mDataPref.getUsername())) {
viewHolder.messageTextRight.setText(chatDetailModels.get(position).getMessage());
viewHolder.chatLeftLayout.setVisibility(View.GONE);
if (mDataPref.getProfilePicFullUrl().equals("null") || mDataPref.getProfilePicFullUrl().equals("")) {
viewHolder.fromImageView.setImageResource(R.drawable.default_profile_pic);
} else {
Picasso.with(context).load(mDataPref.getProfilePicFullUrl()).placeholder(R.drawable.default_profile_pic).transform(new CircleTransform()).resize(40, 40).into(viewHolder.fromImageView);
}
} else {
viewHolder.messageTextLeft.setText(chatDetailModels.get(position).getMessage());
viewHolder.chatRightLayout.setVisibility(View.GONE);
if (toProfilePic.equals("null") || toProfilePic.equals("")) {
viewHolder.toImageView.setImageResource(R.drawable.default_profile_pic);
} else {
Picasso.with(context).load(toProfilePic).placeholder(R.drawable.default_profile_pic).transform(new CircleTransform()).resize(40, 40).into(viewHolder.toImageView);
}
}
}
#Override
public int getItemCount() {
return chatDetailModels.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private LinearLayout chatLeftLayout;
private ImageView toImageView;
private TextView messageTextLeft;
private LinearLayout chatRightLayout;
private TextView messageTextRight;
private ImageView fromImageView;
public ViewHolder(View view) {
super(view);
chatLeftLayout = (LinearLayout) view.findViewById(R.id.chatLeftLayout);
toImageView = (ImageView) view.findViewById(R.id.toImageView);
messageTextLeft = (TextView) view.findViewById(R.id.message_text_left);
chatRightLayout = (LinearLayout) view.findViewById(R.id.chatRightLayout);
messageTextRight = (TextView) view.findViewById(R.id.message_text_right);
fromImageView = (ImageView) view.findViewById(R.id.fromImageView);
}
}
}
}
From onSaveInstanceState documentation:
Called when the LayoutManager should save its state. This is a good time to save your
* scroll position, configuration and anything else that may be required to restore the same
* layout state if the LayoutManager is recreated.
* RecyclerView does NOT verify if the LayoutManager has changed between state save and
* restore. This will let you share information between your LayoutManagers but it is also
* your responsibility to make sure they use the same parcelable class.
To get current state of recyclerview:
private Parcelable recyclerViewState = recyclerView.getLayoutManager().onSaveInstanceState();
to restore saved instance:
recyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState);

Categories

Resources