Empty ListView after reshresh SwipeRefreshLayout - android

I try to use SwipeRefreshLayout with ListView.
ListView and ArrayAdapter works well when i try to load data first time.
But, when i try to refresh - i have empty ListView (but array have data).
Here some code:
MainActivity:
final SwipeRefreshLayout swipe= (SwipeRefreshLayout) findViewById(R.id.swipe);
_loader=new RssLoader(getApplicationContext(),this,swipe);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
_loader.loadFeeds();
}
});
Loader class:
public void loadFeeds() {
String[] urlArr = {"http://www.example.com/export/news.xml"};
new RssReader(_context)
.showDialog(false)
.urls(urlArr)
.parse(new OnRssLoadListener() {
#Override
public void onSuccess(List<RssItem> rssItems) {
ArrayList<String> titles=new ArrayList<>();
if(rssItems.size()!=0)
{
titles.clear();
RssItems.clear();
}
Toast.makeText(_context, rssItems.get(0).getTitle(), Toast.LENGTH_SHORT).show();
for (RssItem item:rssItems
) {
RssItems.add(item);
titles.add(item.getTitle());
Log.i("Item:",item.getTitle());
}
ArrayAdapter<String> adapter=new ArrayAdapter<String>(_context,R.layout.support_simple_spinner_dropdown_item,titles);
ListView listNewNews= (ListView) _activity.findViewById(R.id.listViewNews);
listNewNews.setAdapter(adapter);
if(_swipeRefresh!=null) {
_swipeRefresh.setRefreshing(false);
}
}
#Override
public void onFailure(String message) {
Toast.makeText(_context, "Error: "+message, Toast.LENGTH_SHORT).show();
}
});
}

Related

data not showing in recyclerview using notifyDataSetChanged in Retrofit but works in volley

