Error: The method getFragmentManager () is undefined for the type ActivitiesListAdapter

1

How do I call a Fragment from a BaseAdapter? I'll call him at the click of the button, and I should also pass on some information.

I'm trying to call it this way:

Fragment fr = new Fragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container, fr);
fragmentTransaction.commit();

But it does give some errors:

  

The method getFragmentManager () is undefined for the type ActivitiesListAdapter

Here is the code for my adapter, it loads data from a json, assembles a list and has icons in that list that will do some action, in this case, click on CheckClickListener, is opening an activity, and passing some information, I need open a fragment instead and pass the same information.

public class ActivitiesListAdapter extends BaseAdapter {

    private static final int        DEPLETED__RED    = 3;
    private static final int        DEPLETED__YELLOW = 2;
    private static final int        DEPLETED__GREEN  = 1;
    private static final DateFormat FMT_DATE;

    static {
        DateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
        iso8601Format.setTimeZone(TimeZone.getTimeZone("UTC"));

        FMT_DATE = iso8601Format;
    }

    private ArrayList<JSONObject>   dataProvider     = new ArrayList<JSONObject>();
    private String[]                jsonColumns;
    private LayoutInflater          inflater;
    private OptionsVO               options;
    private Context                 context;
    private int                     imageResource;
    private BaseListener            imageCallback;
    private String[]                columnsToCompare;
    private ActivitiesListFragment  fragment;

