每次都会调用AsyncTask

时间:2014-11-03 06:44:23

标签: android android-fragments android-asynctask

我有navigation drawer包含2个项目。现在在我的第一个项目点击中,我使用asynctask加载数据,并且加载的数据填充在相应片段的列表视图中。现在,当我切换到第二项时,我再次使用AsyncTask为第二个片段加载数据并在列表视图中显示它。

  

现在问题开始了。当我回到第一个片段时,我的   再次调用asyncTask,再次从中获取数据   服务器,我想防止这种情况并直接加载我的数据   已经加载了一次。

请建议

P.S - 如果有人需要,请询问代码。     USERPAYFRAGMENT

public class UserPay extends Fragment {

ProgressDialog prg;
Properties prop;

private PrefSingleton mMyPreferences;
private JSONParser jsonParser = new JSONParser();

ArrayList<HashMap<String, String>> RequestList;
HashMap<String, String> map;
UserAdapter req_adp;
ListView req;
private boolean flag;

@Override
public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);
    Toast.makeText(getActivity(), "ATTACHED", 1000).show();
}

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setRetainInstance(true);
    Toast.makeText(getActivity(), "CREATE", 1000).show();
}

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

    View rootView = inflater.inflate(R.layout.user_pay, container, false);

    initViews(rootView);
    Toast.makeText(getActivity(), "ONCREATEVIEW", 1000).show();
    return rootView;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {

    super.onActivityCreated(savedInstanceState);

    Toast.makeText(getActivity(), "ONACTIVITYCREATED", 1000).show();
    mMyPreferences = PrefSingleton.getInstance();
    mMyPreferences.Initialize(getActivity());
    RequestList = new ArrayList<HashMap<String, String>>();

    Resources resources = this.getResources();
    AssetManager assetManager = resources.getAssets();
    try {
        InputStream inputStream = assetManager.open("jsonURL.properties");
        prop = new Properties();
        prop.load(inputStream);
    } catch (IOException e) {
        System.err.println("Failed to open jsonURL property file");
        e.printStackTrace();
    }

    req_adp = new UserAdapter(getActivity(), RequestList);
    req.setAdapter(req_adp);

    if (!flag) {
        new GetRequests().execute();
    } else {

    }
}

@Override
public void onStart() {
    // TODO Auto-generated method stub
    super.onStart();
    Toast.makeText(getActivity(), "ONSTART", 1000).show();
}

@Override
public void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    Toast.makeText(getActivity(), "ONRESUME", 1000).show();
}

private void initViews(View v) {
    req = (ListView) v.findViewById(R.id.req_list);

}

private class GetRequests extends AsyncTask<Void, Void, Integer> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        prg = new ProgressDialog(getActivity());
        prg.setIndeterminate(true);
        prg.setMessage("Fetching Pending Requests...");
        prg.setCanceledOnTouchOutside(false);
        prg.show();
    }

    @Override
    protected Integer doInBackground(Void... params) {

        List<NameValuePair> params1 = new ArrayList<NameValuePair>();
        params1.add(new BasicNameValuePair("userID", mMyPreferences
                .getPreference("LoginId")));

        String error_code = null;
        Log.e("URL ", "is" + prop.getProperty("GET_REQUESTS_URL"));

        try {
            // getting JSON string from URL
            JSONObject json = jsonParser.makeHttpRequest(
                    Appconstant.GET_REQUESTS_URL, "POST", params1);

            // Check your log cat for JSON response
            Log.d("Inbox JSON: ", json.toString());

            JSONObject jsonObj = json.getJSONObject("data");
            error_code = jsonObj.getString("Error_Code");
            RequestList.clear();

            if ("1".equals(error_code)) {

                JSONArray jArray = jsonObj.getJSONArray("result");
                for (int i = 0; i < jArray.length(); i++) {
                    map = new HashMap<String, String>();

                    JSONObject jsonObj1 = jArray.getJSONObject(i);
                    String FBankId = jsonObj1
                            .getString("payment_from_bank_id");
                    String DestBankId = jsonObj1
                            .getString("payment_to_bank_id");
                    String FBank = jsonObj1.getString("fBank");
                    String TBank = jsonObj1.getString("tBank");
                    String reason = jsonObj1.getString("payment_reason");
                    String amt = jsonObj1.getString("amount");
                    String p_type = jsonObj1.getString("payment_type");
                    String status = jsonObj1.getString("status");
                    String r_date = jsonObj1
                            .getString("request_created_date");

                    map.put("FBankId", FBankId);
                    map.put("TBankId", DestBankId);
                    map.put("SourceBank", FBank);
                    map.put("DestBank", TBank);
                    map.put("ReqDate", r_date);
                    map.put("PayReason", reason);
                    map.put("Amt", amt);
                    map.put("PayType", p_type);
                    map.put("Status", status);

                    if (status.equals("pending")) {
                        if (p_type.equals("cheque")
                                || p_type.equals("Net Banking")) {
                            RequestList.add(map);
                        }
                    }
                }
            }
        } catch (JSONException e) {

            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return Integer.parseInt(error_code);
    }

    @Override
    protected void onPostExecute(Integer result) {
        super.onPostExecute(result);

        if (prg.isShowing()) {
            prg.cancel();
        }

        if (result == 2) {
            Toast.makeText(getActivity(),
                    "No User Request Details Available.Please Try Again",
                    Toast.LENGTH_SHORT).show();
        }
        req_adp.notifyDataSetChanged();
        flag = true;
    }
}

@Override
public void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    Toast.makeText(getActivity(), "ONPAUSE",1000).show();
}

@Override
public void onStop() {
    // TODO Auto-generated method stub
    super.onStop();
    Toast.makeText(getActivity(), "ONSTOP", 1000).show();
}

@Override
public void onDestroyView() {
    // TODO Auto-generated method stub
    super.onDestroyView();
    Toast.makeText(getActivity(), "ONDESTROYVIEW", 1000).show();
}

@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    Toast.makeText(getActivity(), "ONDESTROY", 1000).show();
}

@Override
public void onDetach() {
    // TODO Auto-generated method stub
    super.onDetach();
    Toast.makeText(getActivity(), "ONDETACH", 1000).show();
}
}

1 个答案:

答案 0 :(得分:1)

有两种方法可以解决

1 - 在本地存储数据,并根据适当的条件检查使用存储的数据

2 - 如果您的应用基于这两个片段,只需创建这些片段的实例并存储在父活动的成员变量中。不要给一次又一次重建的机会