I always use the approach to show the data in recyclerview using Volley is to create Adapter in Oncreate method and then notify after receiving response from volley using notifyDataSetChanged.
I tried to use the same approach in Retrofit but data is not showing in Recyclerview,but if instead of setting adapter in Oncreate method if I set Adapter in retrofit after receiving response from Retrofit then it works perfectly
My question is that
(1) why the data is not showing in Retrofit if i create adapter in Oncreate am i doing something wrong?
(2)Is it a good approach to create adapter in Oncreate and then notifying it after receiving response or shoud I set adapter after getting response?
If I set adapter after getting response like this
#Override
public void onResponse(Call<SubCatModelList> call, Response<SubCatModelList> response) {
Log.d("subcategoryJsonResponse", String.valueOf(response));
Gson gson = new Gson();
String successResponse = gson.toJson(response.body());
Log.d("aaaaaa", String.valueOf(successResponse));
if (response.isSuccessful()) {
subCatModel =response.body().getSubCategories();
Log.d("asaaaaaaa", String.valueOf(subCatModel));
subCategoryAdapter = new SubCategoryAdapter(BinaryCommissionActivity.this, subCatModel);
FixedGridLayoutManager manager = new FixedGridLayoutManager();
manager.setTotalColumnCount(1);
rvBinaryCommission.setLayoutManager(manager);
rvBinaryCommission.setAdapter(subCategoryAdapter);
rvBinaryCommission.addItemDecoration(new DividerItemDecoration(BinaryCommissionActivity.this, DividerItemDecoration.VERTICAL));
}
then every time this line initializes adapter and creates object whenver api hits and i think its a bad approach
subCategoryAdapter = new
SubCategoryAdapter(BinaryCommissionActivity.this, subCatModel);
public class BinaryCommissionActivity extends AppCompatActivity {
int scrollX = 0;
List<SubCatModel> subCatModel = new ArrayList<>();
SubCategoryAdapter subCategoryAdapter;
VolleyCustomClass volleyCustomClass;
#BindView(R.id.toolbarcustom) Toolbar toolbarcustom;
#BindView(R.id.spinner_binary_commission) Spinner spinnerBinaryCommission;
#BindView(R.id.searchViewBinary) SearchView searchViewBinary;
#BindView(R.id.headerScroll) HorizontalScrollView headerScroll;
#BindView(R.id.rvBinaryCommission) RecyclerView rvBinaryCommission;
#BindView(R.id.swipeRefreshBinaryList) SwipeRefreshLayout swipeRefreshBinaryList;
private AlertDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_binary_commission);
ButterKnife.bind(this);
toolbarcustom = findViewById(R.id.toolbarcustom);
setSupportActionBar(toolbarcustom);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Binary Commission");
volleyCustomClass = new VolleyCustomClass(getApplicationContext());
dialog = new SpotsDialog.Builder().setContext(this)
.setMessage("Loading...")
.setCancelable(false).build();
spinnerData();
setUpRecyclerView();
prepareClubData();
recyclerviewScrollListener();
searchFilter();
swipeRefreshBinaryList.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
if (!InternetUtils.checkForInternet(getApplicationContext())) {
swipeRefreshBinaryList.setRefreshing(false);
FancyToast.makeText(getApplicationContext(), "No Internet Connection", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show();
} else {
prepareClubData();
}
}
});
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return super.onSupportNavigateUp();
}
/**
* Recyclerview ScrollListener
*/
private void recyclerviewScrollListener() {
rvBinaryCommission.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
scrollX += dx;
headerScroll.scrollTo(scrollX, 0);
}
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
});
}
/**
* Search Filter
*/
private void searchFilter() {
searchViewBinary.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
subCategoryAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
subCategoryAdapter.getFilter().filter(newText);
return false;
}
});
}
/**
* Adding data to spinner
*/
private void spinnerData() {
List<String> show_entries = new ArrayList<String>();
show_entries.add("5");
show_entries.add("10");
show_entries.add("15");
show_entries.add("20");
show_entries.add("All");
ArrayAdapter<String> dataAdapterShowEntries = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, show_entries);
dataAdapterShowEntries.setDropDownViewResource(R.layout.layout_spinner_item);
spinnerBinaryCommission.setAdapter(dataAdapterShowEntries);
spinnerBinaryCommission.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
Object item = adapterView.getItemAtPosition(position);
if (item != null) {
// Toast.makeText(getContext(), item.toString(), Toast.LENGTH_SHORT).show();
}
// Toast.makeText(getContext(), "Selected", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
// TODO Auto-generated method stub
}
});
}
private void prepareClubData() {
if (!InternetUtils.checkForInternet(getApplicationContext())) {
FancyToast.makeText(getApplicationContext(), "No Internet Connection", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show();
return;
} else {
dialog.show();
if (subCatModel != null) {
subCatModel.clear();
}
/**
* Volley
*/
/* volleyCustomClass.callGetServer(URLs.subcategoryURL, new VolleyCallback() {
#Override
public void onSuccess(String response) {
Log.d("subcategoryJsonResponse", response);
try {
JSONObject obj = new JSONObject(response);
JSONArray productArray = obj.getJSONArray("sub-categories");
for (int i = 0; i < productArray.length(); i++) {
JSONObject productObject = productArray.getJSONObject(i);
SubCatModel subCatModelClass = new SubCatModel();
subCatModelClass.setSubcategoriesId(productObject.getString("Subcategories-Id"));
subCatModelClass.setCategoriesId(productObject.getString("categories-Id"));
subCatModelClass.setSubcategoriesName(productObject.getString("Subcategories-Name"));
subCatModel.add(subCatModelClass);
Log.d("subCategoryArraylist", String.valueOf(subCatModel));
}
dialog.dismiss();
subCategoryAdapter.notifyDataSetChanged();
swipeRefreshBinaryList.setRefreshing(false);
} catch (JSONException e) {
e.printStackTrace();
dialog.dismiss();
}
}
#Override
public void onError(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
swipeRefreshBinaryList.setRefreshing(false);
}
});*/
/**
* Retrofit
*/
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<SubCatModelList> call = apiService.getList();
call.enqueue(new Callback<SubCatModelList>() {
#Override
public void onResponse(Call<SubCatModelList> call, Response<SubCatModelList> response) {
Log.d("subcategoryJsonResponse", String.valueOf(response));
Gson gson = new Gson();
String successResponse = gson.toJson(response.body());
Log.d("aaaaaa", String.valueOf(successResponse));
if (response.isSuccessful()) {
subCatModel =response.body().getSubCategories();
Log.d("asaaaaaaa", String.valueOf(subCatModel));
}
dialog.dismiss();
subCategoryAdapter.notifyDataSetChanged();
swipeRefreshBinaryList.setRefreshing(false);
}
#Override
public void onFailure(Call<SubCatModelList> call, Throwable t) {
swipeRefreshBinaryList.setRefreshing(false);
}
});
}
}
/**
* Handles RecyclerView for the action
*/
private void setUpRecyclerView() {
subCategoryAdapter = new SubCategoryAdapter(BinaryCommissionActivity.this, subCatModel);
FixedGridLayoutManager manager = new FixedGridLayoutManager();
manager.setTotalColumnCount(1);
rvBinaryCommission.setLayoutManager(manager);
rvBinaryCommission.setAdapter(subCategoryAdapter);
rvBinaryCommission.addItemDecoration(new DividerItemDecoration(BinaryCommissionActivity.this, DividerItemDecoration.VERTICAL));
}
}
Instead of initializing adapter everytime, you can use: (inside adapter class)
public void setItems(List<String> myList) { // Let's say it's List of Strings
this.myList = myList;
notifyDataSetChanged();
}
And everytime you change List with your data to display (in your case inside of onResponse()) you just call 'setItems()' on your adapter.

