I want to check some checkbox with a recieved list from a Rest Service.
Here some code.
REQUEST
private void requestOpcionais() {
OpcionalRequestHelper.opcionaisRequest(Request.Method.GET, EndpointURL.GET_OPCIONAIS, null, new Response.Listener<Opcional[]>() {
#Override
public void onResponse(Opcional[] response) {
ArrayList<Opcional> opcionalArrayList = new ArrayList<>();
opcionalArrayList.addAll(Arrays.asList(response));
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
listOpcionalAdapter = new ListOpcionalAdapter(getActivity(), opcionalArrayList, VeiculoFragment.this);
mRecyclerView.setAdapter(listOpcionalAdapter);
if (veiculo != null) {
setOpcionalVeiculoSelected(opcionalArrayList, veiculo.getOpcionais());
}
progressDialogOpcionais.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialogOpcionais.dismiss();
Toast.makeText(getActivity(), "Erro ao carregar opcionais.", Toast.LENGTH_LONG).show();
}
});
}
There is the verification if my opcional list...
private void setOpcionalVeiculoSelected(ArrayList<Opcional> opcionalArrayList, List<Opcional> opcionais) {
for (Opcional opcionalList : opcionalArrayList) {
for (Opcional opcionalVeiculo : opcionais) {
if (opcionalVeiculo.getId() == opcionalList.getId()) {
mOpcionalChecked.add(opcionalVeiculo);
}
}
}
}
How i check those "opcionais" on my recyclerview?
I resolved my issue on this way...
I've sended the array to my adapter.
if (veiculo != null) {
setOpcionalVeiculoSelected(opcionalArrayList, veiculo.getOpcionais());
listOpcionalAdapter = new ListOpcionalAdapter(getActivity(), opcionalArrayList, VeiculoFragment.this, veiculo.getOpcionais());
} else {
listOpcionalAdapter = new ListOpcionalAdapter(getActivity(), opcionalArrayList, VeiculoFragment.this, null);
}
On my onBindViewHolder() I checked if my array is not null.
onBindViewHolder()
if (opcionalsVeiculo != null) {
setOpcionalVeiculoSelected(holder, position);
}
And finally check my array and the position of my other array from adapter.
private void setOpcionalVeiculoSelected(ViewHolder holder, int position) {
for (Opcional opcional : opcionalsVeiculo) {
if (opcionals.get(position).getId() == opcional.getId()) {
holder.chb_opcional.setChecked(true);
}
}
}
Related
I am trying to implement the recycler-view-selection library in android, I have implemented most of it, but I am facing an issue when I am trying to refresh my screen. After refreshing my screen using SwipeRefresh, if I try to long press an item in my recycler view the app keeps crashing and I receive this error.
FATAL EXCEPTION: main
Process: com.quicklyservices.restaurants, PID: 4026
java.lang.IllegalArgumentException
at androidx.core.util.Preconditions.checkArgument(Preconditions.java:38)
at androidx.recyclerview.selection.DefaultSelectionTracker.anchorRange(DefaultSelectionTracker.java:288)
at androidx.recyclerview.selection.MotionInputHandler.selectItem(MotionInputHandler.java:60)
at androidx.recyclerview.selection.TouchInputHandler.onLongPress(TouchInputHandler.java:164)
at androidx.recyclerview.selection.GestureRouter.onLongPress(GestureRouter.java:97)
at android.view.GestureDetector.dispatchLongPress(GestureDetector.java:770)
at android.view.GestureDetector.-wrap0(GestureDetector.java)
at android.view.GestureDetector$GestureHandler.handleMessage(GestureDetector.java:293)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
This how I set my onRefreshListener
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
resetTracker();
getPendingCarts();
}
});
getPendingCarts method -
public void getPendingCarts()
{
swipeRefreshLayout.setRefreshing(true);
String token = SharedPrefUtil.getInstance().getApiToken(getActivity());
Call<ResponsePendingCart> call = ApiClient.getInstance().getPendingCarts(token);
call.enqueue(new Callback<ResponsePendingCart>() {
#Override
public void onResponse(Call<ResponsePendingCart> call, Response<ResponsePendingCart> response) {
try{
ResponsePendingCart pendingCart = response.body();
if(pendingCart.getStatus() == -1)
{
HelperClass.getInstance().forceLogout(getActivity());
}
else
{
List<Order> items = pendingCart.getItems();
if(items == null || items.size()==0)
{
container_no_order.setVisibility(View.VISIBLE);
rview_ongoing.setVisibility(View.INVISIBLE);
}
else
{
container_no_order.setVisibility(View.INVISIBLE);
rview_ongoing.setVisibility(View.VISIBLE);
AppData.shopCurrency = Html.fromHtml(pendingCart.getItems().get(0).getShop().getCurrencyHtmlCode()).toString();
for (Order item : items ) {
try{
List<ShopPromotion> promotions = item.getShopPromotion();
for (ShopPromotion promotionItem: promotions) {
List<FreeDishItem> dishItem = promotionItem.getFreeDish();
if (dishItem != null) {
for (int i = 0; i < dishItem.size() && dishItem.get(i) != null; i++) {
Dish orderItemListItem = new Dish();
orderItemListItem.setTitle(dishItem.get(i).getTitle());
orderItemListItem.setQuantity(dishItem.get(i).getQuantity());
orderItemListItem.setDetails(dishItem.get(i).getDetails());
orderItemListItem.setPrice(0.00);
orderItemListItem.setIsFreeDish(1);
item.getOrderItemList().add(orderItemListItem);
}
}
}
}
catch (Exception e) {
FirebaseCrashlytics.getInstance().log(e.toString());
}
}
if(listAdapter == null)
{
listAdapter = new OngoingListAdapter(getActivity(),items);
rview_ongoing.setAdapter(listAdapter);
rview_ongoing.setLayoutManager(new LinearLayoutManager(getActivity()));
int resId = R.anim.layout_animation_from_bottom;
LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(getActivity(), resId);
rview_ongoing.setLayoutAnimation(animation);
initSelectionTracker(listAdapter,rview_ongoing);
swipeRefreshLayout.setRefreshing(false);
}
else
{
OngoingListAdapter listAdapter = new OngoingListAdapter(getActivity(),items);
rview_ongoing.setAdapter(listAdapter);
rview_ongoing.setLayoutManager(new LinearLayoutManager(getActivity()));
initSelectionTracker(listAdapter,rview_ongoing);
swipeRefreshLayout.setRefreshing(false);
}
}
}
swipeRefreshLayout.setRefreshing(false);
}
catch (Exception e)
{
container_no_order.setVisibility(View.VISIBLE);
swipeRefreshLayout.setRefreshing(false);
FirebaseCrashlytics.getInstance().log(e.toString());
}
}
#Override
public void onFailure(Call<ResponsePendingCart> call, Throwable t) {
swipeRefreshLayout.setRefreshing(false);
}
});
}
initSelectionTracker works as such -
public void initSelectionTracker(OngoingListAdapter adapter,RecyclerView recyclerView){
OngoingListItemKeyProvider keyProvider = new OngoingListItemKeyProvider(adapter);
OngoingListItemDetailsLookup itemDetailsLookup = new OngoingListItemDetailsLookup(recyclerView);
StorageStrategy<Order> storageStrategy = StorageStrategy.createParcelableStorage(Order.class);
SelectionTracker.SelectionPredicate<Order> selectionPredicate = new SelectionTracker.SelectionPredicate<Order>() {
#Override
public boolean canSetStateForKey(#NonNull Order key, boolean nextState) {
return key.getService() == 1 && tracker.getSelection().size()<2;
}
#Override
public boolean canSetStateAtPosition(int position, boolean nextState) {
return listAdapter.getItem(position).getService() == 1 && tracker.getSelection().size()<2;
}
#Override
public boolean canSelectMultiple() {
return true;
}
};
tracker = new SelectionTracker.Builder<Order>(
"my-selection-id",
recyclerView,
keyProvider,
itemDetailsLookup,
storageStrategy).withSelectionPredicate(selectionPredicate)
.build();
adapter.setTracker(tracker);
tracker.addObserver(new SelectionTracker.SelectionObserver<Order>() {
#Override
public void onSelectionChanged() {
try{
super.onSelectionChanged();
selectedItems = tracker.getSelection().size();
if(selectedItems>0){
try{
setActionBarTitle(String.format("%d Order(s) Selected",selectedItems));
Selection<Order> selections = tracker.getSelection();
for(Order selectedOrder:selections){
selectedOrders.add(selectedOrder.getTemporaryOrderId());
}
}catch (Exception e){
FirebaseCrashlytics.getInstance().log(e.toString());
}
}else{
tracker.clearSelection();
selectedOrders.clear();
setActionBarTitle("Ongoing");
}
getActivity().invalidateOptionsMenu();
}catch (Exception e){
e.printStackTrace();
}
}
});
}
//1.I am trying to pass Bar code value using ZXingScannerView scanner
//2. Then if scanned bar code is equals to JSON barcode object show item_name and cost from the JSON //file inside recyclerview, My issue is after scanning nothing is showing
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_second, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
scannerView = (ZXingScannerView) view.findViewById(R.id.zxscan);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(linearLayoutManager);
CustomAdapter customAdapter = new CustomAdapter(getActivity(), products_name, cost);
recyclerView.setAdapter(customAdapter); // set the Adapter to RecyclerView
Dexter.withActivity(getActivity())
.withPermission(Manifest.permission.CAMERA)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
scannerView.setResultHandler(SecondFragment.this);
scannerView.startCamera();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
Toast.makeText(getActivity(), "Please Accept The Permission", Toast.LENGTH_LONG).show();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
}
})
.check();
return view;
}
#Override
public void onDestroy() {
scannerView.stopCamera();
super.onDestroy();
}
#Override
public void handleResult(Result rawResult) {
processRawResult(rawResult.getText());
if (Patterns.WEB_URL.matcher(rawResult.getText()).matches()) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(rawResult.getText()));
startActivity(browserIntent);
}
}
private void processRawResult(String text) {
if (text.startsWith("BEGIN:")){
String[] tokens = text.split("\n");
QRVCardModel qrvCardModel = new QRVCardModel();
for (int i = 0; i < tokens.length; i++)
{
if (tokens[i].startsWith("BEGIN:")) {
qrvCardModel.setType(tokens[i].substring("BEGIN:".length()));
}
else if (tokens[i].startsWith("N")) {
qrvCardModel.setName(tokens[i].substring("N:".length()));
}
else if (tokens[i].startsWith("ORG")) {
qrvCardModel.setOrg(tokens[i].substring("ORG:".length()));
}
else if (tokens[i].startsWith("TEL:")) {
qrvCardModel.setTel(tokens[i].substring("TEL:".length()));
}
else if (tokens[i].startsWith("URL:")) {
qrvCardModel.setUrl(tokens[i].substring("URL:".length()));
}
else if (tokens[i].startsWith("EMAIL:")) {
qrvCardModel.setEmail(tokens[i].substring("EMAIL:".length()));
}
else if (tokens[i].startsWith("ADS:")) {
qrvCardModel.setEmail(tokens[i].substring("ADS:".length()));
}
else if (tokens[i].startsWith("NOTE:")) {
qrvCardModel.setNote(tokens[i].substring("NOTE:".length()));
}
else if (tokens[i].startsWith("SUMMERY:")) {
qrvCardModel.setSummer(tokens[i].substring("SUMMERY:".length()));
}
else if (tokens[i].startsWith("DTSTART:")) {
qrvCardModel.setDtstart(tokens[i].substring("DTSTART:".length()));
}
else if (tokens[i].startsWith("DTEND:")) {
qrvCardModel.setDtend(tokens[i].substring("DTEND:".length()));
}
}
}
else if (text.startsWith("hhtp://")||
text.startsWith("hhtps://")||
text.startsWith("www."))
{
QRURLMode qrurlMode = new QRURLMode(text);
}
else if (text.startsWith("geo:"))
{
QRGeoModel qrGeoModel= new QRGeoModel();
String delims = "[ ,?q= ] +";
String tokens[]= text.split(delims);
for (int i=0; i< tokens.length;i++)
{
if (tokens[i].startsWith("geo:"))
{
qrGeoModel.setLat(tokens[i].substring("geo:".length()));
}
}
qrGeoModel.setLat(tokens[0].substring("geo".length()));
qrGeoModel.setLng(tokens[1]);
qrGeoModel.setGeo_place(tokens[2]);
}
else
{
Toast.makeText(getActivity(),"QR CODE PASS", Toast.LENGTH_SHORT).show();
String json;
try {
InputStream is = getActivity().getAssets().open("products.json");
Toast.makeText(getActivity(), "JSON1", Toast.LENGTH_SHORT).show();
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
//Toast.makeText(getActivity(),"JSON2", Toast.LENGTH_SHORT).show();
json = new String(buffer, "UTF-8");
Log.d("JSONTestLogs", "JSON Raw Text: " + json);
JSONObject object = new JSONObject(json);
JSONArray productsArray = object.getJSONArray("products");
Log.d("JSONTestLogs", "Fetching the Products array from JSON File. Size: " + productsArray.length());
for (int i = 0; i < productsArray.length(); i++) {
JSONObject item = productsArray.getJSONObject(i);
Log.d("JSONTestLogs", "Item: " + i + "\n" + item.toString());
if (text.equals(item.getString("bar_code"))) {
products_name.add(item.getString("item_name"));
cost.add(item.getString("cost"));
}
}
}
catch
(IOException e)
{
e.printStackTrace();
}
catch (JSONException e){
e.printStackTrace(); }
}
scannerView.resumeCameraPreview(SecondFragment.this);
// Toast.makeText(getActivity(),"JSON3", Toast.LENGTH_SHORT).show();
}
}
after you scanned the barcode. I think add the barcode to your list here;
products_name.add(item.getString("item_name"));
After add operation, you did not refresh the recyclerview data.
This code part working just one time.
CustomAdapter customAdapter = new CustomAdapter(getActivity(), products_name, cost);
recyclerView.setAdapter(customAdapter); // set the Adapter to RecyclerView
you should call this part again or you need a function inside your adapter which is notify the data of recyclerview.
I have three fragments in a FragmentPagerAdapter, and each of them would fetch a list of frames/data from a server using Volley. This data would later be used to update the Fragment's RecyclerView Adapter as a Cursor.
VolleyRestClientUtils.get(getString(R.string.PATH_SHOP), LOG_TAG, params, true, false, new JsonHttpResponseHandler() {
public void onSuccess(JSONObject response) {
Log.d(LOG_TAG, "request Response : " + response.toString());
try {
String status = response.getString("status");
if (RestClientUtils.STATUS_OK.equals(status)) {
final JSONArray frames = response.getJSONArray("items");
Log.d(LOG_TAG, "request Response : " + frames.length());
if (frames != null && frames.length() > 0) {
new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... voids) {
List<ContentValues> listShopFrame = ShopFrame.fromJSONArray(frames, sort);
if (listShopFrame.size() > 0 && isActivityActive()) {
ContentResolver cr = getActivity().getContentResolver();
if (!isRequestMore) {
cr.delete(ShopFrame.CONTENT_URI, ShopFrame.COLUMN_CATEGORY + "=?",
new String[]{sort});
paramSkip = frames.length();
} else {
paramSkip += frames.length();
}
ArrayList<ContentProviderOperation> operations = new ArrayList<>();
String log = listShopFrame.size()+" ";
for (int i = 0; i < listShopFrame.size(); i++) {
operations.add(ContentProviderOperation
.newInsert(ShopFrame.CONTENT_URI)
.withValues(listShopFrame.get(i))
.build());
log += listShopFrame.get(i).toString()+"\n";
}
Log.i("loader_callback_"+sort, log);
//cr.applyBatch(ShopFrame.CONTENT_AUTHORITY, operations);
ContentValues[] opsAsArray = new ContentValues[listShopFrame.size()];
listShopFrame.toArray(opsAsArray);
cr.bulkInsert(ShopFrame.CONTENT_URI, opsAsArray);
//return true;
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
dataRefreshed = true;
Log.i("loader_callback_"+sort, "response post execute");
if (result) {
loadSucceed();
PicMixApp.getInstance().setRefreshed(ShopFrameFragment.this.getClass().getName());
} else {
loadFailed(null);
}
}
}.execute();
} else {
//TODO
//Handle error
loadFailed(getString(R.string.err_load_s, getString(R.string.frame)));
}
} else if (VolleyRestClientUtils.STATUS_RESOURCE_NOT_FOUND.equals(status)) {
hasMore = false;
loadSucceed();
} else {
loadFailed(getString(R.string.err_load_s, getString(R.string.frame)));
}
} catch (Exception e) {
Log.e(LOG_TAG, "Exception:" + e.getMessage());
loadFailed(getString(R.string.err_load_s, getString(R.string.frame)));
}
}
#Override
public void onJSONError(String responseString) {
loadFailed(getString(R.string.err_load_s, getString(R.string.frame)));
}
#Override
public void onFailure(String errMessage, int statusCode, Map<String, String> headers, byte[] responseBytes) {
loadFailed(getString(R.string.err_load_s, getString(R.string.frame)));
}
});
Whereas loadSucceed() has this following code:
if (this.recyclerView != null) {
final RecyclerView.Adapter adapter = recyclerView.getAdapter();
if (adapter != null) {
adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onChanged() {
super.onChanged();
Log.i(DefaultRecyclerFragment.this.getClass().getName(), "onChanged");
adapter.unregisterAdapterDataObserver(this);
isLoading = false;
}
public void onItemRangeRemoved(int positionStart, int itemCount) {
Log.i(DefaultRecyclerFragment.this.getClass().getName(), "onItemRangeRemoved:" + positionStart + ", itemcount:" + itemCount);
adapter.unregisterAdapterDataObserver(this);
isLoading = false;
}
});
if (adapter instanceof CursorRecyclerAdapter && loadMoreView != null) {
((CursorRecyclerAdapter) adapter).removeFooter(loadMoreView);
}
}
}
I've put the code to initialize the loader in the onResume() method of each fragment:
int id = 100+Integer.valueOf(sort);
Loader l = getLoaderManager().getLoader(id);
Log.i("loader_callback_"+sort, "success loading volley "+l);
if(l == null) {
getLoaderManager().restartLoader(id, null, this);
}
My problem is that there seems to be some sort of race condition happening, that the currently viewed fragment's adapter seem to be updated twice, and sometimes thrice. The initial cursor fetched by the Fragment's Loader has 10 rows, sure, but after the update, most of the time it only has 7 of the 21 rows expected to be put in.
I thought all the ContentResolvers' operations are synchronous (can only be done one after another, not simultaneously). What's going on here?
EDIT: Should I just put the loader init code in the loadSuccess() callback?
EDIT2: I should note that these Fragments extend android.support.v4.app.Fragment, and I'm using the version 27.1.1 of the Support Library.
I have used rxjava and retrofit to load data from backend and update the UI.
But there is no data displayed on section view. I have tested it, and the backend data load successful and the UI can be updated using fake data.
Are there something wrong when I use Rxjava?
private void retrieveCardInfo(String stripeId, String userToken) {
subscriptions.add(NetworkUtil.getRetrofit(userToken).getCustomerInfo(new GetCustomer(stripeId))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::handleCustomerResponse, this::handleError));
}
private void handleCustomerResponse(CreateStripeCustomerResponse response) {
if (response.getSuccess()) {
updateCardList(response);
bankSection.setState(Section.State.EMPTY);
} else {
Utils.toast(this,"Get credit card failed");
}
}
private void updateCardList(CreateStripeCustomerResponse response) {
List<CardInfo> cardList = response.getCustomer().getSources().getData();
if (cardList == null || cardList.size() == 0) {
cardSection.setState(Section.State.EMPTY);
} else {
list = new ArrayList<>();
for (int i = 0; i < cardList.size(); i++) {
CardInfo cardInfo = cardList.get(i);
String brand = cardInfo.getBrand();
String subTitle = cardInfo.getFunding() + "****" + cardInfo.getLast4();
list.add(new PaymentAccountItem(brand, subTitle, cardDrawable.get(brand)));
}
list.add(new PaymentAccountItem("title", "subtitle", R.drawable.ic__credit_amex_svg));
cardSection.swipeData(list);
}
}
private void handleError(Throwable throwable) {
}
// works fine without sectionedAdapter.notifyDataSetChanged(); when using fake data,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
ButterKnife.bind(this);
subscriptions = new CompositeSubscription();
initialToolbar();
initialRecyclerView();
initialPaymentData();
}
private void initialPaymentData() {
stripeIdAndToken = Utils.getStripeIdAndToken(this);
if (TextUtils.isEmpty(stripeIdAndToken.first)) {
cardSection.setState(Section.State.EMPTY);
bankSection.setState(Section.State.EMPTY);
} else {
initialCardDrawableResource();
retrieveCardInfo(stripeIdAndToken.first, stripeIdAndToken.second);
}
// fake data here
// initialCardDrawableResource();
// list = new ArrayList<>();
// list.add(new PaymentCreditCardItem("Visa", "123456", 10, 2018, cardDrawable.get("Visa")));
// cardSection.swipeData(list);
}
private void initialCardDrawableResource() {
cardDrawable = new HashMap<>();
cardDrawable.put("Visa", R.drawable.ic_visa_svg);
cardDrawable.put("Discover", R.drawable.ic_discover_svg);
cardDrawable.put("American Express", R.drawable.ic__credit_amex_svg);
cardDrawable.put("Mastercard", R.drawable.cio_ic_mastercard);
}
private void retrieveCardInfo(String stripeId, String token) {
subscriptions.add(NetworkUtil.getRetrofit(token).getCustomerInfo(new GetCustomer(stripeId))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::handleCustomerResponse, this::handleError));
}
private void handleCustomerResponse(CreateStripeCustomerResponse response) {
if (response.getSuccess()) {
updateCardList(response);
} else {
Utils.toast(this, "Get credit card failed");
}
}
private void updateCardList(CreateStripeCustomerResponse response) {
List<CardInfo> cardList = response.getCustomer().getSources().getData();
if (cardList == null || cardList.size() == 0) {
cardSection.setState(Section.State.EMPTY);
} else {
list = new ArrayList<>();
for (int i = 0; i < cardList.size(); i++) {
CardInfo cardInfo = cardList.get(i);
String brand = cardInfo.getBrand();
String cardNum = cardInfo.getFunding() + "****" + cardInfo.getLast4();
list.add(new PaymentCreditCardItem(brand, cardNum, cardInfo.getExpMonth(), cardInfo.getExpYear(), cardDrawable.get(brand)));
}
cardSection.swipeData(list);
sectionedAdapter.notifyDataSetChanged();
}
}
private void handleError(Throwable throwable) {
}
private void initialRecyclerView() {
sectionedAdapter = new SectionedRecyclerViewAdapter();
cardSection = new PaymentCardAndAccountSection(this, R.layout.header_card, R.layout.payment_card_empty_view);
bankSection = new PaymentCardAndAccountSection(this, R.layout.header_bank, R.layout.payment_account_empty_view);
sectionedAdapter.addSection(cardSection);
sectionedAdapter.addSection(bankSection);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(sectionedAdapter);
bankSection.setState(Section.State.EMPTY);
}
private void initialToolbar() {
toolbar.setTitle("Payment");
toolbar.setNavigationIcon(R.drawable.ic_back_svg);
setSupportActionBar(toolbar);
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
#OnClick(R.id.fab_add_payment)
void launchAddPaymentDialog() {
AddPaymentDialogFragment addPaymentDialogFragment = AddPaymentDialogFragment.newInstance();
addPaymentDialogFragment.setStyle(DialogFragment.STYLE_NO_FRAME, 0);
addPaymentDialogFragment.show(getSupportFragmentManager(), "dialog");
}
#Override
public void onPause() {
super.onPause();
if (subscriptions != null) {
subscriptions.clear();
}
}
Do you use an adapter? In this case adapter.notifyDataSetChanged();
Also, print yout error: throwable.printStackTrace(); in order to see if something goes wrong.
You need to add .observeOn(AndroidSchedulers.mainThread()) after you write subsribeOn() to tell your observable to perform your onNext callback on UI thread/MainThread.
i am showing some server data using recyclerview which will show updated data to the top,and to update list i am calling a method after 15 sec each, first time i req server its working fine but after that when i am updating list with server data 15 sec each and trying to add the new item to top and show, its not working well ,more specific the problem is while the last item is pic and updated data is text its merged in output.
see the pics. last item was webadeal pic and when i updated list with data "test" its merged in UI.
here is my code:
fragment:
oncreateview(){
//adapter initialization
linearLayoutManager=new LinearLayoutManager(context_newsfeed);
recyclerView.setLayoutManager(linearLayoutManager);
newsFeedAdapter = new NewsFeedAdapter(newsFeedClassArrayList, context_newsfeed);
recyclerView.setAdapter(newsFeedAdapter);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(context_newsfeed, linearLayoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
if (WebViewActivity.getScrollPosition() != null) {
recyclerView.scrollToPosition(Integer.valueOf(WebViewActivity.getScrollPosition()));
}
}
//below are two method. first is called for once which working well but second is for 15 sec each.
void updateNewsFeed(){
// newsFeedClassArrayList=new ArrayList<>();
postId_ArrayList=new ArrayList<>();
// allArrayList=new ArrayList<>();
try {
newsFeedQuery= URLEncoder.encode("userId","UTF-8")+"="+URLEncoder.encode(ServiceClass.getDefaults("USERID",context_newsfeed),"UTF-8")
+ "&" + URLEncoder.encode("updatePostId","UTF-8")+"="+ URLEncoder.encode(lastPostId,"UTF-8");
if(asyncTaskClass==null || asyncTaskClass.getStatus()== AsyncTask.Status.FINISHED) {
asyncTaskClass = new AsyncTaskClass(context_newsfeed, new AsyncTaskResult() {
#Override
public void AsyncTaskResult(String result) throws JSONException {
Log.v("ResDUpdate", result);
swipeRefreshLayout.setRefreshing(false);
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("result");
if (jsonArray.length() > 0){
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject tmpjsonObject = new JSONObject(jsonArray.optString(i));
newsFeedClass_updated = new NewsFeedClass();
if (tmpjsonObject.getString("funpage").equals("1")) {
newsFeedClass_updated.setUserId_friends(tmpjsonObject.getString("user_id"));
newsFeedClass_updated.setPostId(tmpjsonObject.getString("id"));
/*if(postId==(null) || postId.equals("")|| Integer.valueOf(postId)<Integer.valueOf(tmpjsonObject.getString("id")))
{
ServiceClass.setDefaults("postId",tmpjsonObject.getString("id"),context_newsfeed);
}*/
// make post id arrayList
ContactListClass contactListClass_postId = new ContactListClass();
contactListClass_postId.setContactName(tmpjsonObject.getString("id")); //post id
contactListClass_postId.setContactNumber(String.valueOf(i)); //index no
postId_ArrayList.add(contactListClass_postId);
//updated post id
if (Integer.valueOf(tmpjsonObject.getString("id")) > Integer.valueOf(lastPostId)) {
lastPostId = tmpjsonObject.getString("id");
}
newsFeedClass_updated.setUserPicUrl_newsFeed(tmpjsonObject.getString("profile_pic"));
newsFeedClass_updated.setUserProName(tmpjsonObject.getString("author_name"));
newsFeedClass_updated.setStatus(tmpjsonObject.getString("post_content"));
newsFeedClass_updated.setLikeCount(tmpjsonObject.getString("post_likes"));
newsFeedClass_updated.setWowCount(tmpjsonObject.getString("post_wows"));
newsFeedClass_updated.setBlehCount(tmpjsonObject.getString("post_blehs"));
newsFeedClass_updated.setDislikeCount(tmpjsonObject.getString("post_dislikes"));
newsFeedClass_updated.setTimeStamp(tmpjsonObject.getString("post_time"));
newsFeedClass_updated.setVideo("");
newsFeedClass_updated.setYoutubeVideo("");
newsFeedClass_updated.setIsSharedValue(tmpjsonObject.getString("is_shared"));
newsFeedClass_updated.setIsFriend(tmpjsonObject.getString("is_by_friend"));
//post attachment // here image if more than one
imageList_FunPost = new ArrayList<>();
if (tmpjsonObject.getJSONArray("attachments").length() > 0) {
JSONArray jsonArray_attachment = tmpjsonObject.getJSONArray("attachments");
for (int i_attachment = 0; i_attachment < jsonArray_attachment.length(); i_attachment++) {
JSONObject jsonObject_attachment = new JSONObject(jsonArray_attachment.optString(i_attachment));
ContactListClass contactListClass = new ContactListClass();
contactListClass.setContactName(InfoSetClass.getBaseUrl() + jsonObject_attachment.getString("file_path"));// post picture url save
contactListClass.setContactNumber((tmpjsonObject.getString("id")));
imageList_FunPost.add(contactListClass);
}
newsFeedClass_updated.setImageList(imageList_FunPost);
}
Log.v("ResDfsd","tes "+ newsFeedClassArrayList);
newsFeedClassArrayList.add(0,newsFeedClass_updated);// but as i need to show last item at top thats why i do this and prb raise.
Log.e("newsFeedClassArrayList","after adding new data from api response "+ newsFeedClassArrayList);
}
}
//that is fine, may be problem is else where
// allArrayList.addAll(newsFeedClassArrayList);
// newsFeedAdapter.swapList(newsFeedClassArrayList);
// newsFeedAdapter.notifyItemInserted(0);
newsFeedAdapter.notifyDataSetChanged();
//set list to service class
ServiceClass.setPostId_list(postId_ArrayList);
}
Log.v("ResDfsd","tesdf "+ newsFeedClassArrayList);
}
});
asyncTaskClass.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "POST", "mobileApi/getUpdatePost", newsFeedQuery);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
adapter:
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.rightArrowViewPagerId.setVisibility(View.GONE);
holder.leftArrowViewPagerId.setVisibility(View.GONE);
currentPageNo=holder.viewPager.getCurrentItem();
// mediaPlayer=new MediaPlayer();
newsFeedClass=newsFeedClassArrayList.get(position);
Picasso.with(context).load(InfoSetClass.getBaseUrl()+newsFeedClass.getUserPicUrl_newsFeed()).centerCrop().transform(new CircleTransform()).resize(50,50).into(holder.userProPicImg);
holder.userProNameTvId.setText(newsFeedClass.getUserProName());
if(newsFeedClass.getLikeCount()!=null)
totalLikeWow=Integer.valueOf(newsFeedClass.getLikeCount())+Integer.valueOf(newsFeedClass.getBlehCount()) +Integer.valueOf(newsFeedClass.getDislikeCount())+Integer.valueOf(newsFeedClass.getWowCount());
holder.likeCountTv.setText(String.valueOf(totalLikeWow));
if(newsFeedClass.getCommentCount()!=null)
holder.commentCountTv.setText(String.valueOf(newsFeedClass.getCommentCount()));
if(newsFeedClass.getShareCount()!=null){
holder.shareCountTv.setText(String.valueOf(newsFeedClass.getShareCount()));
}
if(!((newsFeedClass.getStatus().toLowerCase().contains(".jpg"))||(newsFeedClass.getStatus().toLowerCase().contains(".png"))||
(newsFeedClass.getStatus().toLowerCase().contains("https"))||(newsFeedClass.getStatus().toLowerCase().contains("http")))) {
holder.statusTv.setText(Html.fromHtml(newsFeedClass.getStatus()));
// holder.viewPager.setVisibility(View.GONE);
}
else {
holder.newsFeedImageView.loadData(newsFeedClass.getStatus(), "text/html", null);
holder.newsFeedImageView.getSettings().setJavaScriptEnabled(true);
WebSettings webSettings = holder.newsFeedImageView.getSettings();
webSettings.setGeolocationEnabled(true);
webSettings.getJavaScriptEnabled();
webSettings.getMediaPlaybackRequiresUserGesture();
// holder.viewPager.setVisibility(View.GONE);
}
//image slider
if(newsFeedClass.getImageList()!=null){
holder.viewPager.setVisibility(View.VISIBLE);
viewPagerAdapter=new ViewPagerAdapter(context,newsFeedClass.getImageList());
holder.viewPager.setAdapter(viewPagerAdapter);
if(viewPagerAdapter.getCount()>1){
holder.rightArrowViewPagerId.setVisibility(View.VISIBLE);
}
if(holder.viewPager.getCurrentItem()>1){
holder.leftArrowViewPagerId.setVisibility(View.VISIBLE);
}
if(holder.viewPager.getCurrentItem()==0){
holder.leftArrowViewPagerId.setVisibility(View.GONE);
}
if(holder.viewPager.getCurrentItem()==viewPagerAdapter.getCount()){
holder.rightArrowViewPagerId.setVisibility(View.GONE);
}
holder.rightArrowViewPagerId.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(holder.viewPager.getCurrentItem()<viewPagerAdapter.getCount()){
if(holder.viewPager.getCurrentItem()<=viewPagerAdapter.getCount()){
holder.viewPager.setCurrentItem(currentPageNo++,true);
}
}
}
});
// holder.viewPagerArrowIndicator.bind(holder.viewPager);
// holder.viewPagerArrowIndicator.setArrowIndicatorRes(R.drawable.arrow_left_black_24dp,R.drawable.arrow_right_black_24dp);
viewPagerAdapter.notifyDataSetChanged();
}else {
// holder.viewPager.setVisibility(View.GONE);
relativeLayout.setVisibility(View.GONE);
}
holder.timeStampTvId.setText(newsFeedClass.getTimeStamp());
}
Recycle View will reuse the item so we should set the value in bindView all time, but some value you didn't set properly, so do like this,
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.rightArrowViewPagerId.setVisibility(View.GONE);
holder.leftArrowViewPagerId.setVisibility(View.GONE);
currentPageNo=holder.viewPager.getCurrentItem();
// mediaPlayer=new MediaPlayer();
newsFeedClass=newsFeedClassArrayList.get(position);
Picasso.with(context).load(InfoSetClass.getBaseUrl()+newsFeedClass.getUserPicUrl_newsFeed()).centerCrop().transform(new CircleTransform()).resize(50,50).into(holder.userProPicImg);
holder.userProNameTvId.setText(newsFeedClass.getUserProName());
if(newsFeedClass.getLikeCount()!=null)
totalLikeWow=Integer.valueOf(newsFeedClass.getLikeCount())+Integer.valueOf(newsFeedClass.getBlehCount()) +Integer.valueOf(newsFeedClass.getDislikeCount())+Integer.valueOf(newsFeedClass.getWowCount());
holder.likeCountTv.setText(String.valueOf(totalLikeWow));
if(newsFeedClass.getCommentCount()!=null) {
holder.commentCountTv.setText(String.valueOf(newsFeedClass.getCommentCount()));
} else {
holder.commentCountTv.setText("");
}
if(newsFeedClass.getShareCount()!=null){
holder.shareCountTv.setText(String.valueOf(newsFeedClass.getShareCount()));
} else {
holder.shareCountTv.setText("");
}
if(!((newsFeedClass.getStatus().toLowerCase().contains(".jpg"))||(newsFeedClass.getStatus().toLowerCase().contains(".png"))||
(newsFeedClass.getStatus().toLowerCase().contains("https"))||(newsFeedClass.getStatus().toLowerCase().contains("http")))) {
holder.statusTv.setText(Html.fromHtml(newsFeedClass.getStatus()));
holder.newsFeedImageView.setVisibility(View.GONE);
// holder.viewPager.setVisibility(View.GONE);
}
else {
holder.newsFeedImageView.setVisibility(View.VISIBLE);
holder.statusTv.setText("");
holder.newsFeedImageView.loadData(newsFeedClass.getStatus(), "text/html", null);
holder.newsFeedImageView.getSettings().setJavaScriptEnabled(true);
WebSettings webSettings = holder.newsFeedImageView.getSettings();
webSettings.setGeolocationEnabled(true);
webSettings.getJavaScriptEnabled();
webSettings.getMediaPlaybackRequiresUserGesture();
// holder.viewPager.setVisibility(View.GONE);
}
//image slider
if(newsFeedClass.getImageList()!=null){
relativeLayout.setVisibility(View.VISIBLE);
holder.viewPager.setVisibility(View.VISIBLE);
ViewPagerAdapter viewPagerAdapter=new ViewPagerAdapter(context,newsFeedClass.getImageList());
holder.viewPager.setAdapter(viewPagerAdapter);
if(viewPagerAdapter.getCount()>1){
holder.rightArrowViewPagerId.setVisibility(View.VISIBLE);
}
if(holder.viewPager.getCurrentItem()>1){
holder.leftArrowViewPagerId.setVisibility(View.VISIBLE);
}
if(holder.viewPager.getCurrentItem()==0){
holder.leftArrowViewPagerId.setVisibility(View.GONE);
}
if(holder.viewPager.getCurrentItem()==viewPagerAdapter.getCount()){
holder.rightArrowViewPagerId.setVisibility(View.GONE);
}
holder.rightArrowViewPagerId.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(holder.viewPager.getCurrentItem()<viewPagerAdapter.getCount()){
if(holder.viewPager.getCurrentItem()<=viewPagerAdapter.getCount()){
holder.viewPager.setCurrentItem(currentPageNo++,true);
}
}
}
});
// holder.viewPagerArrowIndicator.bind(holder.viewPager);
// holder.viewPagerArrowIndicator.setArrowIndicatorRes(R.drawable.arrow_left_black_24dp,R.drawable.arrow_right_black_24dp);
viewPagerAdapter.notifyDataSetChanged();
}else {
holder.viewPager.setVisibility(View.GONE);
relativeLayout.setVisibility(View.GONE);
}
holder.timeStampTvId.setText(newsFeedClass.getTimeStamp());
}