2015-07-12 93 views
-1

我試圖用共享首選項保存點擊次數,所以當我回到應用程序時,它可以檢索最後一個數字,它在這裏不工作的代碼。感謝您的幫助。 公共類MainActivity延伸活性在countClick功能中使用爲空{Android SharedPreferences,保存簡單的int變量時發生問題

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

AllRequestsCount變量。

只需使用i++;i = countClick();

+0

由於它的工作原理:) – Alex41