Update RecyclerView items in android

I want to update the items inside RecyclerView using sending request to API and a timer.
This is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
get_items();
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
synchronized public void run() {
get_items();
}
}, TimeUnit.SECONDS.toMillis(3), TimeUnit.SECONDS.toMillis(3));
}
public void get_items(){
Client client = ServiceGenerator.createService(Client.class,getBaseContext());
final Call<List<Items>> call = Client.getItems("items");
call.enqueue(new Callback<List<Items>>() {
#Override
public void onResponse(Call<List<Items>> call, Response<List<Items>> response) {
List<Items> items = response.body();
ItemsAdapter adapter = new ItemsAdapter(items);
recyclerView = findViewById(R.id.chatrecycler);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(Activity.this, LinearLayoutManager.VERTICAL,true));
}
#Override
public void onFailure(Call<List<Items>> call, Throwable t) {
}
});
}
And every 3 seconds the list updates but it starts from beginning.
What should I do to keep the position of the list during update??
You should not create new RecyclerView object in every api call. Also you are assigning adapter and LayoutManager with yout RecycletView in each call.
You just need to setAdapter with your RecycletView once and then second time just add new data in your adapter list and notify your adapter to refresh.
Please check below code.
private ItemsAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
recyclerView = findViewById(R.id.chatrecycler);
recyclerView.setLayoutManager(new LinearLayoutManager(SingleChat.this, LinearLayoutManager.VERTICAL,true));
get_items();
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
synchronized public void run() {
get_items();
}
}, TimeUnit.SECONDS.toMillis(3), TimeUnit.SECONDS.toMillis(3));
}
public void get_items(){
Client client = ServiceGenerator.createService(Client.class,getBaseContext());
final Call<List<Items>> call = Client.getItems("items");
call.enqueue(new Callback<List<Items>>() {
#Override
public void onResponse(Call<List<Items>> call, Response<List<Items>> response) {
List<Items> items = response.body();
if(adapter == null) {
adapter = new ItemsAdapter(items);
recyclerView.setAdapter(adapter);
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.addMoreItems(items);
adapter.notifyDatasetChanged();
}
});
}
}
#Override
public void onFailure(Call<List<SingleChatItem>> call, Throwable t) {
}
});
}
Add one method in your ItemsAdapter.java like,
public void addMoreItems(List<Items> items) {
this.items = items;
}
I have not tested this code myself.But it must work.Let me know if it doesn't.
final ItemsAdapter adapter = null;
ArrayList<Items> items = null;
recyclerView = findViewById(R.id.chatrecycler);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(Activity.this, LinearLayoutManager.VERTICAL,true));
call.enqueue(new Callback<List<Items>>() {
#Override
public void onResponse(Call<List<Items>> call, Response<List<Items>> response) {
List<Items> newItems = response.body();
if(adapter == null){
adapter = new ItemsAdapter(items);
items.addAll(newItems);
}else{
int i = 0;
for(Item item : items){
int index = newItems.indexOf(item);
item.stuff = newItems.get(index).stuff;
adapter.notifyItemChanged(i);
i++;
}
}
}
#Override
public void onFailure(Call<List<Items>> call, Throwable t) {
}
});

