0

I am trying to refresh my fragment view, and the data inside it, i've tried to invalidate the view, but its not working. the only method worked is to detach and attach the fragment, but its not the ideal solution. I want something more performant.

So it would help me a lot if someone suggest me a better solution to refresh the view.

Thank you all

`// Injections @Inject Service service; @Inject SessionManager session;

// Views
    // User views
@BindView(R.id.user_name) TextView fullName;
@BindView(R.id.user_img) ImageView userImage;
    // Troc views
@BindView(R.id.description) TextView desView;
@BindView(R.id.created_date) TextView createdDate;
@BindView(R.id.title) TextView title;
@BindView(R.id.month) TextView monthPurchaseDate;
@BindView(R.id.year) TextView yearPurchaseDate;
@BindView(R.id.place) TextView address;
@BindView(R.id.actual_price) TextView actualPrice;
@BindView(R.id.original_price) TextView originalPrice;
@BindView(R.id.photo) ImageView postImage;
@BindView(R.id.comments_recycler) RecyclerView commentsRecycler;
@BindView(R.id.send_comment) ImageView sendCommentButton;
@BindView(R.id.text_comment) EditText commentText;
@BindView(R.id.categories_recycler) RecyclerView categoriesRecycler;
@BindView(R.id.close_view) ImageView closeView;
@BindView(R.id.delete_view) ImageView deleteView;
private Socket socket;
private View view;
public TrocDetailsFragmentDialog(Context context, Troc troc){
    this.context = context;
    this.troc = troc;
}


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_troc_details_dialog, container, false);
    ((TrocApp)getActivity().getApplication()).getDeps().inject(this);

    ButterKnife.bind(this, view);

    subscriptions = new CompositeSubscription();

   /* view.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
                onTouchEvent(event,v);
            return false;
        }
    });*/

    // Handle other views
    closeView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            TrocDetailsFragmentDialog.this.dismiss();
        }
    });

    deleteView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Snackbar snackbar = Snackbar.make(getView(),R.string.want_to_delete_troc, Snackbar.LENGTH_LONG)
                    .setAction(R.string.undo, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    });
            snackbar.setCallback(new Snackbar.Callback(){
                @Override
                public void onDismissed(Snackbar transientBottomBar, int event) {
                    super.onDismissed(transientBottomBar, event);

                    if(event == Snackbar.Callback.DISMISS_EVENT_TIMEOUT){
                        startDeletingPost(troc.getId());
                    }
                }
            }).show();



        }
    });

 // User
    fullName.setText(troc.getAuthor().getFullName());
    Picasso.with(context)
            .load(BuildConfig.API_SERVER_USER_SMALL_UPLOADS + troc.getAuthor().getPhoto())
            .placeholder(R.drawable.defaultuserlog)
            .error(R.drawable.defaultuserlog)
            .fit()
            .into(userImage);

 // Troc
    title.setText(troc.getTitle());
    desView.setText(troc.getBody());
    address.setText(troc.getAddress().getStreet()+", "+troc.getAddress().getCity()+", "+troc.getAddress().getCountry()+", "+troc.getAddress().getPostalCode());

    // Handle Date of creation of troc
    SimpleDateFormat formattedDate = new SimpleDateFormat(ISO_8601_24H_FULL_FORMAT);
    formattedDate.setTimeZone(TimeZone.getTimeZone("GMT"));

    try {
        Date date = formattedDate.parse(troc.getDateCreated());
        createdDate.setText(new PrettyTime().format( date ));
    } catch (ParseException e) {
        e.printStackTrace();
    }

    if(troc.getPhotos().length > 0) {
        Picasso.with(context)
                .load(BuildConfig.API_SERVER_TROCS_MEDIUM_UPLOADS + troc.getPhotos()[0])
                .placeholder(R.drawable.placeholder_post)
                .error(R.drawable.placeholder_post)
                .resize(400, 400)
                .into(postImage);

        // handle troc image click

        postImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FullScreenImagePagerDialog fullScreenDialog = new FullScreenImagePagerDialog(context, troc.getPhotos());
                fullScreenDialog.setStyle(DialogFragment.STYLE_NORMAL, R.style.DialogFragment);
                fullScreenDialog.show(getFragmentManager(), "dialog");
            }
        });
    }

    // Handle original and actual price

    originalPrice.setText(troc.getOriginalPrice() + " " + Constants.LOCAL_CURRENCY);
    actualPrice.setText(troc.getActualPrice() + " " +Constants.LOCAL_CURRENCY);

    // Handle purchase Date

    handlePurchaseDateView(troc.getPurchaseDate(),monthPurchaseDate,yearPurchaseDate);

    // Handle categories

    handleCategoriesView(categoriesRecycler,troc.getCategories());


    // Make comments area ready

    LinearLayoutManager layoutManager
            = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
    commentsRecycler.setLayoutManager(layoutManager);
    commentsRecycler.setItemAnimator(new DefaultItemAnimator());
    commentsRecycler.setNestedScrollingEnabled(false);
    commentAdapter = new CommentAdapter(context,troc.getComments());
    commentsRecycler.setAdapter(commentAdapter);

    // Handle add comment

    sendCommentButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(commentText.getText().toString().isEmpty()){
                Toast.makeText(context,R.string.specify_comment,Toast.LENGTH_SHORT).show();
            }
            else{
                sendComment(troc.getId(),commentText.getText().toString(),v);
            }
        }
    });

   /* Subscription updateListener = updateSubscription();
    subscriptions.add(updateListener);*/
    socket = IO.socket(URI.create(API_SERVER_ADDRESS));
    socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {

        @Override
        public void call(Object... args) {
            socket.emit("post", troc.getId());

            //  socket.disconnect();
        }

    }).on("post", new Emitter.Listener() {

        @Override
        public void call(Object... args) {
        }

    }).on("postMessage", new Emitter.Listener() {

        @Override
        public void call(final Object... args) {

            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(getContext(),(String)args[0],Toast.LENGTH_SHORT ).show();

                    if(((String)args[0]).equals(SOCKET_POST_STATUS_UPDATED)){
                       updateTrocView();
                   }
                }
            });
        }

    }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {

        @Override
        public void call(Object... args) {

        }

    });
    socket.connect();
    return view;
}`

