2

I have an ArrayList listwriter which I populate using this AsyncTask.

class LoadAllGamesWhenNull extends AsyncTask<String, String, String> {
    private String id;
    private String stake;
    private String user;
    private String returns;
    private String teams;
    private String status;


    //  *//**
    //   * Before starting background thread Show Progress Dialog
    //    *//*
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    //  *//**
    //    * getting All products from url
    //    *//*
    protected String doInBackground(String... args) {
        // Building Parameters
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url_all_games);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("email", name));
        try {
            post.setEntity(new UrlEncodedFormEntity(params));
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        try {
            HttpResponse response = client.execute(post);
            Log.d("Http Post Response:", response.toString());
            HttpEntity httpEntity = response.getEntity();
            InputStream is = httpEntity.getContent();
            JSONObject jObj = null;
            String json = "";
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {

                    if (!line.startsWith("<", 0)) {
                        if (!line.startsWith("(", 0)) {
                            sb.append(line + "\n");
                        }
                    }
                }

                is.close();
                json = sb.toString();
                json = json.substring(json.indexOf('{'));
                Log.d("sb", json);

            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }

            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }

            // return JSON String
            Log.d("json", jObj.toString());
            try {
                allgames = jObj.getJSONArray(TAG_BET);
                Log.d("allgames", allgames.toString());
                ArrayList<BetDatabaseSaver> listofbets = new ArrayList<>();
                // looping through All Products
                for (int i = 0; i < allgames.length(); i++) {
                    JSONObject c = allgames.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_ID);
                    String user = c.getString(TAG_USER);
                    String returns = c.getString(TAG_RETURNS);
                    String stake = c.getString(TAG_STAKE);
                    String status = c.getString(TAG_STATUS);
                    String Teams = c.getString(TAG_TEAMS);
                    Log.d("id", id);
                    Log.d("user", user);
                    Log.d("returns", returns);
                    Log.d("stake", stake);
                    Log.d("status", status);
                    Log.d("teams", Teams);


                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_ID, id);
                    map.put(TAG_TEAMS, Teams);
                    map.put(TAG_USER, user);
                    map.put(TAG_RETURNS, returns);
                    map.put(TAG_STAKE, stake);
                    map.put(TAG_STATUS, status);
                    if (status.equals("open")) {
                        useroutcomes.put(id.substring(0, 10), Teams);
                    }

                    listwriter.add(i, new BetDisplayer(user, id, Integer.parseInt(stake), Integer.parseInt(returns), status, "","",Teams));

                    Log.d("map", map.toString());
                    // adding HashList to ArrayList
                    bet.add(map);
                }


            } catch (JSONException e) {
                e.printStackTrace();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }


        return "";
    }


    @Override
    protected void onPostExecute(String param) {


        // dismiss the dialog after getting all products
        // updating UI from Background Thread
        String ultparam = "";
        int i = 0;
        for (HashMap<String, String> a : bet) {
            String teams = a.get(TAG_TEAMS);

            Map<String, String> listofteams = new HashMap<>();

            Pattern p = Pattern.compile("[(](\\d+)/([1X2])[)]");
            Matcher m = p.matcher(teams);
            Log.d("printa", teams);
            while (m.find()) {
                listofteams.put(m.group(1), m.group(2));
            }
            Log.d("dede", listofteams.toString());
            String c = "";
            for (String x : listofteams.keySet()) {
                String b = x + ",";
                c = c + b;
            }
            Log.d("C", c);
            c = c.substring(0, c.lastIndexOf(","));
            //    Log.d("Cproc", c);

                ultparam = ultparam + a.get(TAG_ID).substring(0, 10) + c + "//";
                passtocheck.add(listofteams);
                allopens.put(Integer.toString(i), a.get(TAG_STATUS));
                i++;

            i++;

        }
        ultparam = ultparam.substring(0, ultparam.lastIndexOf("//"));
        Log.d("ULTPARAM", ultparam);
        CheckBet checker = new CheckBet(ultparam, passtocheck);
        HashMap<String, String> finaloutcomes = checker.checkbetoutcome();
        Log.d("Finaloutcomes", finaloutcomes.toString());
        finaloutcomess = finaloutcomes.toString();
        for (String x : finaloutcomes.keySet()) {
            for (int p = 0; p < listwriter.size(); p++) {
                if (listwriter.get(p).getId().substring(0, 10).equals(x)) {
                    String[] finaloutcomearray = finaloutcomes.get(x).split(" ");
                    String[] useroutcomearray = listwriter.get(p).getSelections().split(" ");
                    for (int r = 0; r < finaloutcomearray.length; r++) {
                        Log.d("finaloutcomearray", finaloutcomearray[r]);
                        Log.d("useroutcomearray", useroutcomearray[r]);
                        String[] indfinaloutcomesarray = finaloutcomearray[r].split("\\)");
                        String[] induseroutcomearray = useroutcomearray[r].split("\\)");
                        for (int d = 0; d < indfinaloutcomesarray.length; d++) {
                            Log.d("indfinaloutcome", indfinaloutcomesarray[d]);
                            Log.d("induseroutcome", induseroutcomearray[d]);
                            finalhash.put(indfinaloutcomesarray[d].substring(1, indfinaloutcomesarray[d].lastIndexOf("/")), indfinaloutcomesarray[d].substring(indfinaloutcomesarray[d].lastIndexOf("/") + 1));
                            userhash.put(induseroutcomearray[d].substring(1, induseroutcomearray[d].lastIndexOf("/")), induseroutcomearray[d].substring(induseroutcomearray[d].lastIndexOf("/") + 1));

                        }
                    }
                    Log.d("FINALHASHfinal", finalhash.toString());
                    listwriter.get(p).setActualselections(finalhash.toString());
                    listwriter.get(p).setUserselections(userhash.toString());
                    Log.d("USERHASHfinal", userhash.toString());
                    listwriter.get(p).setStatus("won");
                    for (String id : userhash.keySet()) {
                        if (finalhash.get(id).equals("null")) {
                            listwriter.get(p).setStatus("open");
                        } else if (!(finalhash.get(id).equals(userhash.get(id)))) {
                            listwriter.get(p).setStatus("lost");
                            break;
                        }

                    }
                    finalhash.clear();
                    userhash.clear();
                    currentitem = listwriter.get(p);
                    if (currentitem.getStatus().equals("open")) {

                    } else {
                        if (currentitem.getStatus().equals("won")) {
                            valuechange = valuechange + currentitem.getReturns() - (currentitem.getStake());
                        }
                        String c = currentitem.getId() + "," + currentitem.getStatus() + "//";
                        updateparam = updateparam + c;
                        Log.d("UPDATEPARAM1", updateparam);
                    }
                }
            }
        }
        Log.d("Listwriterbefore",listwriter.toString());
        session.setListwriter(listwriter);
        new UpdateBetStatus().execute();
        Intent g = new Intent(loadingscreen.this,DisplayAllBets.class);
        startActivity(g);
        finish();
    }}