Swipe/Pull to Refresh for Android RecyclerView

I have created an app to get RSS Feed from XML file and show it in a recyclerview within card views. I want to implement the Pull to refresh to load the data.
where exactly the method supposed to be ?
my main activity :
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
//Call Read rss asyntask to fetch rss
try {
ReadRss readRss = new ReadRss(this, recyclerView);
readRss.execute();
}catch (Exception e) {
Toast.makeText(getApplicationContext(), "There's a problem", Toast.LENGTH_LONG);
}
}
}
and this is ReadRss class :
public class ReadRss extends AsyncTask<Void, Void, Void> {
Context context;
String address = "http://karary-001-site1.htempurl.com/XMLFile1.xml";
ProgressDialog progressDialog;
ArrayList<FeedItem> feedItems;
RecyclerView recyclerView;
URL url;
public ReadRss(Context context, RecyclerView recyclerView) {
this.recyclerView = recyclerView;
this.context = context;
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("loading....");
}
//before fetching of rss statrs show progress to user
#Override
protected void onPreExecute() {
progressDialog.show();
super.onPreExecute();
}
//This method will execute in background so in this method download rss feeds
#Override
protected Void doInBackground(Void... params) {
//call process xml method to process document we downloaded from getData() method
ProcessXml(Getdata());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
FeedsAdapter adapter = new FeedsAdapter(context, feedItems);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.addItemDecoration(new VerticalSpace(20));
recyclerView.setAdapter(adapter);
}
pullToRefresh method :
final SwipeRefreshLayout pullToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
//refresh code
pullToRefresh.setRefreshing(false);
}
});
where exactly the method supposed to be ?
First set pullToRefresh.setRefreshing(true); if its not working than try below code
pullToRefresh.post(new Runnable() {
#Override
public void run() {
pullToRefresh.setRefreshing(true);
}
});
Here is what you can do
pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
//refresh code
ReadRss readRss = new ReadRss(this, recyclerView);
readRss.execute();
}
});
and then in onPostExeceute()
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
pullToRefresh.setRefreshing(false); // in case of pullToRefresh
FeedsAdapter adapter = new FeedsAdapter(context, feedItems);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.addItemDecoration(new VerticalSpace(20));
recyclerView.setAdapter(adapter);
}
Hope this helps

How to reload Volley data to get current items from json