the method that ive tried

public void updateTrocView(){
    Subscription diplayTrocSubscription = service.getTroc(troc.getId(), new Service.TrocResultServiceCallback() {
        @Override
        public void onSuccess(TrocResult trocResult) {
            if(trocResult.isSuccess()){
                troc = trocResult.getTroc();
                view.invalidate();
                commentAdapter.notifyDataSetChanged();
            }
            else{
               Snackbar.make(view,R.string.check_internet,Snackbar.LENGTH_LONG).show();
            }
        }

        @Override
        public void onError(NetworkError networkError) {

        }
    });
    subscriptions.add(diplayTrocSubscription);
}
  • Post your code. – SAM Apr 10 '17 at 13:27
  • code is there now – Hédy HidouRy Apr 10 '17 at 13:35
  • You can only update ui from mainThread. Check whether you are using main thread or background thread. – Krish Apr 10 '17 at 13:44
  • @Krish i am running the update on UiThread, as i know, it is the same as the mainThread, ill try it ( on Mainthread ) and inform you, thank you – Hédy HidouRy Apr 10 '17 at 13:49
  • I mean onSuccess() method should call from main thread. Did you check that? – Krish Apr 10 '17 at 13:57
  • @Krish it still the same, no changes – Hédy HidouRy Apr 10 '17 at 13:57
  • Yes it is on mainthread, i am using the service of my requests as a singleton, which is initialized on my mainThread, on the creation of the app. – Hédy HidouRy Apr 10 '17 at 14:00
  • Initialising an object with main thread doesnt mean , it will always work with main thread. What is the purpose of that class ? – Krish Apr 10 '17 at 14:03
  • check this condition in your onSuceess() method if(Looper.myLooper() == Looper.getMainLooper()) { // Current Thread is Main Thread. } http://stackoverflow.com/questions/11411022/how-to-check-if-current-thread-is-not-main-thread – Krish Apr 10 '17 at 14:06
  • the class contains my requests from server, so each method return a subscription, and this subscription will be added to a CompositeSubscription, and wait for a response from server – Hédy HidouRy Apr 10 '17 at 14:06
  • ill check it right now – Hédy HidouRy Apr 10 '17 at 14:08
  • @Krish yes it on mainThread – Hédy HidouRy Apr 10 '17 at 14:12
  • Maybe you can show some toast message there . for checking is it a problem with your adapter or some thing else – Krish Apr 10 '17 at 14:14
  • already done that, with logs and debugs, its just the clean version of the code you see right now, i just dont want to re-combine data with views again – Hédy HidouRy Apr 10 '17 at 14:18
  • troc.getComments() this is a ArrayList I think. right? – Krish Apr 10 '17 at 14:19
  • You should set this object again in the adapter . Otherwise it will always draw the previous data , since you are not assigning new reference to that object. – Krish Apr 10 '17 at 14:21
  • yes you have a point there, but the main problem, is that other views are not changing, like textViews, and also the adapter should be notified with this data to show new comments – Hédy HidouRy Apr 10 '17 at 14:26
  • How did you updating the new models . – Krish Apr 10 '17 at 14:26
  • I didnt get you, what you meant exactly ?? – Hédy HidouRy Apr 10 '17 at 14:29
  • Maybe you misunderstand the method . calling invalidate() method only redraw the whole view with its old data. That you set before (in onCreateView). For setting the new data. You have to write code. Like in onCreateView(). Otherwise it wont work – Krish Apr 10 '17 at 14:31
  • you sure redraw the view with old data ? Otherwise the only solution will be writing re-affect each view with data again, thank you @Krish , was new informations i got – Hédy HidouRy Apr 10 '17 at 14:35
  • I have updated my answer . Please check and accept it if it works. – Krish Apr 10 '17 at 14:37

2 Answers2

0

Use onResume() method to refresh views and data.

  • didnt get it clearly, i am calling the invalidate after a request from the server, so basically onResume() wont be called, note that i am calling invalidate after a success response from ther server – Hédy HidouRy Apr 10 '17 at 13:38
0

Change your code some thing like this ,

public void updateTrocView() {
        Subscription diplayTrocSubscription = service.getTroc(troc.getId(), new Service.TrocResultServiceCallback() {
            @Override
            public void onSuccess(TrocResult trocResult) {
                if (trocResult.isSuccess()) {
                    troc = trocResult.getTroc();

                    bindDataToUI();
                    //set new Data to commentAdapter
                    commentAdapter.notifyDataSetChanged();
                } else {
                    Snackbar.make(view, R.string.check_internet, Snackbar.LENGTH_LONG).show();
                }
            }

            @Override
            public void onError(NetworkError networkError) {

            }
        });
        subscriptions.add(diplayTrocSubscription);
    }

    private void bindDataToUI() {
        fullName.setText(troc.getAuthor().getFullName());
        Picasso.with(context)
                .load(BuildConfig.API_SERVER_USER_SMALL_UPLOADS + troc.getAuthor().getPhoto())
                .placeholder(R.drawable.defaultuserlog)
                .error(R.drawable.defaultuserlog)
                .fit()
                .into(userImage);

        // Troc
        title.setText(troc.getTitle());
        desView.setText(troc.getBody());
        address.setText(troc.getAddress().getStreet() + ", " + troc.getAddress().getCity() + ", " + troc.getAddress().getCountry() + ", " + troc.getAddress().getPostalCode());

    }
Krish
  • 3,860
  • 1
  • 19
  • 32