This is done on my loadscreen Activity and I want to set the listwriter to my SharedPreferences so that I can use it in another Activity. This is my session manager class. The logging in the AsyncTask shows me that the listwriter gets populated correctly. However, when I call on the getlistwriter in my other class I receive an empty ArrayList. I can't see where the error is.

public class SessionManager {
// LogCat tag
private static String TAG = SessionManager.class.getSimpleName();
private ArrayList<BetDisplayer> listwriter = new ArrayList<>();
// Shared Preferences
SharedPreferences pref;

Editor editor;
Context _context;

// Shared pref mode
int PRIVATE_MODE = 0;

// Shared preferences file name
private static final String PREF_NAME = "AndroidHiveLogin";

private static final String KEY_IS_LOGGEDIN = "isLoggedIn";

public static final String USERNAME = "username";


public SessionManager(Context context) {
    this._context = context;
    pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = pref.edit();
}

public ArrayList<BetDisplayer> getListwriter() {
    return listwriter;
}

public void setListwriter(ArrayList<BetDisplayer> listwriter) {
    this.listwriter = listwriter;
}

public void setLogin(boolean isLoggedIn, String username) {

    editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);
    editor.putString(USERNAME, username);

    // commit changes
    editor.commit();

    Log.d(TAG, "User login session modified!");
}

public HashMap<String, String> getUserDetails(){
    HashMap<String, String> user = new HashMap<String, String>();
    // user name
    user.put(USERNAME, pref.getString(USERNAME, null));

    // return user
    return user;
}
public boolean isLoggedIn(){
    return pref.getBoolean(KEY_IS_LOGGEDIN, false);
}}

Code used to retrieve listwriter

public void onCreate(Bundle savedInstanceState) { 
 super.onCreate(savedInstanceState);    
 setContentView(R.layout.activity_display_all_bets); 
 menu menu = (menu) 
 getFragmentManager().findFragmentById(R.id.fragment); 
 menu.updateinfo(getName()); 
 session = new SessionManager(getApplicationContext());
  HashMap<String, String> user = session.getUserDetails(); 
  name = user.get(SessionManager.USERNAME);
   listwriter = session.getListwriter();

AppController class :

public class AppController extends Application {

public static final String TAG = AppController.class.getSimpleName();

private RequestQueue mRequestQueue;

private static AppController mInstance;

private ArrayList<HashMap<String, String>> gamesList;

public ArrayList<HashMap<String, String>> getGamesList() {
    return gamesList;
}

public void setGamesList(ArrayList<HashMap<String, String>> gamesList) {
    this.gamesList = gamesList;
}

@Override
public void onCreate() {
    super.onCreate();
    mInstance = this;
}


public static synchronized AppController getInstance() {
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {
    req.setTag(TAG);
    getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
    if (mRequestQueue != null) {
        mRequestQueue.cancelAll(tag);
    }
}
0

1 Answer 1

2

In your SessionManager you're not saving your List into SharedPrefs. You should do something like this:

public static final String MY_LIST = "my_list";
private static final Type LIST_TYPE = new TypeToken<List<BetDisplayer>>() {}.getType();

to save:

public void setListwriter(ArrayList<BetDisplayer> listwriter) {
    this.listwriter = new ArrayList<BetDisplayer>(listwriter);
    mPrefs.edit()
            .putString(MY_LIST, new Gson().toJson(listwriter));
            .commit();
}

to load:

public ArrayList<BetDisplayer> getListwriter() {
    if (listwriter == null) {
       listwriter = new Gson().fromJson(mPrefs.getString(MY_LIST, null), LIST_TYPE);
       if(listwriter == null){
           listwriter = new ArrayList<BetDisplayer>();
       }
    }
    return listwriter;
}

Your BetDisplayer must implements Serializable.
See here: Android array to Sharedpreferences with Gson

To use Gson just add this dependency: 'com.google.code.gson:gson:2.3.1' or download the .jar

UPDATE: Create a Singleton that holds one reference only to your SharedPreferences editor, it's just a will guess but I think you are using different context to get your editor and that could be the problem (UPDATE 2: it's not, check here, but the Singleton approach it's a plus):

private static SharedPreferences mPrefs;
private static SessionManager sInstance = null;

protected SessionManager() {
    mPrefs = AppController.getInstance().getApplicationContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
}

public static SessionManager getInstance() {
    if (sInstance == null) {
        sInstance = new SessionManager();
    }
    return sInstance;
}

And when you need to use SharedPreferences use SessionManager().getInstance().someMethod();

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

5 Comments

Thing is the AppController is in my main package, the Session Manager is in a helper package and when I do the import it says that the package doesn't exist
Well that's a different problem (question). Why having a different package instead of a helper folder inside the project package? Consider moving that helper package to the same project package. If not, see here how to add module dependencies with gradle: stackoverflow.com/questions/21170395/…
I used this tutorial a while ago when generating my login screens and I still have the helper package for the shared preferences , so I decided to use it in this case. androidhive.info/2012/08/…
Create another question showing your project files tree and the error regarding your import. This issue no longer belongs to this thread
Yeah hey I fixed it but I'm still getting an empty array

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.