"Refresh" from Fragment co listview

Asked

Viewed 92 times

1

I have a Fragment that, clicked on a RadioButton, a route is calculated, after this route calculation, a ListView with the results.

By clicking on the other option of this radiobuttom, the routes are recalculated and the new results are shown.

Problem: When you upload these new results, the old ones are not removed from the screen.

How can I remove them and put only the new results?

Fragment:

public class ResultsFragment extends Fragment implements ListView.OnItemClickListener {

    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    public static final String RESULTS_JSON = "results_json";
    public static final String GENERIC_ROUTE_ID = "generic_route_id";
    public static final String IS_RIDER = "is_rider";

    private String mResultsJson;
    private String mResultsJson2;
    private int mGenericRouteId;

    private urMainOnActionPerformed mListener;

    private RouteResultsAdapter mAdapter;

    private ArrayList<Route> mResults;

    @BindView(R.id.results_label)
    TextView mResultsLabel;

    @BindView(R.id.date_container)
    RelativeLayout mDateContainer;

    @BindView(R.id.pick_date_search)
    TextView mDate2;

    @BindView(android.R.id.list)
    public ListView mListView;

    private boolean isRider;
    private Calendar selectedDate = Calendar.getInstance();

    private DatePickerDialog mDatePickerDialog;


    public ResultsFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param resultsJson Parameter 1.
     * @return A new instance of fragment ResultsFragment.
     */
    public static ResultsFragment newInstance(String resultsJson, int genericRouteId
            , boolean isRider) {
        ResultsFragment fragment = new ResultsFragment();
        Bundle args = new Bundle();
        args.putString(RESULTS_JSON, resultsJson);
        args.putInt(GENERIC_ROUTE_ID, genericRouteId);
        args.putBoolean(IS_RIDER, isRider);
        fragment.setArguments(args);
        return fragment;
    }

    public void setResults(String json) {
        mResultsJson = json;
        ArrayList<Route> routes = Route.buildRouteArrayFromJsonString(mResultsJson);
        routes = Route.buildRouteArrayFromJsonString(mResultsJson);
        routes.clear();
        mResults = Route.orderRouteArrayByHavingCar(routes);
        mDate2.setText(TimeUtils.getDayOfWeekFromDate(getContext(), SearchRideType.getInstance().getDate()));
        if (mResults != null) {
            mAdapter = new RouteResultsAdapter(mResults, getContext(), isRider);
            mListView.setAdapter(mAdapter);
            mListView.setOnItemClickListener(this);
            mResultsLabel.setText(mResults.size() + " " + getString(R.string.results));
        }


    }

    public void setGenericRouteId(int id) {
        mGenericRouteId = id;
    }

    public void setIsRider(boolean isRider) {
        this.isRider = isRider;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mResultsJson = getArguments().getString(RESULTS_JSON);
            mGenericRouteId = getArguments().getInt(GENERIC_ROUTE_ID);
            isRider = getArguments().getBoolean(IS_RIDER);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_display_results, container, false);
        ButterKnife.bind(this, view);
        if (mResultsJson != null) {
            setResults(mResultsJson);
        }
        mDateContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDatePickerDialog = new DatePickerDialog(getContext(), R.style.MyDatePickerStyle, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        Calendar date = Calendar.getInstance();
                        date.set(year, monthOfYear, dayOfMonth);
                        if (!SearchRideType.getInstance().getDate().equals(date)) {
                            SearchRideType.getInstance().setDateTime(date.getTime());
                            mDate2.setText(TimeUtils.getDayOfWeekFromDate(getContext(), date.getTime()));
                            mListener.recalculateSuggestions();
                        }

                    }
                }, SearchRideType.getInstance().getCalendar().get(Calendar.YEAR), SearchRideType.getInstance().getCalendar().get(Calendar.MONTH), SearchRideType.getInstance().getCalendar().get(Calendar.DAY_OF_MONTH));
                mDatePickerDialog.show();
            }
        });
        return view;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        showItemAndAction(parent, view, position, id);
    }

    public void showItemAndAction(AdapterView<?> parent, View view, int position, long id) {
        if (mListener != null) {
            mListView.smoothScrollToPosition(position);
            Route route = mResults.get(position);
            if (!route.ride.isRideTimeValid()) {
                Toast.makeText(
                        getActivity(), getString(R.string.ride_time_passed), Toast.LENGTH_SHORT).show();
            } else if (SearchRideType.getInstance().isDriver() || route.getUser() != null && route.getUser().hasCar()) {
                mListView.setSelection(position);
                route.setGenericRouteId(mGenericRouteId);
//                mListener.showAskRideFragment(route);
                RelativeLayout mActionButton = (RelativeLayout) view.findViewById(R.id.action_button);
                mActionButton.setVisibility(View.VISIBLE);
                setActionButton(mActionButton, route);
            } else if (isRider || route.getUser() != null && !route.getUser().hasCar()) {
                mListView.setSelection(position);
                route.setGenericRouteId(mGenericRouteId);
//                mListener.showAskRideFragment(route);
                RelativeLayout mActionButton = (RelativeLayout) view.findViewById(R.id.action_button);
                mActionButton.setVisibility(View.VISIBLE);
                setActionButton(mActionButton, route);
            } else {
                Toast.makeText(
                        getActivity(), getString(R.string.has_no_car), Toast.LENGTH_SHORT).show();
            }

        }
        ((RouteResultsAdapter)parent.getAdapter()).notifyDataSetChanged();
    }

    public void setActionButton(RelativeLayout actionButton, Route route) {
        setActionButtonLayout(actionButton);
        setActionButtonListener(actionButton, route);
    }

    public void setActionButtonLayout(RelativeLayout actionButtonLayout) {
        if (actionButtonLayout != null) {
            ImageView icon = (ImageView) actionButtonLayout.findViewById(R.id.icon_action_button);
            TextView label = (TextView) actionButtonLayout.findViewById(R.id.action_button_label);
            if (isRider) {
                label.setText(getString(R.string.request_ride));
                icon.setImageResource(R.drawable.ic_person_white);
            } else {
                label.setText(getString(R.string.offer_ride));
                icon.setImageResource(R.drawable.ic_driver_white);
            }
        }
    }

    public void setActionButtonListener(RelativeLayout actionButton, final Route route) {
        actionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListener.onAskOrOfferRideRequested(
                        route.ride,
                        isRider ? "ask" : "offer",
                        route.getGenericRouteId()
                );
            }
        });
    }

    @OnClick(R.id.map_button)
    public void onMapClick() {
        mListener.showMap();
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof urMainOnActionPerformed) {
            mListener = (urMainOnActionPerformed) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnConfirmRoutineFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public void requestLayoutForListView() {
        if (mResults != null) {
            mAdapter = new RouteResultsAdapter(mResults, getContext(), isRider);
            mListView.setAdapter(mAdapter);
        }
    }
}

Adapter:

public class RouteResultsAdapter extends BaseAdapter {

    ArrayList<Route> mData;
    Context mContext;
    private boolean isRider;

    public RouteResultsAdapter(ArrayList<Route> routes, Context context, boolean isRider){
        mData = routes;
        mContext = context;
        this.isRider = isRider;

    }

    @Override
    public int getCount(){
        return mData.size();
    }

    @Override
    public long getItemId(int position){
        return position;
    }

    @Override
    public Route getItem(int position){
        return mData.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        RouteResultViewHolder holder;
        if(convertView == null){
            holder = new RouteResultViewHolder();
            convertView = ((LayoutInflater)
                    mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
                    .inflate(R.layout.fragment_display_results_item,null);
            holder.username = (TextView)convertView.findViewById(R.id.username);
            holder.companyPosition = (TextView)convertView.findViewById(R.id.company_position);
            holder.profilePic = (ImageView)convertView.findViewById(R.id.profile_image);
            holder.hour = (TextView)convertView.findViewById(R.id.hour);
            holder.resultBackground = (RelativeLayout)convertView
                    .findViewById(R.id.result_background);
            convertView.setTag(holder);
        }else{
            holder = (RouteResultViewHolder)convertView.getTag();
        }
        holder.fillHolder(getItem(position),mContext,isRider);
        loadBitmapFromUser(getItem(position).getUser(),holder.profilePic);

        return convertView;
    }


    public static class RouteResultViewHolder{
        TextView username;
        TextView companyPosition;
        TextView hour;
        ImageView profilePic;
        RelativeLayout resultBackground;

        public void fillHolder(Route item,Context context, boolean isRider){
            if(item!=null){
                User user = item.getUser();
                if(user!=null){
                    username.setText(user.getName());
                    companyPosition.setText(user.getJob());
                    if(item.ride!=null){
                        hour.setText(item.ride.getStartTimeStampString());
                    }else{
                        hour.setVisibility(View.GONE);
                    }
                    if(isRider) {
                        if (user.hasCar() && item.ride.isRideTimeValid()) {
                            resultBackground.setBackgroundDrawable(
                                    context.getResources().getDrawable(R.drawable.display_results_selector));
                        } else {
                            resultBackground.setBackgroundColor(context.getResources()
                                    .getColor(R.color.grey));
                        }
                    }
                }
            }
        }
    }

    public void loadBitmapFromUser(User user, final ImageView mProfileImage){
        if(ConnectionUtils.isNetworkAvailable(mContext)){
            Ion.with(mContext)
                    .load(user.getPhotoUrl())
                    .asBitmap()
                    .setCallback(new FutureCallback<Bitmap>() {
                        @Override
                        public void onCompleted(Exception e, Bitmap result) {
                            if (e != null) {
                                e.printStackTrace();
                            }
                            if(mProfileImage != null) {
                                mProfileImage.setImageBitmap(result);
                            }
                        }
                    });
        }else{
            ConnectionUtils.showConnetionError(mContext, 1);
        }
    }

    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
    }
}

2 answers

2

Suppose your ListView displays some data stored in a ArrayList. After changing the content of ArrayList, you need to tell the list that the data source had changed and it needs to redesign itself to show the new data. So this is where notifyDatasetChanged() that checks for change in your list and soon your list is redrawn:

adapter.notifyDataSetChanged();

The notifyDataSetChanged method is responsible for warning that there has been change in the data in the Adapter.

  • then, this method is in my Adapter. I had placed this call in several places in the code for verification, but failed.

1


I decided to go through a method that checks whether it is the same Ragment and whether or not it should be removed and inflated again. So it loads the new data.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.