I have this recyclerview that loads data from a server through a json api. the Data on the server will be updated frequently so i have a "swipe to refresh" in my application. I'm using volley to get the data from the server and i want to make it in such a way that, when the user swipe to refresh, volley will reload the json data from the server so that recyclerview can display the newly added items.
This is my onSwipeListener
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
}, 3000);
}
});
This is how volley is requesting the data
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
public ArrayList<Deal> userlist;
public DealAdapter adapter;
#Override
public void onResponse(String response) {
MainActivity.userList = this.userlist;
userList = new JsonConverter<Deal>().
toArrayList(response, Deal.class);
Collections.reverse(userList);
adapter = new DealAdapter(getApplicationContext(), userList);
MainActivity.adapter= this.adapter;
recyclerView.setAdapter(adapter);
}
But i can't figure out how to refresh the volley response data when onSwipeListener is called.
this is how i add the request to Queue
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
I think the problem is that you are re-assigning the Activity adapter, but never setting that new adapter back onto the Activity's RecyclerView.
Sure, you have recyclerView.setAdapter(adapter), but it is not clear where that reference came from.
Similarly, the Activity's userList is empty.
MainActivity.userList = this.userlist; // This is null
userList = new JsonConverter<Deal>(). // This should have been first
toArrayList(response, Deal.class);
So, anyways, as I was saying in the comments, static variables are really not a good way to "toss data over the Java class wall".
Let's say you have this class to handle all the Volley calls. Notice that the Response.Listener interface is passed as the parameter.
public class JsonApi {
private Context mContext;
private static JsonApi instance;
private JsonApi(Context c) { this.mContext = c; }
public static JsonApi getInstance(Context context) {
if (instance == null) instance = new JsonApi(context);
return instance;
}
public void getSomeData(Response.Listener<String> success) {
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, success);
MySingleton.getInstance(this.mContext).addToRequestQueue(stringRequest);
}
}
Now, over in the Activity or Adapter, you can get this class and re-do Volley requests whenever.
(Apologies for any typos. This is untested, but it just gives a sample of how I would layout the code).
public class MainActivity implements
SwipeRefreshLayout.OnRefreshListener,
Response.Listener<String> {
private List<Deal> userList;
private DealAdapter adapter;
private RecyclerView recyclerView;
private SwipeRefreshLayout swipeRefreshLayout;
private JsonApi api;
#Override
public void onResponse(String response) {
userList.clear();
userList.addAll(new JsonConverter<Deal>().
toArrayList(response, Deal.class));
Collections.reverse(userList);
// Handle adapter updates here
if (swipeRefreshLayout.isRefreshing()) {
swipeRefreshLayout.setRefreshing(false);
}
recyclerView.notifyDataSetChanged();
}
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// Start an API call to refresh data
api.getSomeData(MainActivity.this);
}
}, 3000);
}
#Override
protected void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_main);
api = JsonApi.getInstance(MainActivity.this);
userList = new ArrayList<Deal>();
adapter = new DealAdapter(MainActivity.this, userList);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
// set layout manager ... etc.
recyclerView.setAdapter(adapter);
api.getSomeData(MainActivity.this); // start the first call when the activity starts
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefresh);
swipeRefreshLayout.setOnRefreshListener(MainActivity.this);
}
}
Okay So this is what worked for me. I had to call StringRequest again in the OnRefreshListener with new variable so that when the user swipes, volley requests the json data again and pass it to the adapter as shown below.
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
StringRequest mrequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
public ArrayList<Deal> userlist;
public DealAdapter adapter;
#Override
public void onResponse(String response) {
MainActivity.userList = this.userlist;
userList = new JsonConverter<Deal>().
toArrayList(response, Deal.class);
Collections.reverse(userList);
adapter = new DealAdapter(getApplicationContext(), userList);
MainActivity.adapter= this.adapter;
recyclerView.setAdapter(adapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.toString());
Toast.makeText(getApplicationContext(), "Something Went wrong: " + "'" + error + "'", Toast.LENGTH_LONG).show();
}
});
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(mrequest);
adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
}, 3000);
}
});

Recyclerview not refreshing after returning to fragment

