【问题标题】:data load twice... means AsyncTask onPostExecute load same data twice?数据加载两次...意味着 AsyncTask onPostExecute 两次加载相同的数据?
【发布时间】:2016-03-10 06:20:55
【问题描述】:

数据加载两次...意味着 AsyncTask onPostExecute 两次加载相同的数据? 我的 AsyncTask onPostExecute 运行两次它加载相同的数据... 我正在运行异步任务以从服务器加载结果。在gridview中显示数据但数据显示两次..我对为什么AsyncTask输出数据两次感到困惑。 请帮助我 这是我的代码:

public class InfoAccountsascyn extends AsyncTask <String, String, String>{

    String result;
    String s;
    private Activity activity;
    private String url;
    private String user_id;
    private ProgressDialog pDialog;
    JSONObject json;
    JSONParser jsonParser = new JSONParser();
    private static final String TAG_SUCCESS = "Success";
    int Success;

    public InfoAccountsascyn(Activity activity, String url,String user_id) {
        super();
        this.activity = activity;
        this.url = url;
        this.user_id=user_id;
    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(activity);
        pDialog.setMessage("Loading Items...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.setCanceledOnTouchOutside(false);
        pDialog.show();
    }

    protected String doInBackground(String... args) {
        try {

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("customer_id", user_id));
            //if(Last_id!=null){
            // params.add(new BasicNameValuePair("last_product_id", Last_id));
            // }

            json = jsonParser.makeHttpRequest(url, "POST", params);

            Success = json.getInt(TAG_SUCCESS);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (Success == 1) {
            result = json.toString();
        }else{
            try {
                result = json.getString("CartData");
                //s=result;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    protected void onPostExecute(String result) {
        ((DetaildAddress) activity).parseJsonResponse(result);
        pDialog.dismiss();

   }
   }

这是 parseJsonResponse

public void parseJsonResponse(String result) {

String res = result;
    if (res !=null) {
        try {
            JSONObject jObjects = new JSONObject(result);
            JAS = jObjects.getJSONArray("Data");
            for (int i = 0; i < JAS.length(); i++) {
                JSONObject c = JAS.getJSONObject(i);
                DetailedAddressInfo productinfo = new DetailedAddressInfo();
                productinfo.setFirstname(c.optString("firstname"));
                productinfo.setLastname(c.optString("lastname"));
                productinfo.setStreet(c.optString("street"));
                productinfo.setCity(c.optString("city"));
                productinfo.setRegion(c.optString("region"));
                productinfo.setPostcode(c.optString("postcode"));
                productinfo.setTelephone(c.optString("telephone"));
                productinfo.setFax(c.optString("fax"));
                productinfo.setAddId(c.optString("customer_address_id"));
                productinfo.setBilling(c.optString("is_default_billing"));
                productinfo.setShipping(c.optString("is_default_shipping"));


                products.add(productinfo);
                if (i == JAS.length() - 1) {
                    Last_id = c.optString("product_id");
                }
            }
            adapter = new DetailedAddressAdapter(DetaildAddress.this, R.layout.deshbord_address, products);
            gridView.setAdapter(adapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    else {
        new AlertDialog.Builder(DetaildAddress.this)
        .setTitle("No Address Available")
                .setMessage("You Want to Add New Address")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent=new Intent(DetaildAddress.this,NewAddress.class);
                        String ok = "0";
                        intent.putExtra("ok", ok);
                        startActivity(intent);
                    }
                })
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // do nothing
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();
    } if (pDialog != null) {
        pDialog.dismiss();
    }
}

这是我调用 AsyncTask 的 OnCreate

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detaild_address);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    stub = (ViewStub) findViewById(R.id.layout_stub);
    stub.setLayoutResource(R.layout.content_detaild_address);
    View inflated = stub.inflate();

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    String check = "0";
    String chEck;
    DBHandler db = new DBHandler(DetaildAddress.this);
    List<DBconnector> Contacts = db.getAllContacts();
    for (DBconnector cn : Contacts) {
        chEck = cn.getActive();
        if(chEck != null){
            if (chEck.equals("1")){
                check = chEck;
            }
        }
    }
    if (check.equals("1")) {
        List<DBconnector> contacts = db.getActiveData();

        for (DBconnector c : contacts) {
            Customer_id = c.getCustomer_id();
            //new CheckAddress().execute();
            boolean connected = false;
            ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
            if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
                    connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
                //we are connected to a network
                new InfoAccountsascyn(DetaildAddress.this,url_address,Customer_id).execute();
            }
            else
            {
                Toast.makeText(DetaildAddress.this,"Internet Connection is not Available",Toast.LENGTH_LONG).show();
                Intent intent=new Intent(DetaildAddress.this,HomeActivity.class);
                startActivity(intent);
                connected = false;
            }

        }

    }
    else{
        Toast.makeText(DetaildAddress.this, "Please login First", Toast.LENGTH_LONG).show();
        Intent intent = new Intent(DetaildAddress.this, UserLogin.class);
        startActivity(intent);
    }
    gridView = (GridView) findViewById(R.id.gridView1);
    myLastVisiblePos = gridView.getFirstVisiblePosition();
    products = new ArrayList<DetailedAddressInfo>();
    //gridView.setAdapter(new DetailedAddressAdapter(DetaildAddress.this, R.layout.deshbord_address, products));

    TextView newaddress=(TextView)findViewById(R.id.newaddress);
    newaddress.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent=new Intent(DetaildAddress.this,NewAddress.class);
            String ok = "0";
            intent.putExtra("ok", ok);
            startActivity(intent);
        }
    });
}

【问题讨论】:

  • 我认为这与您的 AsyncTask 无关。对我来说看起来还不错。将适配器粘贴到您要填充数据的位置。重新加载列表/网格时,您可能没有清除数据集。这是一个常见的错误。
  • 您是否在同一个 InfoAccountsascyn 实例上多次调用 execute()?
  • 请再检查一遍
  • 发布您调用此异步任务的代码部分
  • 再次检查我调用此异步任务的部分代码

标签: android android-asynctask


【解决方案1】:

您应该在初始化 JSONObject 之前使用 Arraylist 的 clear() 方法,如下所示:

if(products.size()>0)
 products.clear();

【讨论】:

  • 因为你创建了arraylist的对象一次但是你一次又一次地添加相同的数据这就是为什么它需要清除arraylist。
  • 我有 4 个地址 ok.. 它加载 4 个地址并再次加载相同的 4 个地址...问题是 AsyncTask onPostExecute 方法再次自动调用 onPostExecute 方法运行两次..这就是问题...
  • 一件事如果我在 gridview 中设置适配器之前调用 Adapter.clear()..address 没有显示两次,但这不是完美的解决方案..
  • 为什么你的 doInBackground 和 postExecute 没有被 AsyncTask 覆盖??
【解决方案2】:

我也遇到了同样的问题。我在代码中发现了一个小问题,即 我没有关闭对话框,我在 AsyncTask 的 onPostExecute() 中打开该对话框是为了在 AsyncTask Work 之后做一些额外的工作。

当我打电话给myCustomDialog.dismiss() 时,一切正常。

【讨论】:

    猜你喜欢
    • 2016-04-27
    • 2022-08-11
    • 1970-01-01
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 2021-05-21
    • 1970-01-01
    相关资源
    最近更新 更多