1

Tenho um Fragment que, clicado num RadioButton, é calculado uma rota, após este calculo de rotas, é mostrado um ListView com os resultados.

Ao clicar na outra opção deste radiobuttom, é novamente calculada as rotas e mostrado os novos resultados.

Problema: Ao subir estes novos resultados, os antigos, não são retirados da tela.

Como posso remove-los e colocar somente os novos resultados?

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 Respostas 2

2

Suponha que seu ListView exibe alguns dados armazenados em um ArrayList. Depois de alterar o conteúdo do ArrayList, você precisa dizer a lista que a fonte dos dados tinha mudado e ele precisa redesenhar próprio para mostrar os novos dados. Então, esse é o lugar onde notifyDatasetChanged() que verifica se há mudança na sua lista e logo é redesenhado sua lista:

adapter.notifyDataSetChanged();

O método notifyDataSetChanged é responsável por avisar que houve mudança nos dados que estão no Adapter.

1
  • então, este método está no meu adapter. Eu havia colocado esta chamada em vários lugares no código para a verificação, mas não obtive sucesso.
    – Henrique
    Commented 16/09/2016 às 19:07
1

Resolvi passando por um metodo que verifica se é o mesmo fragment e se deve ou não ser removido e inflado novamente. Assim ele carrega os dados novos.

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .