简体   繁体   中英

How to add conditions for a user in shared preference

I am working on a quiz app where there are many quizzes and the score user obtain for each quiz is stored in server. Is there a way to add a condition so that the score particular user gets in a quiz is logged only on his first try and If the user appear for the same quiz second or more time, His score is not logged.

Following is the part of code where the score is sent to the server.

 private void sendScoreToServer(String subcategory, String username, String email, String score){
    Map<String, String> params = getParams(subcategory, username, email, score);
    GsonRequest<ScoreObject> serverRequest = new GsonRequest<ScoreObject>(
            Request.Method.POST,
            Constants.PATH_TO_ADD_SCORE,
            ScoreObject.class,
            params,
            createRequestSuccessListener(),
            createRequestErrorListener());

    ((CustomApplication)getApplication()).getNetworkCall().callToRemoteServer(serverRequest);
}

private Map<String, String> getParams(String subcategory, String username, String email, String score){
    Map<String, String> params = new HashMap<String,String>();
    params.put(Constants.SUBCATEGORY, subcategory);
    params.put(Constants.NAME, username);
    params.put(Constants.EMAIL, email);
    params.put(Constants.SCORE, score);
    return params;
}

private Response.Listener<ScoreObject> createRequestSuccessListener() {
    return new Response.Listener<ScoreObject>() {
        @Override
        public void onResponse(ScoreObject response) {
            try {
                if(response != null){
                    Log.d(TAG, "Response value " + response);
                } else{
                    displayErrorMessage(ResultActivity.this, "Quiz score failed to upload");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
}

private Response.ErrorListener createRequestErrorListener() {
    return new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    };
}
}

As for as I know It can be done in two ways, either by using shared preference or adding values to server. Any input is welcomed.

I am a total newbie in coding so please bear with me.

Assuming you want them to be able to retake the quiz but not store the score again- the easiest and most secure way is on the server. When the user uploads a score, check and see if the user already has a score for that quiz. If he does, do not save the new score.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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