gpt4 book ai didi

java - 递增 int 创建 HashMap

转载 作者:太空宇宙 更新时间:2023-11-04 15:17:43 24 4
gpt4 key购买 nike

我只是通过在 JSON 的帮助下获取数据来更新我的 ListView ,但是我想每 5 秒执行一次,通过增加一个计数器,这意味着;获取数据后,当计数器>=5时,将计数器设置为0,这样当计数器为5时,就会再次刷新。

获取数据工作正常,无需使用 if 语句检查计数器值。

当 if 语句为 true 时,我不确定应该在哪里键入 if 语句才能获取结果。

这是我的整个类(class);

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

}

}

}

最佳答案

似乎您不需要在 TimerTask 中添加任何 if 条件。如果您想在 5 秒后启动计时器,并每 5 秒启动下一个请求。比做

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

如果您想立即开始任务,请将延迟降至最低。

尝试一下,希望能成功。

关于java - 递增 int 创建 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20732039/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com