无法停止在我的应用程序中显示来自json解析器的重复数据

时间:2014-06-10 10:53:00

标签: java android json

我有一个应用程序从网站接收json数据,然后解析它以编程方式显示在我的应用程序上。我现在面临的问题是,如果我关闭应用程序并重新启动它,相同的数据会重复,我不想要。所以请有人帮我解决这个问题。以下是将数据映射到我的应用程序的类的代码。

public class FirstScreen extends Activity {
// int numberquantity;
JSONParse Jp=new JSONParse();


// URL to get JSON Array
private static String url = "http://10.0.2.2/SUPERSHOP/supershop_api.php";


private static final String TAG_USER = "record";
private static final String TAG_NAME = "Name";
private static final String TAG_PRICE = "Price";
private static final String TAG_IMAGE_PATH="http://10.0.2.2/bootstrap-dist/images/";

private static final String TAG_DESCRIPTION = "Description";



JSONArray user = null;
//  private ProgressDialog pDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Controller aController = (Controller) getApplicationContext();
    aController.getCart().clearCart();
    Jp.execute();


}

Bitmap drawable_from_url(String url) throws java.net.MalformedURLException, java.io.IOException {
    Bitmap x;

    HttpURLConnection connection = (HttpURLConnection)new URL(url) .openConnection();
    connection.setRequestProperty("User-agent","Mozilla/4.0");

    connection.connect();
    InputStream input = connection.getInputStream();

    x = BitmapFactory.decodeStream(input);
    return x;
 }


private class JSONParse extends AsyncTask<String, String, JSONObject> {
    private ProgressDialog pDialog;



    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(FirstScreen.this);
        pDialog.setMessage("Getting Data ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected JSONObject doInBackground(String... args) {
        JSONParser jParser = new JSONParser();
        // Getting JSON from URL
        JSONObject json = jParser.getJSONFromUrl(url);
        return json;
    }

    @Override
    protected void onPostExecute(JSONObject json) {
        pDialog.dismiss();
        Controller aController = (Controller) getApplicationContext();
        ModelProducts productObject = null;




        JSONObject c=null;
        try {
            // Getting JSON Array
            user = json.getJSONArray(TAG_USER);


            for(int i=0;i<user.length();i++){


                 c = user.getJSONObject(i);
                // Storing JSON item in a Variable
                    String name = c.getString(TAG_NAME);
                    String prices= c.getString(TAG_PRICE);  
                    int price=Integer.parseInt(prices);
                    String description = c.getString(TAG_DESCRIPTION);  

                    String imagePath=c.getString("Picture");

                    String Url=imagePath;







                    // Create product model class object


                    productObject = new ModelProducts(name,description,Url, price, 0, 0);

                    // store product object to arraylist in controller
                    aController.setProducts(productObject);




                    onResume();


            }


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

/******************end of parser****************************/

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();


    Bitmap bitmap;

    // ImageLoader class instance
    ImageLoader imgLoader = new ImageLoader(getApplicationContext());





    setContentView(R.layout.firstscreen);

    final LinearLayout lm = (LinearLayout) findViewById(R.id.linearMain);
    final Button secondBtn = (Button) findViewById(R.id.second);
    ModelProducts productObject = null;

    // Get Global Controller Class object (see application tag in
    // AndroidManifest.xml)
    final Controller aController = (Controller) getApplicationContext();





    /****************** Products Data Creation Begins ***********/

    /******* Create view elements dynamically and show on activity ******/

    // Product arraylist size
    int ProductsSize = aController.getProductsArraylistSize();

    // create the layout params that will be used to define how your
    // button will be displayed
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

    /******** Dynamically create view elements - Start **********/

    for (int j = 0; j < ProductsSize; j++) {
        // Get probuct data from product data arraylist


        String pName = aController.getProducts(j).getProductName();
        final String pDsc = aController.getProducts(j).getProductDesc();
        String pUrl=aController.getProducts(j).getImageUrl();
        final int pPrice = aController.getProducts(j).getProductPrice();
        // int pQuantity = aController.getProducts(j).getProductQuantity();
        //Toast.makeText(FirstScreen.this,pUrl, Toast.LENGTH_SHORT).show();

        // Create LinearLayout to view elemnts
        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);



        // settingup images to show in cataglog
        ImageView image = new ImageView(this);

        imgLoader.DisplayImage("http://10.0.2.2/bootstrap-dist/"+pUrl, image);


        //ll.addView(image);
        ll.addView(image);

        TextView product = new TextView(this);
        product.setText(" " + pName + "    ");

        // Add textView to LinearLayout
        ll.addView(product);

        TextView price = new TextView(this);
        price.setText(pPrice +":  Tk"+ "     ");

        // Add textView to LinearLayout
        ll.addView(price);

        TextView quantity = new TextView(this);
        quantity.setText(" " + "Quantity:" + "    ");

        // Add textView to LinearLayout
        ll.addView(quantity);

        final EditText inpquantity = new EditText(this);
        inpquantity.setText("1");

        ll.addView(inpquantity);

        final Button btn = new Button(this);
        btn.setId(j + 1);
        ModelProducts tempProductObject = aController.getProducts(j);
        if (!aController.getCart().checkProductInCart(tempProductObject)) {
            btn.setText("Add To Cart");
        }else{
            btn.setText("Added");
        }
        //btn.setText("Add To Cart");

        // set the layoutParams on the button
        btn.setLayoutParams(params);

        final int index = j;

        //to stop the keypad from popping up

        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);



        // Created click listener for dynamically created button
        btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {

                int numberquantity = Integer.parseInt(inpquantity.getText()
                        .toString());
                int trackID = 0;

                // ModelProducts productobj=new ModelProducts(pName, pDsc,
                // pPrice,numberquantity);
                aController.updateProduct(index).setProductQuantity(
                        numberquantity);

                // Clicked button index
                Log.i("TAG", "index :" + index);

                // Get product instance for index
                ModelProducts tempProductObject = aController
                        .getProducts(index);

                // Check Product already exist in Cart or Not
                if (!aController.getCart().checkProductInCart(
                        tempProductObject)) {

                    btn.setText("Added");

                    // saving data of button id of items added to cart to a
                    // shared preference.
                    trackID = btn.getId();

                    // Product not Exist in cart so add product to
                    // Cart product arraylist

                    aController.getCart().setProducts(tempProductObject);

                    Toast.makeText(
                            getApplicationContext(),
                            "Now Cart size: "
                                    + aController.getCart().getCartSize(),
                            Toast.LENGTH_LONG).show();



                } 
            }
        });

        // Add button to LinearLayout
        ll.addView(btn);

        // Add LinearLayout to XML layout
        lm.addView(ll);
    }

    // aController.getProductsArraylist().clear();
    /******** Dynamically create view elements - End **********/

    secondBtn.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {

            Intent i = new Intent(getBaseContext(), Secondscreen.class);
            startActivity(i);
        }
    });
}




}

2 个答案:

答案 0 :(得分:0)

我不确定你重复自己的意思。你是说你得到两次json数据还是意味着它再次下载json数据?

无论如何,只要你在onCreate上执行json Parse,每次你关闭并再次打开Activity时都会下载json数据。

也不要将onResume用作功能。看起来每次重新输入活动时JSON Parser以及Android LifeCycle都会打开onResume。这意味着,你在onResume中设置TextViews代码会被执行两次,因为JSON Parser和普通onResume Call将被执行两次。尝试将onResume中的代码移动到其他位置,然后在onPostExecute中调用此方法。

答案 1 :(得分:0)

每次调用

时都必须清除ModelProducts.class