增加int以创建HashMap

时间:2013-12-22 17:27:13

标签: java android json

我只是通过在JSON的帮助下获取数据来更新我的列表视图,但是我想通过递增计数器来每5秒执行一次,这意味着;当计数器在获取数据后> gt = = 5然后将计数器设置为0,因此当它为5时它将再次刷新。

使数据完美无缺,没有检查计数器值的if语句。

当if语句为真时,我不确定在哪里键入if语句来获取结果。

这是我的全班;

public class AllProductsActivity extends ListActivity {
 int delay = 5000; // delay for 5 sec.
 int period = 1000; // repeat every sec.
 int counterr=0;
 // Progress Dialog
 private ProgressDialog pDialog;
 public boolean refresh=false;
 // Creating JSON Parser object
 JSONParser jParser = new JSONParser();

 ArrayList<HashMap<String, String>> productsList;

 // url to get all products list
private static String url_all_products = "http://XXXXXXX.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";
// products JSONArray
JSONArray products = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_products);
    //counterr=100;
    Timer timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask()
    {
        public void run()
        {
           // Your code

            counterr++;
            System.out.println("COun "+counterr);
            System.out.println("Refresh?  "+refresh);

            if(counterr>=3)
                refresh=true;
        }
    }, delay, period);

    // Hashmap for ListView
    productsList = new ArrayList<HashMap<String, String>>();

    // Loading products in Background Thread
    new LoadAllProducts().execute();

    // Get listview
    ListView lv = getListView();

    // on seleting single product
    // launching Edit Product Screen
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                    .toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(),
                    EditProductActivity.class);
            // sending pid to next activity
            in.putExtra(TAG_PID, pid);

            // starting new activity and expecting some response back
            startActivityForResult(in, 100);
        }
    });

}

// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // if result code 100
    if (resultCode == 100) {
        // if result code 100 is received 
        // means user edited/deleted product
        // reload this screen again
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

}

/**
 * Background Async Task to Load all product by making HTTP Request
 * */
class LoadAllProducts extends AsyncTask<String, String, String> {
    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {

        super.onPreExecute();
        pDialog = new ProgressDialog(AllProductsActivity.this);
        pDialog.setMessage("Loading products. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();

    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
            // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG

            int success = json.getInt(TAG_SUCCESS);
            System.out.println(success);

            if (success == 1){// && counterr>=5) {

                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);

                // looping through All Products
                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_PID);
                    String name = c.getString(TAG_NAME);
                    String price = c.getString(TAG_PRICE);
                    String description = c.getString(TAG_DESCRIPTION);


                    //if(counterr>=5){
                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();
                    // adding each child node to HashMap key => value
                    map.put(TAG_PID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_PRICE, "" + price);
                    map.put(TAG_DESCRIPTION, description);
                    // adding HashList to ArrayList
                    productsList.add(map);
                    counterr=0;
                    refresh=false;
                    }
                        }

                //counterr=0;
    // }

          else {
                // no products found
                // Launch Add New product Activity
                Intent i = new Intent(getApplicationContext(),
                        NewProductActivity.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        AllProductsActivity.this, productsList,
                        R.layout.list_item, new String[] { TAG_PID,
                                TAG_NAME, TAG_PRICE, TAG_DESCRIPTION},
                        new int[] { R.id.pid, R.id.name, R.id.price, R.id.description });
                // updating listview
                setListAdapter(adapter);
            }
        });

    }

}

}

2 个答案:

答案 0 :(得分:0)

似乎你不需要在TimerTask中放入任何if条件。如果要在5秒后启动计时器,则每5秒启动一次计时器。而不是

int delay = 5000; // delay for 5 sec.
int period = 5000; // repeat after every 5 sec.

如果您想立即启动任务,请将延迟减少到最小值。

试试希望它会起作用。

答案 1 :(得分:0)

通过实施这一点;在public void run(){

  if(counterr>=5){
    counterr=0;
        json = jParser.makeHttpRequest(url_all_products, "GET", params);
        Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
        startActivity(i);
  }

诀窍!