我正在尝试使用共享偏好设置保存点击次数,因此当我返回应用时,它可以检索最后一个号码,而这里没有工作的是代码。谢谢你的帮助。 公共类MainActivity扩展了Activity {
private ListView GetAllAreasListView;
private JSONArray jsonArray;
private int AllRequestsCount;
private int i;
private final String AllRequests = "AllRequests";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Restore preferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
i = prefs.getInt(AllRequests, 0);
this.GetAllAreasListView = (ListView) this.findViewById(R.id.get_all_areas);
new GetAllImageTask().execute(new ApiConnector());
this.GetAllAreasListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try
{
// GEt the customer which was clicked
JSONObject customerClicked = jsonArray.getJSONObject(position);
// Send Customer ID
Intent showDetails = new Intent(getApplicationContext(),AreaDetailsActivity.class);
showDetails.putExtra("ImageID", customerClicked.getInt("id"));
startActivity(showDetails);
i = countClick();
saveInt();
System.out.println(i);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
});
}
public void setListAdapter(JSONArray jsonArray)
{
this.jsonArray = jsonArray;
this.GetAllAreasListView.setAdapter(new GetAllAreasListViewAdapter(jsonArray,this));
}
private class GetAllImageTask extends AsyncTask<ApiConnector,Long,JSONArray>
{
@Override
protected JSONArray doInBackground(ApiConnector... params) {
// it is executed on Background thread
return params[0].GetAllAreas();
}
@Override
protected void onPostExecute(JSONArray jsonArray) {
setListAdapter(jsonArray);
}
}
protected void onResume() {
super.onResume();
new GetAllImageTask().execute(new ApiConnector());
}
public int countClick(){
AllRequestsCount++;
return(AllRequestsCount);
}
public void saveInt(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(AllRequests,i);
editor.commit();
}
}
答案 0 :(得分:0)
AllRequestsCount
函数使用的countClick
变量为空。
使用i++;
而不是i = countClick();