JSON 每当我按下后退按钮时片段增加

JSON Increased in Fragment whenever I press back button

我有一个名为 HomeFragment 的片段,其中包含 JSON 中请求使用 Volley 的 GridView 列表。它成功地显示 JSON,但问题是当我转到另一个片段或 activity 然后再次返回到 HomeFragment 时,GridView 中的 JSON 是 increased/added 再次使用相同的数据。

如何停止这样数据就不会增加。

HomeFragment中有我的代码

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    view = inflater.inflate(R.layout.fragment_home, container, false);;
    getActivity().setTitle("Dashboard");

    final HashMap<String, String> role = sharedPreference.getDetails();
    String url = "http://myurl";

    RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject obj = new JSONObject(response);
                JSONArray array = obj.getJSONArray("data");
                for (int i = 0; i < array.length(); i++) {
                    JSONObject data = array.getJSONObject(i);
                    String menu_id = data.getString("menu_id");
                    String menu_name = data.getString("menu_name");

                    HashMap<String, String> row = new HashMap<>();
                    row.put("menu_id", menu_id);
                    row.put("menu_name", menu_name);

                    menulist.add(row);

                    Log.e(TAG, "onResponse: " + menulist );

                    GridView gridView = (GridView) view.findViewById(R.id.menu_item_grid);
                    ListAdapter listAdapter = new SimpleAdapter(getContext(), menulist,
                            R.layout.home_menu, new String[]{"menu_name"},
                            new int[]{R.id.item_grid});
                    gridView.setAdapter(listAdapter);
                }
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getContext(), "error : " + error, Toast.LENGTH_SHORT).show();
        }
    });

    queue.add(stringRequest);
    return view;
}

the result

谢谢..

当您转到另一个 fragment/activity 时,您的 HomeFragment 不会立即被销毁,因此它的值 (menulist) 仍会保留。但是当你回到它时,视图又被创建了,API 中的新数据被添加到之前的列表中。

在您的 onResponse() 方法中,用 menulist.clear()

清除 menulist
menulist.clear();
JSONObject obj = new JSONObject(response);
JSONArray array = obj.getJSONArray("data");

这不会减少 API 次调用,但会保持数据一致。

当您从 HomeFragmnt 转到 OtherFragment 并按下时 onCreateView()HomeFragment 中再次调用,因此您的请求再次调用,因此您的数据是重复的。

您应该使 BaseFragment 执行以下代码。它会帮助你。

Java 帮助

BaseFragment.java

public class BaseFragment<T> extends Fragment {

    public boolean hasInitializedRootView = false;

    private View rootView;

    public View getPersistentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState, int layout){
        if (rootView == null) {
            rootView = inflater.inflate(layout, container, false);
        } else {
            ((ViewGroup) rootView.getParent()).removeView(rootView);
        }

        return rootView;
    }
    
}

HomeFragment.java

public class HomeFragment extends BaseFragment<View> {

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        return getPersistentView(inflater, container, savedInstanceState, R.layout.fragment_home);
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        if (!hasInitializedRootView) {
            hasInitializedRootView = true;

            // Do your work here

        }

    }
}

Kotlin 帮助

BaseFragment.kt

open class BaseFragment<T : View> : Fragment() {

    var hasInitializedRootView = false
    private var rootView: View? = null

    fun getPersistentView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
        layout: Int
    ): View? {
        if (rootView == null) {
            rootView = inflater.inflate(layout, container, false)
        } else {

            (rootView?.parent as? ViewGroup)?.removeView(rootView)
        }

        return rootView
    }

}

HomeFragment.kt

class HomeFragment : BaseFragment<View>() {
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return getPersistentView(inflater, container, savedInstanceState, R.layout.fragment_home)
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        if (!hasInitializedRootView) {
            hasInitializedRootView = true

            // Do your work here

        }
    }
}