使用共享首选项来存储arraylist,返回null对象

时间:2015-06-17 21:59:20

标签: java android sharedpreferences

我有一个ArrayList列表编写器,我使用此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();
    }}

这是在我的加载屏Activity上完成的,我想将列表编写器设置为SharedPreferences,以便我可以在另一个Activity中使用它。这是我的会话管理器类。 AsyncTask中的日志记录向我显示列表编写器已正确填充。但是,当我在其他课程中调用getlistwriter时,我收到一个空的ArrayList。我无法看到错误的位置。

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);
}}

用于检索列表编写器的代码

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类:

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);
    }
}

1 个答案:

答案 0 :(得分:2)

在您的SessionManager中,您未将List保存到SharedPrefs。你应该这样做:

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

保存:

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

加载:

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;
}

您的BetDisplayer必须implements Serializable 见这里:Android array to Sharedpreferences with Gson

要使用Gson,只需添加此依赖项:'com.google.code.gson:gson:2.3.1'或下载.jar

<强>更新 创建一个仅Singleton仅包含SharedPreferences编辑器的Singleton,这只是猜测但我认为您使用不同的上下文来获取编辑器,这可能是问题所在(更新2 :不是,请检查here,但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; } 接近它是一个加号:

SharedPreferences

当您需要使用SessionManager().getInstance().someMethod();时使用{{1}}