i want to make app With Rest Api and Retrofit. i want to load Random posts when user pull down the RecyclerView, i made it but one thing that is annoying, when i load Random posts. it display after the first 10 posts, i mean after home page's 10 posts but i want to clear the old posts and display random posts from row 1.
the code i am using for scroll up
else if (!recyclerView.canScrollVertically(-1) && dy < 0)
{
yourURL1 = baseURL + baseModel + "&orderby=rand&page=" + pageNo++;
getRetrofit1();
}
Retrofit
try {
List<Model> list = new ArrayList<>();
Call<List<WPPost>> call = service.getPostInfo( yourURL);
call.enqueue(new Callback<List<WPPost>>() {
#Override
public void onResponse(Call<List<WPPost>> call, Response<List<WPPost>> response) {
Log.d("==>>", " response "+ response.body());
mListPost = response.body();
progressBar.setVisibility(View.GONE);
if (response.body() != null) {
for (int i = 0; i < response.body().size(); i++ ) {
Log.d("==>>", " title " + response.body().get(i).getTitle().getRendered() + " " +
response.body().get(i).getId());
String tempdetails = String.valueOf((Html.fromHtml(response.body().get(i).getExcerpt().getRendered().toString())));
tempdetails = tempdetails.replace("<p>", "");
tempdetails = tempdetails.replace("</p>", "");
tempdetails = tempdetails.replace("[…]", "");
list.add(new Model(String.valueOf((Html.fromHtml(response.body().get(i).getTitle().getRendered()))),
tempdetails, response.body().get(i).getPostViews().toString(),
response.body().get(i).getImages().getMedium(),response.body().get(i).getContent().getRendered()));
}
if (loading){
loading = false;
adapter.showHideProgress(false);
}
adapter.addItemsToList(list);
progressBar.setVisibility(View.GONE);
} else {
progressBar.setVisibility(View.GONE);
}
}
#Override
public void onFailure(Call<List<WPPost>> call, Throwable t) {
}
});
}catch (Exception exception){
Log.d("tisha==>>"," "+exception.getLocalizedMessage());
}
In adapter
void addItemsToList(List<Model> newItems){
if (dataset.isEmpty()){
dataset.addAll(newItems);
notifyDataSetChanged();
Log.d("tisha==>>","First time List size = "+dataset.size());
}else {
int lastItemPosition = dataset.size() -1;
Log.d("tisha==>>","Old list size = "+dataset.size()+ "Last Item position= "+lastItemPosition);
dataset.addAll(newItems);
Log.d("tisha==>>","Update List size = "+dataset.size());
notifyItemRangeInserted(lastItemPosition,newItems.size());
}
}
how can i clear list ?
once this list is set you are adding items to list , you have to remove elements first notify item ranged removed then add new and update on notify item inserted
void addItemsToList(List<Model> newItems)
{ if (dataset.isEmpty())
{ dataset.addAll(newItems);
notifyDataSetChanged();
Log.d("tisha==>>","First time List size = "+dataset.size());
}
else
{
int lastItemPosition = dataset.size() -1;
Log.d("tisha==>>","Old list size = "+dataset.size()+ "Last Item position= "+lastItemPosition); dataset.addAll(newItems);
Log.d("tisha==>>","Update List size = "+dataset.size()); notifyItemRangeInserted(lastItemPosition,newItems.size()); } }
Related
I can display the information of my phone application but I am restricted to display only six.
I would like to know how to proceed to display the rest of the elements ( i have a list of 17 elements).
For the moment I use the first and last columns of my Template to do an invalidate() and display the previous or next items of my list
public Template onGetTemplate() {
ListTemplate.Builder templateBuilder = new ListTemplate.Builder();
ItemList.Builder sectionABuilder = new ItemList.Builder();
if(compteur < 4 ) {
try {
if (DataMgr.getInstance().getDataListAdress().size() > 0 && compteur < DataMgr.getInstance().getDataListAdress().get(0).length) {
for (int i = compteur; i < compteur + 5; i++) {
System.out.println("////Test + " + DataMgr.getInstance().getDataListAdress().get(0)[i]);
System.out.println("////TestLength + " + DataMgr.getInstance().getDataListAdress().get(0).length);
sectionABuilder.addItem(buildRow(DataMgr.getInstance().getDataListAdress().get(0)[i]));
}
}
sectionABuilder.addItem(buildRowClick("Suivant"));
templateBuilder.addSectionedList(
SectionedItemList.create(sectionABuilder.build(), "Header"));
} catch (Exception e) {
CarToast.makeText(getCarContext(), "No more", CarToast.LENGTH_SHORT).show();
}
} else {
sectionABuilder.addItem(buildRowClickPrecedent("Precedent"));
try {
if (DataMgr.getInstance().getDataListAdress().size() > 0 && compteur < DataMgr.getInstance().getDataListAdress().get(0).length) {
for (int i = compteur; i < compteur + 4; i++) {
System.out.println("////Test + " + DataMgr.getInstance().getDataListAdress().get(0)[i]);
System.out.println("////Test +" + DataMgr.getInstance().getDataListAdress().get(0).length);
sectionABuilder.addItem(buildRow(DataMgr.getInstance().getDataListAdress().get(0)[i]));
}
}
sectionABuilder.addItem(buildRowClick("Suivant"));
templateBuilder.addSectionedList(
SectionedItemList.create(sectionABuilder.build(), "Header"));
} catch (Exception e) {
CarToast.makeText(getCarContext(), "No more", CarToast.LENGTH_SHORT).show();
}
}
return templateBuilder
.setHeaderAction(Action.PAN)
.setTitle("ok")
.build();
}
#NonNull
private Row buildRow(String data) {
return new Row.Builder()
.setTitle(data)
.build();
}
#NonNull
private Row buildRowClick(String data) {
return new Row.Builder()
.setOnClickListener(new OnClickListener() {
#Override
public void onClick() {
compteur += 4;
invalidate();
}
})
.setTitle(data)
.build();
}
You can't use it like this. Use ConstraintManager.class.
Lists are limited by unit you have in a car. But there is special API to handle this.
Check ConstraintManager:
int listLimit = Math.min(MAX_LIST_ITEMS,
getCarContext().getCarService(ConstraintManager.class).getContentLimit(
ConstraintManager.CONTENT_LIMIT_TYPE_LIST));
Docs: https://developer.android.com/reference/androidx/car/app/constraints/ConstraintManager
You can take this limit count and interate your list only based on this number.
Refer the image
I want to match elements of favourite_city with options and if match found set favourite_city list as topmost position in options with its own content.
First ArrayList:
favourite_city=["Hyderabad","Bangalore"]
Second ArrayList:
options=["Nashik","Hyderabad","Mumbai","Bangalore","Chennai","Pune"]
Result:
options=["Hyderabad","Bangalore","Nashik","Hyderabad","Mumbai","Bangalore","Chennai","Pune"]
DocumentReference docRef5 = FirebaseFirestore.getInstance().collection("admin").document("users_profile").collection("dynamic_profile").document("city");
docRef5.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document != null) {
//-----------code for loading array item from firebase to spinner view-----------------
final List<String> group = (List<String>) document.get("favourite_city");
Log.d(TAG, "favourite city list data: " + group);
final List<String> group1 = (List<String>) document.get("options");
Log.d(TAG, "options list data: " + group1);
cityAdapter = new ArrayAdapter<String>(AdminSetting.this, android.R.layout.simple_spinner_item, group1);
cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
citySpinner.setAdapter(cityAdapter);
StringBuilder str = new StringBuilder();
for (int i = 0; i < group.size(); i++) {
if (i >= 0)
str = str.append(group.get(i));
String searchedItem = str.toString();
Log.d(TAG, "result " + searchedItem);
int itemPosition = cityAdapter.getPosition(searchedItem);
for(int j=0;j<=i;j++) {
if (itemPosition == -1) {
String message = searchedItem + " : Item not found.";
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
} else {
String message = searchedItem + " : Item found and selected.";
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
citySpinner.setSelection(itemPosition);
}
}
Log.d(TAG, "after appending " + str);
}
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
In order to put in the first positions the favourites cities, you need to know if they are contained in the cities list.
Check this code as an example:
ArrayList<String> favourites = new ArrayList<>(Arrays.asList("city1", "city2"));
ArrayList<String> cities = new ArrayList<>(Arrays.asList("city3", "city4", "city1", "city2"));
for (String favCity : favourites) {
if (cities.contains(favCity)) {
cities.add(favourites.indexOf(favCity), favCity);
}
}
System.out.println(cities);
This will print the following:
[city1, city2, city3, city4, city1, city2]
If you want to remove the duplicated favourites cities to keep only them in the first positions, you should add this line before adding it to the list.
cities.remove(favCity);
And it will return:
[city1, city2, city3, city4]
First of all your question is not clear
If you want to merge two arraylist you need to use below code
favourite_city.addAll(options) // or Either way
If you want to find matches some you need to do like below
public String getUserId(ArrayList<User> newUsers, ArrayList<User> oldUsers, String email) {
String userId = null;
for (User user1 : newUsers) {
if (user1.email.equals(email)) {
userId = user1.uid;
break;
}
}
if(userId == null){
for (User user2 : oldUsers) {
if (user2.email.equals(email)) {
userId = user2.uid;
break;
}
}
}
return userId;
}
I have struggled to load more items on listview after calling notifyDataSetChanged() method
Here is the code block for setting user scroll action on listview
lv = (ListView) getActivity().findViewById(R.id.list);
adapter = new ItemListAdapter(getActivity(), getList(), 2);
progressDialog.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
lv.setAdapter(adapter);
progressDialog.dismiss();
adapter.notifyDataSetChanged();
}
}, SPLASH_TIME_OUT);
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
userScrolled = true;
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (userScrolled) {
userScrolled = false;
progressDialog.getWindow().setGravity(Gravity.BOTTOM);
progressDialog.show();
updateListView();
}
}
});
And here is my updateListView method:
private void updateListView() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (appPreference.getLoadStatus().equals("0")) {
for (int i = 0; i < getListMore().size(); i++) {
Log.i("MORE VALUES", "" + getListMore().get(i));
getList().add(getListMore().get(i));
}
appPreference.saveLoadStatus("1");
}
progressDialog.dismiss();
adapter.notifyDataSetChanged();
}
}, 100);
}
Here is my getList() method
public List<ItemList> getList() {
ContentResolver cr = getActivity().getContentResolver();
String where = Products.SYNCSTATUS + " != 3";
Cursor c = cr.query(Products.BASEURI, null, where, null, Products.ID + " DESC");
list = new ArrayList<ItemList>();
try {
if (c.getCount() > 0) {
c.moveToFirst();
do {
int colN = c.getColumnIndex(Products.PRODUCT);
int colP = c.getColumnIndex(Products.ON_HAND);
int colI = c.getColumnIndex(Products.ID);
int colD = c.getColumnIndex(Products.SKU);
int colPr = c.getColumnIndex(Products.PRICE);
int colUp = c.getColumnIndex(Products.UPDATE);
String n = c.getString(colNad);
String p = c.getString(colPle);
long i = c.getLong(colIMEI);
String d = c.getString(colDec);
String pr = c.getString(colProd);
String upd = c.getString(colUpdated);
if (!Validating.areSet(upd))
upd = getString(R.string.strnever);
if (tabletsize) {
list.add(new ItemList(n.toUpperCase(Locale.getDefault()), pr, p, i,
d, upd));
} else {
list.add(new ItemList(getString(R.string.strproduct).toUpperCase(Locale.getDefault()) + ": " +
n.toUpperCase(Locale.getDefault()),
getString(R.string.strprice).toUpperCase(Locale.getDefault()) + ": " +
pr.toUpperCase(Locale.getDefault()),
getString(R.string.strtotalqty).toUpperCase(Locale.getDefault()) + ": " + p, i,
getString(R.string.strsku).toUpperCase(Locale.getDefault()) + ": " + d,
getString(R.string.strlastsell).toUpperCase(Locale.getDefault()) + ": " + upd));
}
} while (c.moveToNext());
} else {
String n = getString(R.string.strnodata).toUpperCase(Locale.getDefault());
String p = " ";
long i = 0;
String d = null;
list.add(new ItemList(n, "", p, i, d));
}
} finally {
if (c != null) {
c.close();
}
}
return list;
}
My intention is to load more items using getListMore() method which load data from database, add them into getList() method which returns List<ItemList>
The problem comes when i scroll the listview there is no new data loaded onto it ,the logs shows the
Log.i("MORE VALUES", "" + getListMore().get(i)); returned the data from database but no data has been shown on listview.
Can anyone help with the issue as why the data is not loaded and how to fix it?
Thanks
Can you try changing:
new Handler().postDelayed(new Runnable() {
to:
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
The method adapter.notifyDataSetChanged(); needs to be called from the main thread only.
You are actually fetching the data, adding it into list with getList() but not setting that list. you probably need to setlist() with new values.
Something like, setList(new updated list here) and then adapter.notifyDataSetChanged()
you need to make getList() more clear, see every time you get getList() and add new item in it, it reinstanitate the list, add the old items in it which you have added veru first time. better to make a change the method something like this.
public List<ItemList> getList() {
if(list != null || list.size() > 0) {
return list;
}
ContentResolver cr = getActivity().getContentResolver();
String where = Products.SYNCSTATUS + " != 3";
Cursor c = cr.query(Products.BASEURI, null, where, null, Products.ID + " DESC");
list = new ArrayList<ItemList>();
try {
if (c.getCount() > 0) {
c.moveToFirst();
do {
int colN = c.getColumnIndex(Products.PRODUCT);
int colP = c.getColumnIndex(Products.ON_HAND);
int colI = c.getColumnIndex(Products.ID);
int colD = c.getColumnIndex(Products.SKU);
int colPr = c.getColumnIndex(Products.PRICE);
int colUp = c.getColumnIndex(Products.UPDATE);
String n = c.getString(colNad);
String p = c.getString(colPle);
long i = c.getLong(colIMEI);
String d = c.getString(colDec);
String pr = c.getString(colProd);
String upd = c.getString(colUpdated);
if (!Validating.areSet(upd))
upd = getString(R.string.strnever);
if (tabletsize) {
list.add(new ItemList(n.toUpperCase(Locale.getDefault()), pr, p, i,
d, upd));
} else {
list.add(new ItemList(getString(R.string.strproduct).toUpperCase(Locale.getDefault()) + ": " +
n.toUpperCase(Locale.getDefault()),
getString(R.string.strprice).toUpperCase(Locale.getDefault()) + ": " +
pr.toUpperCase(Locale.getDefault()),
getString(R.string.strtotalqty).toUpperCase(Locale.getDefault()) + ": " + p, i,
getString(R.string.strsku).toUpperCase(Locale.getDefault()) + ": " + d,
getString(R.string.strlastsell).toUpperCase(Locale.getDefault()) + ": " + upd));
}
} while (c.moveToNext());
} else {
String n = getString(R.string.strnodata).toUpperCase(Locale.getDefault());
String p = " ";
long i = 0;
String d = null;
list.add(new ItemList(n, "", p, i, d));
}
} finally {
if (c != null) {
c.close();
}
}
return list;
}
I am developing an app in which I have a listview in which 5 data are visible to user.when I scroll bottom of listview and a progress bar at the bottom of listview is visible to me and server request is send at this point and 5 more data are added in data set, Here I want to make this new data visible to user when added in data set. i.e. move scroll position on new data set.
code:-
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && bBottomOfView) {
Log.i("Listview", "scrolling stopped...");
if (NetworkUtil.isConnected(getActivity())) {
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// convert int value to string
sz_LastCount = String.valueOf(CLastCountData.getInstance().getS_szLastCount());// convert int value to string /////
Log.e(TAG, "Last Count::" + sz_LastCount);
Log.e(TAG, "Record count::" + sz_RecordCount);
loadmoreData();
} else {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "No internet connection available", getActivity());
m_ListView.removeFooterView(mFooter);
}
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, m_DealListingURL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, "Server Response:-" + response);
if (mSwipeRefresh.isRefreshing()) {
mSwipeRefresh.setRefreshing(false);
}
try {
int nResultCodeFromServer = Integer.parseInt(response.getString("resultcode"));
if (nResultCodeFromServer == CStaticVar.m_kTRANSACTION_SUCCESS) {
JSONArray posts = response.optJSONArray("dealList");// GETTING DEAL LIST
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.getJSONObject(i);// GETTING DEAL AT POSITION AT I
item = new CDealAppDatastorage();// object create of DealAppdatastorage
item.setM_szHeaderText(post.getString("dealname"));//getting deal name
item.setM_szsubHeaderText(post.getString("dealcode"));// getting deal code
item.setM_szDealValue(post.getString("dealvalue"));
if (!s_oDataset.contains(item)) {
s_oDataset.add(item);
}
}
m_oAdapter.notifyDataSetChanged();
arrayCount = posts.length();
int add = CLastCountData.getInstance().getS_szLastCount() + arrayCount;
CLastCountData.getInstance().setS_szLastCount(add);
Log.e(TAG, "ArrayCount::" + arrayCount);
m_ListView.removeFooterView(mFooter);
}
Just use listView.setSelection(position of item you want to scroll)
Following code will help you to maintain the scroll position of your listview:
First off all you have to get the current child position of listview from below code:
// this code should be written before updating adapter in your listview
int lastViewedPosition = listView.getFirstVisiblePosition();
//get offset of first visible view
View v = listView.getChildAt(0);
int topOffset = (v == null) ? 0 : v.getTop();
then after updating your data in adapter you have to call this:
listView.setSelectionFromTop(lastViewedPosition, topOffset);
Like in your code:
Log.i(TAG, "Server Response:-" + response);
if (mSwipeRefresh.isRefreshing()) {
mSwipeRefresh.setRefreshing(false);
}
try {
int nResultCodeFromServer = Integer.parseInt(response.getString("resultcode"));
if (nResultCodeFromServer == CStaticVar.m_kTRANSACTION_SUCCESS) {
int lastViewedPosition = listView.getFirstVisiblePosition();
//get offset of first visible view
View v = listView.getChildAt(0);
int topOffset = (v == null) ? 0 : v.getTop();
JSONArray posts = response.optJSONArray("dealList");// GETTING DEAL LIST
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.getJSONObject(i);// GETTING DEAL AT POSITION AT I
item = new CDealAppDatastorage();// object create of DealAppdatastorage
item.setM_szHeaderText(post.getString("dealname"));//getting deal name
item.setM_szsubHeaderText(post.getString("dealcode"));// getting deal code
item.setM_szDealValue(post.getString("dealvalue"));
if (!s_oDataset.contains(item)) {
s_oDataset.add(item);
}
}
m_oAdapter.notifyDataSetChanged();
listView.setSelectionFromTop(lastViewedPosition, topOffset);
arrayCount = posts.length();
int add = CLastCountData.getInstance().getS_szLastCount() + arrayCount;
CLastCountData.getInstance().setS_szLastCount(add);
Log.e(TAG, "ArrayCount::" + arrayCount);
m_ListView.removeFooterView(mFooter);
I have retrieve data from json and set in onbind in recycle list view like
how can add value in spinner product.setQuantity(quantity); for each row
private ArrayList<ProductBySubCategory> parseJSONResponse(JSONArray response) {
ArrayList<ProductBySubCategory> listProducts = new ArrayList<ProductBySubCategory>();
if (response != null && response.length() > 0) {
try {
StringBuilder data = new StringBuilder();
JSONArray jsonArray = response;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String pName = jsonObject.getString(KEY_NAME);
String pPrice = jsonObject.getString(KEY_PRICE);
String pUrlThumbnail = AppConfig.URL_THUBMNAIL_BASE + jsonObject.getString(KEY_THUMBNAIL);
String pSNo = jsonObject.getString(KEY_SNO);
String sellerName = jsonObject.getString(KEY_SELLER_NAME);
String qrValue = jsonObject.getString(KEY_QRVALUE);
String quantity = jsonObject.getString(KEY_QUANTITY);
data.append(pName + " " + pPrice + " " + pUrlThumbnail + " " + pSNo + " " + sellerName +" "+qrValue+ " "+quantity+ "\n");
ProductBySubCategory product = new ProductBySubCategory();
product.setpName(pName);
product.setSellerName(sellerName);
product.setQrValue(qrValue);
product.setpPrice(getString(R.string.material_icon_rupees)+pPrice);
product.setpUrlThumbnail(pUrlThumbnail);
product.setpSNo(pSNo);
product.setQuantity(quantity);
listProducts.add(product);
}
Log.d("Lifecycle2", listProducts.toString());
} catch (JSONException e) {
Log.d("Lifecycle", "Inside JSON EXCEPTION: " + e);
}
}
return listProducts;
}
In above code i want to quantity in spinner for each row.
I have set value in adapter in below code but I didn't set quantity in text view because I want to this value set in spinner and I have array value for spinner for each product in list and now what should I do for set value in spinner like this image for each item if possible please give me some code.
#Override
public void onBindViewHolder(final ViewHolderProducts holder, int position) {
ProductBySubCategory currentProduct = productArrayList.get(position);
holder.productName.setText(currentProduct.getpName());
holder.sellerName.setText(currentProduct.getSellerName());
holder.qrValue.setText(currentProduct.getQrValue());
holder.productPrice.setText(currentProduct.getpPrice());
holder.btnBuy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
RelativeLayout relativeLayout = (RelativeLayout) view.getParent();
TextView textView = (TextView) relativeLayout.findViewById(R.id.qrValue);
String qrText = (String) textView.getText();
Log.d("Abhinav", "qrValue" +qrText);
if (buyItemClickListener != null) {
buyItemClickListener.buttonClicked(qrText);
}
}
});
String urlThumbnail = currentProduct.getpUrlThumbnail();
if (urlThumbnail != null) {
imageLoader.get(urlThumbnail, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean b) {
holder.productThumbnail.setImageBitmap(response.getBitmap());
}
#Override
public void onErrorResponse(VolleyError volleyError) {
}
});
}
}