Daudidenno
Daudidenno

Reputation: 47

Is there a way to save the data on SharedPreference?

I am trying to save data on button toggle, so that if pokemon is caught, when i run the application again, pokemon is caugt, and when released, It toggles back to "catch". But all my pokemon are displaying caught (button shows "release")

package com.example.pokedex;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class PokemonActivity extends AppCompatActivity {
    private TextView nameTextView;
    private TextView numberTextView;
    private TextView type1TextView;
    private TextView type2TextView;
    private String url;
    private RequestQueue requestQueue;
    Button button;
    SharedPreferences sharedpreferences;
    public static final String mypreference = "mypref";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pokemon);
        requestQueue = Volley.newRequestQueue(getApplicationContext());
        url = getIntent().getStringExtra("url");
        nameTextView = findViewById(R.id.pokedex_name);
        numberTextView = findViewById(R.id.pokedex_number);
        type1TextView = findViewById(R.id.pokedex_type);
        type2TextView = findViewById(R.id.pokedex_type2);
        button = findViewById(R.id.catcher);

        sharedpreferences = getSharedPreferences(mypreference,
                Context.MODE_PRIVATE);

        load();

    }

    public void load() {
        type1TextView.setText("");
        type2TextView.setText("");

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, response -> {
            try {
                nameTextView.setText(response.getString("name"));
                numberTextView.setText(String.format("#%03d", response.getInt("id")));

                JSONArray typeEntries = response.getJSONArray("types");
                for (int i = 0; i < typeEntries.length(); i++) {
                    JSONObject typeEntry = typeEntries.getJSONObject(i);
                    int slot = typeEntry.getInt("slot");
                    String type = typeEntry.getJSONObject("type").getString("name");

                    if (slot == 1) {
                        type1TextView.setText(type);
                    } else if (slot == 2) {
                        type2TextView.setText(type);
                    }
                }
            } catch (JSONException e) {
                Log.e("cs50", "Pokemon json error", e);
            }
        }, error -> Log.e("cs50", "Pokemon details error", error));

        requestQueue.add(request);

        if (sharedpreferences.contains(nameTextView.getText().toString()))
            button.setText("Release");
    }


    public void toggleCatch(View view) {
        String name = nameTextView.getText().toString();
        SharedPreferences.Editor editor = sharedpreferences.edit();

        if (button.getText().toString().toLowerCase().equals("Catch".toLowerCase())) {
            //editor.clear();
            editor.putString(name, name);
            editor.apply();
            editor.commit();
            button.setText("Release");

        } else if (button.getText().toString().toLowerCase().equals("Release".toLowerCase())){
            editor.remove(name);
            editor.apply();
            editor.commit();
            button.setText("Catch");
        }
    }
}

I have tried everything i know how to, please help.

Unmodified source code at "https://cdn.cs50.net/2019/fall/tracks/android/pokedex/pokedex.zip"

Upvotes: 0

Views: 337

Answers (1)

alperozge
alperozge

Reputation: 136

The following line of code

if (sharedpreferences.contains(nameTextView.getText().toString()))
            button.setText("Release");

should go into your onResponseListener() that is your response -> ....

Currently you are calling the if statement above synchronously. This means that you are searching for not any valid Pokemon name but "" (empty string) inside SharedPreferences. In one of your tests, you probably saved empty string as a key, and you cannot undo that because any transaction after you load your pokemons includes a non-empty string Pokemon name.

If taht is indeed the case, you can easily add a temporary code inside your activity onCreate() method to remove that entry from SharedPreferences.

Upvotes: 1

Related Questions