i have favorites fragment with recyclerview , the data is showing well
but when i click on a reyclerview item and remove it from favorites when pressing back to the favorites fragment is still showing in the recylerview , i know that the probleme is recyclerview is not refrishing because when i restart the app the item is removed , i tried notifydatasetchanged but its not working
here is oncreateview and onresume of the favorites fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView= inflater.inflate(R.layout.fragment_favourites, container, false);
activity=getActivity();
tinydb = new TinyDB(activity);
liststorieshits=(RecyclerView) rootView.findViewById(R.id.lsv_cat_item_fav);
liststorieshits.setLayoutManager(new LinearLayoutManager(getActivity()));
rippleView = ((RippleView) rootView.findViewById(R.id.rect_fav));
liststorieshits.setHasFixedSize(true);
liststorieshits.addItemDecoration(new VerticalDividerItemDecoration.Builder(getActivity()).build());
mAdapter=new FavoritesAdapter(getActivity(),itemsList);
liststorieshits.setAdapter(mAdapter);
progress = new ProgressDialog(getActivity());
progress.setTitle("Loading");
progress.setMessage("Wait while loading Stories");
progress.show();
RestAdapter restAdapter=new RestAdapter.Builder().setEndpoint(getString(R.string.categories_feed)).build();
final CategoriesApiInterface categoriesApiInterface=restAdapter.create(CategoriesApiInterface.class);
idlist2=tinydb.getListInt("strid");
int ab=0;
for(int i=0;i<idlist2.size();i++){
ab=idlist2.get(i);
categoriesApiInterface.getStreams3(ab, new Callback<List<Stories>>() {
#Override
public void success(List<Stories> stories, Response response) {
progress.dismiss();
if (stories == null || stories.isEmpty()) {
return;
}
for (Stories stories1 : stories) {
itemsList.add(stories1);
}
mAdapter.notifyDataSetChanged();
Log.e("Stories", "krb :" + itemsList.size());
}
#Override
public void failure(RetrofitError error) {
progress.dismiss();
Log.e("Stories", "Retrofit error " + error.getMessage());
}
});
}
return rootView;
}
#Override
public void onResume() {
super.onResume();
mAdapter.notifyDataSetChanged();
}
You may try this way to update your RecycleView:
#Override
public void onResume() {
super.onResume();
itemsList.clear();
idlist2=tinydb.getListInt("strid");
int ab=0;
for(int i=0;i<idlist2.size();i++){
ab=idlist2.get(i);
categoriesApiInterface.getStreams3(ab, new Callback<List<Stories>>() {
#Override
public void success(List<Stories> stories, Response response) {
progress.dismiss();
if (stories == null || stories.isEmpty()) {
return;
}
for (Stories stories1 : stories) {
itemsList.add(stories1);
}
mAdapter.notifyDataSetChanged();
Log.e("Stories", "krb :" + itemsList.size());
}
#Override
public void failure(RetrofitError error) {
progress.dismiss();
Log.e("Stories", "Retrofit error " + error.getMessage());
}
});
}
mAdapter = new FavoritesAdapter(getActivity(),itemsList);
liststorieshits.setAdapter(mAdapter);
}
ADDED
You may make update() for updating data in separate function, like this:
private void update() {
itemsList.clear();
idlist2=tinydb.getListInt("strid");
int ab=0;
for(int i=0;i<idlist2.size();i++){
ab=idlist2.get(i);
categoriesApiInterface.getStreams3(ab, new Callback<List<Stories>>() {
#Override
public void success(List<Stories> stories, Response response) {
progress.dismiss();
if (stories == null || stories.isEmpty()) {
return;
}
for (Stories stories1 : stories) {
itemsList.add(stories1);
}
mAdapter.notifyDataSetChanged();
Log.e("Stories", "krb :" + itemsList.size());
}
#Override
public void failure(RetrofitError error) {
progress.dismiss();
Log.e("Stories", "Retrofit error " + error.getMessage());
}
});
}
mAdapter = new FavoritesAdapter(getActivity(),itemsList);
liststorieshits.setAdapter(mAdapter);
}
And use it:
#Override
public void onResume() {
super.onResume();
update();
}
override fun onResume() {
super.onResume()
binding.mRecyclerView.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
}

Categories

Resources