简体   繁体   English

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

[英]Can not stop showing repeating data from json parser in my App

I have an app that receives json data from a website and then parse it to show on my app programmatically. 我有一个应用程序,该应用程序从网站接收json数据,然后解析它以编程方式显示在我的应用程序上。 The problem that I am facing right now is if i close the app and restart it, the same data gets repeated and that I don't want. 我现在面临的问题是,如果我关闭应用程序并重新启动它,则相同的数据会重复出现,而我却不想这样做。 So please someone help me to solve this. 所以请有人帮我解决这个问题。 Following is the code of the class that maps the data into my app. 以下是将数据映射到我的应用程序的类的代码。

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);
        }
    });
}




}

I'm not sure what you mean by repeating itself. 我不确定您重复一遍是什么意思。 Do you mean you get the json data twice or do you mean it downloads the json data again? 您是说两次获取json数据,还是再次下载json数据?

Anyway, as far you execute the json Parse on the onCreate, the json data will downloaded each time you close and open the Activity again. 无论如何,就您在onCreate上执行json解析而言,每次关闭并再次打开Activity时,都会下载json数据。

Also don't use onResume as a function. 也不要将onResume用作函数。 It looks like everytime you reenter the Activity the JSON Parser and as well the Android LifeCycle opens the onResume. 似乎每次您重新输入Activity时,JSON解析器都会显示,Android LifeCycle也会打开onResume。 This means, your setting TextViews code in onResume is executed twice, because the JSON Parser and the normal onResume Call will be executed twice. 这意味着,您在onResume中设置的TextViews代码将执行两次,因为JSON解析器和常规onResume调用将被执行两次。 Try to move the code in onResume somewhere else and then call this method in onPostExecute. 尝试将代码在onResume中移动到其他位置,然后在onPostExecute中调用此方法。

每次调用时,您都必须清除ModelProducts.class

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM