0

I am trying to do a module where once I fetched the JSON from the API and I am loading it into RAM memory I immediately load it to Shared Prefs and also once I any change to the data (in the adapter onClick method) I re-save the new changed array into the shared preferences. Apparently it does not work and I can't figure out why.

Here is my activity containing all of the relevant code:


package com.example.superheros.Controllers;

import android.content.SharedPreferences;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.ImageView;

import com.example.superheros.Adapter.HeroesAdapter;
import com.example.superheros.Model.Hero;
import com.example.superheros.Networking.HttpRequest;
import com.example.superheros.R;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    //API constant -
    private static final String BASE_URL = "https://heroapps.co.il/employee-tests/android/androidexam.json";
    public static final String SAVED_HERO_LIST = "heroesList";
    // Recyclerview variables -
    private RecyclerView heroesRecylerView;
    private ArrayList<Hero> heroesArrayList;
    private RecyclerView.LayoutManager layoutManager;
    private HeroesAdapter heroesAdapter;
    //Toolbar variables -
    private CollapsingToolbarLayout collapsingToolbarLayout;
    private ImageView toolbarImageView;
    //Persistence variables -
    private Hero selectedFavoriteHero;
    private SharedPreferences sharedPreferences;
    private Gson gson;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            heroesArrayList = loadFromLocal();
        }catch (Exception ex) {
            ex.printStackTrace();
        }
        if (heroesArrayList != null && heroesArrayList.size() > 0){
            initViews();
        } else {
            initNetworking();
        }

    }

    private void initNetworking() {
        HttpRequest httpRequest = new HttpRequest(this, BASE_URL, new HttpRequest.OnHttpCompleteListener() {
            @Override
            public void onComplete(String response) {
                dataToModel(response, false);
                initViews();
            }

            @Override
            public void onError(String error) {
                Log.d("error", error);
            }
        });
        httpRequest.request();
    }


    private void initViews() {
        heroesRecylerView = findViewById(R.id.herosRecyclerView);
        collapsingToolbarLayout = findViewById(R.id.collapsingHeroToolbarLayout);
        toolbarImageView = findViewById(R.id.toolbarImageview);
        heroesRecylerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        heroesRecylerView.setLayoutManager(layoutManager);
        heroesAdapter = new HeroesAdapter(heroesArrayList, new HeroesAdapter.OnHeroListClickListener() {
            @Override
            public void onListItemClicked(int position) {
                changeFavoriteHero(position);
            }
        });
        heroesRecylerView.setAdapter(heroesAdapter);

    }

    private void changeFavoriteHero(int position) {
        Hero pressedHeroRow = heroesArrayList.get(position);
        selectedFavoriteHero = pressedHeroRow;
        Picasso.get().load(pressedHeroRow.image)
                .fit()
                .centerCrop()
                .placeholder(R.drawable.ic_launcher_background)
                .error(R.drawable.ic_launcher_foreground)
                .into(toolbarImageView);
        collapsingToolbarLayout.setTitle(pressedHeroRow.title);
        pressedHeroRow.setFavorite(!pressedHeroRow.isFavorite());
        for (int i = 0; i < heroesArrayList.size(); i++) {
            if (i == position) continue;
            heroesArrayList.get(i).setFavorite(false);
        }
        saveToLocal(heroesArrayList);
        heroesAdapter.notifyDataSetChanged();
    }


    private ArrayList<Hero> dataToModel(String json, boolean isLocalInfo) {
        Gson gson = new Gson();
        Hero[] heroesList = gson.fromJson(json, Hero[].class);
        heroesArrayList = new ArrayList<>(Arrays.asList(heroesList));
        if (!isLocalInfo) {
            saveToLocal(heroesArrayList);
        }
        return heroesArrayList;
    }


    //Shared preferences load & save methods -

    private void saveToLocal(ArrayList<Hero> heroesArrayList) {
        sharedPreferences = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
        Gson gson = new Gson();
        String heroesList = gson.toJson(heroesArrayList);
        Log.d("heroArrayList", heroesList);
        prefsEditor.putString(SAVED_HERO_LIST, heroesList);
        prefsEditor.apply();
    }

    private ArrayList<Hero> loadFromLocal(){
        sharedPreferences = getPreferences(MODE_PRIVATE);
        try {
            String fetchedHeroesJson = gson.fromJson(SAVED_HERO_LIST, String.class);
            ArrayList<Hero> heroArrayList = dataToModel(fetchedHeroesJson, true);
            return heroArrayList;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;

    }
}


I hope I can be pointed about what I was missing

9
  • SharedPreference is not Memory DB. I don't fully understand what you want to do. But delete the app completely(delete the data) and then re-try, if you want to remove the data in SharedPreference. Commented May 29, 2019 at 8:21
  • I don't fully understand you. Commented May 29, 2019 at 8:22
  • tried to delete and re-install the app and did not do anything new Commented May 29, 2019 at 8:25
  • Be specific please. I'd like to help you out. But can't understand what you need. Commented May 29, 2019 at 8:27
  • 1
    you got it right mate. thanks Commented May 29, 2019 at 8:40

2 Answers 2

1

try this.

 private ArrayList<Hero> loadFromLocal(){
        sharedPreferences = getPreferences(MODE_PRIVATE);
        try {
            String fetchedHeroesJson = sharedPreferences.getString(SAVED_HERO_LIST, "null");
            ArrayList<Hero> heroArrayList = dataToModel(fetchedHeroesJson, true);
            return heroArrayList;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;

    }
Sign up to request clarification or add additional context in comments.

2 Comments

thank you very much. solved! the issue was that I trying to get the data from shared prefs using GSON, haha.
welcome, it happens.. keep coding... will get a wonderful result :)
0

change

prefsEditor.apply();

to

prefsEditor.commit();

apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. As you're accessing the same preferences object (is a singleton) you should see a consistent view at all times but not in your case you access from separate thread.

2 Comments

does not seems to have any effect on the row item I pressed. I have an imageview that should change according to if the rowitem has been pressed and it seems like it did not saved it.
there is though some behavior that is interesting - it loads much faster than it does when deleting the app and re-installing, does that mean that the data has been fetched but not fully? or is it because of some other reason ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.