    public ActivitiesListAdapter(JSONArray array, String[] jsonColumns, AbstractListFragment fragment) {
        for(int index = 0; index < array.length(); index++) {
            try {
                this.dataProvider.add(array.getJSONObject(index));
            }
            catch(JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        this.jsonColumns = jsonColumns;
        this.context = fragment.getContext();
        this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.options = ApplicationOptionsManager.getOptions(fragment.getActivity(), fragment.getNetworkAction());
        this.fragment = (ActivitiesListFragment) fragment;
    }

    public void setImageCondition(int imageResource, BaseListener imageCallback, String... columns) {
        this.columnsToCompare = columns;
        this.imageResource = imageResource;
        this.imageCallback = imageCallback;
    }

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

    @Override
    public Object getItem(int position) {
        return this.dataProvider.get(position);
    }

    @Override
    public long getItemId(int position) {
        return ((JSONObject) getItem(position)).optLong("id");
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;

        if(convertView == null) {
            final ViewHolder holder = new ViewHolder();

            view = this.inflater.inflate(R.layout.custom_list_activities, parent, false);
            view.setTag(R.string.HOLDER, holder);

            holder.icoPlay = (ImageView) view.findViewById(R.id.actionPlay);
            holder.icoCheck = (ImageView) view.findViewById(R.id.actionCheck);
            holder.title = (TextView) view.findViewById(R.id.title);
            holder.data = (TextView) view.findViewById(R.id.data);
            holder.icoAbort = (ImageView) view.findViewById(R.id.actionAbort);
            holder.icoInfo = (ImageView) view.findViewById(R.id.actionInfo);
            holder.icoScaled = (ImageView) view.findViewById(R.id.bar);

            holder.icoPlay.setTag(R.string.HOLDER, holder);
            holder.icoCheck.setTag(R.string.HOLDER, holder);
            holder.icoAbort.setTag(R.string.HOLDER, holder);
            holder.icoScaled.setTag(R.string.HOLDER, holder);
            holder.icoInfo.setTag(R.string.HOLDER, holder);

        }

        final ViewHolder holder = (ViewHolder) view.getTag(R.string.HOLDER);
        JSONObject item = (JSONObject) getItem(position);

        try {
            item.putOpt("currIndex", position);
        }
        catch(JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        holder.icoPlay.setTag(R.string.JSON, item);
        holder.icoCheck.setTag(R.string.JSON, item);
        holder.icoAbort.setTag(R.string.JSON, item);
        holder.icoScaled.setTag(R.string.JSON, item);
        holder.icoInfo.setTag(R.string.JSON, item);

        int cdDepleted = item.optInt("cdDepleted", -1);
        if(cdDepleted == DEPLETED__RED) {
            view.setBackgroundColor(Color.argb(127, 255, 0, 0));
        }
        if(cdDepleted == DEPLETED__YELLOW) {
            view.setBackgroundColor(Color.argb(127, 255, 255, 0));
        }
        if(cdDepleted == DEPLETED__GREEN) {
            view.setBackgroundColor(Color.argb(127, 0, 255, 0));
        }

        int fkIdArticle = item.optInt("fkIdArticle", -1);
        if(fkIdArticle != -1) {
            holder.icoInfo.setVisibility(View.VISIBLE);
        }
        else {
            holder.icoInfo.setVisibility(View.INVISIBLE);
        }

        boolean flScaled = item.optBoolean("flScaled", false);
        if(flScaled == true) {
            holder.icoScaled.setVisibility(View.VISIBLE);
        }
        else {
            holder.icoScaled.setVisibility(View.INVISIBLE);
        }

        int cdStatus = item.optInt("cdStatus", 1);
        if(cdStatus == 1) {
            holder.icoPlay.setVisibility(View.VISIBLE);
            holder.icoCheck.setVisibility(View.GONE);
            holder.icoAbort.setVisibility(View.GONE);
        }
        else {
            holder.icoPlay.setVisibility(View.GONE);
            holder.icoCheck.setVisibility(View.VISIBLE);
            holder.icoAbort.setVisibility(View.VISIBLE);
        }

        holder.icoPlay.setOnClickListener(new PlayClickListener());
        holder.icoCheck.setOnClickListener(new CheckClickListener());
        holder.icoAbort.setOnClickListener(new AbortClickListener());
        holder.icoInfo.setOnClickListener(new InfoClickListener());

        try {
            Date dt = FMT_DATE.parse(item.optString("dtStart"));
            Time tm = new Time(dt, new Date());
            item.putOpt("dtStartFmt", tm.speak());

        }
        catch(ParseException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        catch(JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if(this.columnsToCompare != null && this.columnsToCompare.length > 0) {
            final String[] colsToReturn = new String[this.columnsToCompare.length];
            boolean canShow = false;
            int i = 0;
            for(String col : this.columnsToCompare) {
                String optString = item.optString(col);
                if(optString != null && !optString.isEmpty()) {
                    canShow = true;
                }

                try {
                    colsToReturn[i++] = URLDecoder.decode(optString, "UTF-8");
                }
                catch(Exception e) {
                }
            }

            if(canShow) {
                holder.icoScaled.setVisibility(View.VISIBLE);
                holder.icoScaled.setImageDrawable(MobileUtils.getDrawable(this.context, this.imageResource));
                holder.icoScaled.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(imageCallback != null) {
                            try {
                                imageCallback.onCallback(new Object[] { colsToReturn });
                            }
                            catch(Exception e) {
                            }
                        }
                    }
                });
            }
            else {
                holder.icoScaled.setVisibility(View.GONE);
            }
        }

        try {
            holder.title.setText(URLDecoder.decode(decodeColumn(item, this.jsonColumns[0]).toString(), "UTF-8"));
            holder.assignCustomData(item, this.jsonColumns);
        }
        catch(Exception e) {
        }

        holder.icoAbort.setTag(R.id.tag_favorite_state, false);
        return(view);
    }

    private CharSequence decodeColumn(JSONObject item, String fieldName) {
        String rawValue = item.optString(fieldName);

        if(this.options != null && this.options.getDomains() != null && this.options.getDomains().length > 0) {

            OptionDomainVO[] domains = this.options.getDomains();
            outer: for(OptionDomainVO domain : domains) {
                String field = domain.getField();

                if(field != null && field.equals(fieldName)) {
                    OptionDomainValueVO[] values = domain.getValues();

                    for(OptionDomainValueVO val : values) {
                        if(val.getValue() != null && val.getValue().toString().equals(rawValue)) {
                            rawValue = val.getLabel();
                            break outer;
                        }
                    }
                }
            }
        }

        return rawValue;
    }

    class ViewHolder {
        ImageView icoPlay;
        ImageView icoCheck;

        TextView  title;
        TextView  data;

        ImageView icoAbort;
        ImageView icoInfo;
        ImageView icoScaled;

        public void assignCustomData(JSONObject item, String[] jsonColumns) {
            this.data.setText(null);
            this.data.setVisibility(View.GONE);

            extractValue(jsonColumns, 1, item);
            extractValue(jsonColumns, 2, item);
            extractValue(jsonColumns, 3, item);
            extractValue(jsonColumns, 4, item);
            extractValue(jsonColumns, 5, item);
            extractValue(jsonColumns, 6, item);
        }

        private void extractValue(String[] jsonColumns, int index, JSONObject item) {
            try {
                String col = jsonColumns[index];
                if(col != null && !col.isEmpty()) {
                    TextView line = getLine(index);
                    if(line != null) {
                        CharSequence value = decodeColumn(item, col);
                        if(value != null && !value.toString().isEmpty()) {
                            try {
                                line.setText(URLDecoder.decode(value.toString(), "UTF-8"));
                            }
                            catch(Exception e) {
                            }
                            line.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
            catch(ArrayIndexOutOfBoundsException e) {
            }
        }

        private TextView getLine(int index) {
            TextView text = null;

            switch(index) {
                case 1 :
                    text = this.data;
                    break;

            }

            return(text);
        }
    }

    public void clearItems() {
        this.dataProvider.clear();
        this.notifyDataSetChanged();
    }

    private class PlayClickListener implements OnClickListener {
        public void onClick(View v) {
            final ViewHolder holder = (ViewHolder) v.getTag(R.string.HOLDER);
            final JSONObject json = (JSONObject) v.getTag(R.string.JSON);
            holder.icoPlay.setVisibility(View.INVISIBLE);

            AbstractNetworkHandler handler = AbstractNetworkFactory.build(ActivitiesListAdapter.this.context, NetworkAction.ACTIVITIES_SAVE);
            handler.save(json, new HttpJsonObjectListener() {
                public void onRequestCompleted(JSONObject object, Integer httpStatus, CharSequence msg) {

                    boolean isOk = object.optBoolean("isOk", false);
                    boolean isNew = object.optBoolean("isNew", false);
                    int id = object.optInt("id", -1);

                    if(isOk == true) {
                        try {
                            json.put("cdStatus", 2);
                        }
                        catch(JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                        ActivitiesListAdapter.this.fragment.runRunnableOnUIThread(new Runnable() {
                            public void run() {
                                holder.icoPlay.setVisibility(View.GONE);

                                holder.icoCheck.setVisibility(View.VISIBLE);
                                holder.icoAbort.setVisibility(View.VISIBLE);
                            }
                        });

                        if(isNew == true) {

                            try {
                                json.put("fkIdCallStep", id);
                            }
                            catch(JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                        }

                    }
                    else {
                        ActivitiesListAdapter.this.fragment.runToastOnUiThread("Não foi possível efetuar sua ação", Toast.LENGTH_LONG);
                    }

                }
            }, new HttpFailListener() {
                public void onRequestCompleted(Exception e, Integer httpStatus, CharSequence msg) {
                    ActivitiesListAdapter.this.fragment.runToastOnUiThread("Erro de conectividade", Toast.LENGTH_LONG);
                }
            });
        }
    }

    private class AbortClickListener implements OnClickListener {
        public void onClick(View v) {
            final JSONObject json = (JSONObject) v.getTag(R.string.JSON);
            final ActivitiesListAdapter self = ActivitiesListAdapter.this;
            final ViewHolder holder = (ViewHolder) v.getTag(R.string.HOLDER);
            // holder.icoPlay.setVisibility(View.VISIBLE);

            AbstractNetworkHandler handler = AbstractNetworkFactory.build(ActivitiesListAdapter.this.context, NetworkAction.ACTIVITIES_SAVE);
            handler.save(json, new HttpJsonObjectListener() {
                public void onRequestCompleted(JSONObject object, Integer httpStatus, CharSequence msg) {

                    boolean isOk = object.optBoolean("isOk", false);
                    boolean isNew = object.optBoolean("isNew", false);
                    int id = object.optInt("id", -1);

                    if(isOk == true) {
                        try {
                            json.put("cdStatus", 1);
                        }
                        catch(JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                        ActivitiesListAdapter.this.fragment.runRunnableOnUIThread(new Runnable() {
                            public void run() {
                                holder.icoPlay.setVisibility(View.VISIBLE);

                                holder.icoCheck.setVisibility(View.GONE);
                                holder.icoAbort.setVisibility(View.GONE);
                            }
                        });

                        if(isNew == true) {

                            try {
                                json.put("fkIdCallStep", id);
                            }
                            catch(JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                        }

                    }
                    else {
                        ActivitiesListAdapter.this.fragment.runToastOnUiThread("Não foi possível efetuar sua ação", Toast.LENGTH_LONG);
                    }

                }
            }, new HttpFailListener() {
                public void onRequestCompleted(Exception e, Integer httpStatus, CharSequence msg) {
                    ActivitiesListAdapter.this.fragment.runToastOnUiThread("Erro de conectividade", Toast.LENGTH_LONG);
                }
            });
        }
    }

    private class InfoClickListener implements OnClickListener {
        public void onClick(View v) {
            HomeActivity home = (HomeActivity) context;
            Intent intent = new Intent(context, InfoFragment.class);

            intent.putExtra("EXTRA_INFO", "infomação extra");

            context.startActivity(intent);

            final JSONObject json = (JSONObject) v.getTag(R.string.JSON);
            final ActivitiesListAdapter self = ActivitiesListAdapter.this;
            /*
             * AbstractNetworkHandler handler = AbstractNetworkFactory.build(ActivitiesListAdapter.this.context, NetworkAction.ACTIVITIES_ABORT); handler.update(json, new HttpJsonObjectListener() { public void onRequestCompleted(JSONObject object, Integer httpStatus, CharSequence msg) { ActivitiesListAdapter.this.fragment.runRunnableOnUIThread(new Runnable() { public void run() { self.dataProvider.remove(json.optInt("currIndex")); self.notifyDataSetChanged(); } }); } }, new HttpFailListener() { public void onRequestCompleted(Exception e, Integer httpStatus, CharSequence msg) { ActivitiesListAdapter.this.fragment.runToastOnUiThread("Erro de conectividade", Toast.LENGTH_LONG); } });
             */
        }

    }

    private class CheckClickListener implements OnClickListener {
        public void onClick(View v) {
            final JSONObject json = (JSONObject) v.getTag(R.string.JSON);
            final ActivitiesListAdapter self = ActivitiesListAdapter.this;

            final boolean flQuick = json.optBoolean("flQuick", false);
            final String nmForm = json.optString("nmForm", "sem nmForm");

            AbstractNetworkHandler handler = AbstractNetworkFactory.build(self.context, NetworkAction.ACTIVITIES_QUICK_FINISH);

            handler.update(json, new HttpJsonObjectListener() {
                public void onRequestCompleted(JSONObject object, Integer httpStatus, CharSequence msg) {
                    ActivitiesListAdapter.this.fragment.runRunnableOnUIThread(new Runnable() {
                        public void run() {

                            if(flQuick == false) {
                                Intent intent = new Intent(context, NewActivity.class);

                                intent.putExtra("fkIdCallStep", json.optInt("fkIdCallStep"));
                                intent.putExtra("currIndex", json.optInt("currIndex"));
                                intent.putExtra("flQuick", flQuick);
                                intent.putExtra("nmForm", nmForm);

                                context.startActivity(intent);

                            }
                            else if(flQuick == true) {
                                // remover da lista do check
                                self.dataProvider.remove(json.optInt("currIndex"));
                                self.notifyDataSetChanged();
                            }

                            /*
                             * Animation anim = AnimationUtils.loadAnimation(context, android.R.anim.slide_out_right); anim.setDuration(500);
                             * 
                             * View listItem = self.fragment.getChildAt(itemPosition); listItem.startAnimation(anim);
                             * 
                             * new Handler().postDelayed(new Runnable() { public void run() { self.dataProvider.remove(itemPosition); self.notifyDataSetChanged(); } }, anim.getDuration());
                             */
                        }

                    });
                }
            }, new HttpFailListener() {
                public void onRequestCompleted(Exception e, Integer httpStatus, CharSequence msg) {
                    self.fragment.runToastOnUiThread("Erro de conectividade", Toast.LENGTH_LONG);
                }
            });
        }
    }

    public void addAll(JSONArray array) {
        for(int index = 0; index < array.length(); index++) {
            try {
                this.dataProvider.add(array.getJSONObject(index));
            }
            catch(JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        this.notifyDataSetChanged();
    }
}
    
asked by anonymous 15.11.2015 / 11:44

1 answer

1

You are trying to access the getFragmentManager() method that does not exist in the ActivitiesListAdapter class.

getFragmentManager() is a method that exists in the Activity and Fragment classes.

The posted code snippet works when it is being used in one of these classes.

In this case, you have to use the fragment object passed in the constructor to get the FragmentManager .

Fragment fr = new Fragment();

//Linha alterada
FragmentManager fm = fragment.getFragmentManager();

FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container, fr);
fragmentTransaction.commit();

This change will resolve the displayed error. If your code has a problem or not, I do not know why it is too confusing: I think your adapter has too many responsibilities.

    
15.11.2015 / 16:50