无法从sharedpreference读取字符串集(变量值消失)

时间:2019-03-24 23:14:21

标签: java android set sharedpreferences android-volley

我试图将数据从服务器推送到共享的首选项,然后将它们拉回,但总是出问题。

这是我的代码

package com.vetdevelopers.vetnetwork;
import android.app.LauncherActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.vetdevelopers.modelclass.ListModification;
import com.vetdevelopers.modelclass.OkHttpToJSON;
import com.vetdevelopers.modelclass.VolleyFunctions;

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

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;

public class SearchActivity extends AppCompatActivity
{
    private Button search_searchButton;
    private EditText search_name, search_phone;
    private Spinner search_postingArea_spinner, search_district_spinner, search_division_spinner;
    private String name = "", phone = "", postingArea = "", district = "", division = "",
            POSTING_AREA = "posting_area";
    public List<String> list = new ArrayList<String>(); //variable vanish problem , but why?
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;
    final String PREF_NAME = "prefs";


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        search_name = (EditText) findViewById(R.id.search_name);
        search_phone = (EditText) findViewById(R.id.search_phone);
        search_postingArea_spinner = (Spinner) findViewById(R.id.search_postingArea_spinner);
        search_district_spinner = (Spinner) findViewById(R.id.search_district_spinner);
        search_division_spinner = (Spinner) findViewById(R.id.search_division_spinner);
        search_searchButton = (Button) findViewById(R.id.search_searchButton);


        getJSONFromVolley_1_2(ServerConstants.DOCTOR_POSTING_AREA);
        Set<String> setEmpty = new HashSet<String>();
        setEmpty.add("");
        sharedPreferences = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        Set<String> set = sharedPreferences.getStringSet("getJSONFromVolley_1_2",setEmpty);
        System.out.println("Here is set : "+set);
        System.out.println("List here : "+list);
        //editor.remove("getJSONFromVolley_1_2");
        //editor.apply();

/*
        ArrayAdapter<String> arrayAdapterDivision = new ArrayAdapter<>
                (this, android.R.layout.simple_spinner_item, arrayListPostingArea);
        arrayAdapterDivision.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        search_postingArea_spinner.setAdapter(arrayAdapterDivision);
*/

        search_searchButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                /*
                name = search_name.getText().toString().trim();
                phone = search_phone.getText().toString().trim();
                postingArea = search_postingArea_spinner.getSelectedItem().toString();
                district = search_district_spinner.getSelectedItem().toString();
                division = search_division_spinner.getSelectedItem().toString();

                System.out.println("debug now : " + name + " " + phone + " " + postingArea + " " +
                        district + " " + division + " ");

                Bundle bundle = new Bundle();
                bundle.putString("name", name);
                bundle.putString("phone", phone);
                bundle.putString("postingArea", postingArea);
                bundle.putString("district", district);
                bundle.putString("division", division);

                //Intent intent = new Intent(SearchActivity.this,BrowseActivity.class);

                //startActivity();
                */
            }
        });






        /*
        name=search_name.getText().toString().trim();
        phone=search_phone.getText().toString().trim();
        postingArea=search_postingArea_spinner.getSelectedItem().toString();
        district=search_district_spinner.getSelectedItem().toString();
        division=search_division_spinner.getSelectedItem().toString();
        */
    }

    public void getJSONFromVolley_1_2(String url)
    {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response)
                    {
                        if (response.contains("Connection failed!"))
                        {
                            //popupTextView.setText(response);
                            //mDialog.show();
                            Toast.makeText(SearchActivity.this, response, Toast.LENGTH_SHORT).show();
                        }
                        else if (response.contains("Please check your ID & Password!"))
                        {
                            //popupTextView.setText(response);
                            //mDialog.show();
                            Toast.makeText(SearchActivity.this, response, Toast.LENGTH_SHORT).show();
                        }
                        else if (response.contains("Improper request method!"))
                        {
                            //popupTextView.setText(response);
                            //mDialog.show();
                            Toast.makeText(SearchActivity.this, response, Toast.LENGTH_SHORT).show();
                        }
                        else if (response.contains("Invalid platform!"))
                        {
                            //popupTextView.setText(response);
                            //mDialog.show();
                            Toast.makeText(SearchActivity.this, response, Toast.LENGTH_SHORT).show();
                        }
                        else if (response.contains("sql error"))
                        {
                            Toast.makeText(SearchActivity.this, response, Toast.LENGTH_SHORT).show();
                        }

                        //server data  retrieve code below...
                        else
                        {
                            Set<String> set = new HashSet<String>();
                            set.add("Select");
                            try
                            {
                                JSONArray jsonArray = new JSONArray(response);
                                for (int i = 0; i < jsonArray.length(); i++)
                                {
                                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                                    String output = jsonObject.getString("posting_area");

                                    //debug : for each row - print the two output
                                    //System.out.println("debug : " + (i + 1) + " " + output1);

                                    //unique
                                    if(!set.contains(output) && !output.equals("N/A"))
                                    {
                                        set.add(output);
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                e.printStackTrace();
                            }

                            System.out.println("Initial set : "+set);
                            list.addAll(set);

                            SharedPreferences sharedPreferences;
                            SharedPreferences.Editor editor;
                            String PREF_NAME = "prefs";

                            sharedPreferences = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
                            editor = sharedPreferences.edit();
                            editor.putStringSet("getJSONFromVolley_1_2",set);
                            editor.apply();

                            System.out.println("Initial pref : "+sharedPreferences.getStringSet("getJSONFromVolley_1_2",null));
                        }
                    }
                }, new Response.ErrorListener()
        {
            @Override
            public void onErrorResponse(VolleyError error)
            {
                if (error instanceof TimeoutError)
                {
                    Toast.makeText(SearchActivity.this, "Timeout error!", Toast.LENGTH_SHORT).show();
                }
                else if (error instanceof NoConnectionError)
                {
                    Toast.makeText(SearchActivity.this, "No connection error!", Toast.LENGTH_SHORT).show();
                }
                else if (error instanceof AuthFailureError)
                {
                    Toast.makeText(SearchActivity.this, "Authentication failure error!", Toast.LENGTH_SHORT).show();
                }
                else if (error instanceof NetworkError)
                {
                    Toast.makeText(SearchActivity.this, "Network error!", Toast.LENGTH_SHORT).show();
                }
                else if (error instanceof ServerError)
                {
                    Toast.makeText(SearchActivity.this, "Server error!", Toast.LENGTH_SHORT).show();
                }
                else if (error instanceof ParseError)
                {
                    Toast.makeText(SearchActivity.this, "JSON parse error!", Toast.LENGTH_SHORT).show();
                }
            }
        })
        {
            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String> params = new HashMap<String, String>();
                return params;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError
            {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("User-Agent", "VetNetwork");  ////security purpose
                return headers;
            }
        };

        MySingleton.getInstance(SearchActivity.this).addToRequestQueue(stringRequest);
    }

}

这是logcat:

2019-03-25 05:37:39.961 30919-30919/com.vetdevelopers.vetnetwork 
I/System.out: Here is set : []
2019-03-25 05:37:39.961 30919-30919/com.vetdevelopers.vetnetwork 
I/System.out: List here : []
2019-03-25 05:37:40.178 30919-30919/com.vetdevelopers.vetnetwork 
I/System.out: Initial set : [Noa, Select]
2019-03-25 05:37:40.178 30919-30919/com.vetdevelopers.vetnetwork 
I/System.out: Initial pref : [Select, Noa]

我的问题是为什么值从81(或82)行处的变量(甚至从共享首选项)消失?

请告诉我当我尝试从共享首选项中提取数据时出了什么问题?建议我一些更容易解决的问题

1 个答案:

答案 0 :(得分:0)

尝试使用由editor.commit()插入的editor.apply()

OR

尝试使用相同的首选项变量。

public class SearchActivity extends AppCompatActivity {
    private Button search_searchButton;
    private EditText search_name, search_phone;
    private Spinner search_postingArea_spinner, search_district_spinner, search_division_spinner;
    private String name = "", phone = "", postingArea = "", district = "", division = "", POSTING_AREA = "posting_area";
    public List<String> list = new ArrayList<String>(); //variable vanish problem , but why?
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;
    final String PREF_NAME = "prefs";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        search_name = (EditText) findViewById(R.id.search_name);
        search_phone = (EditText) findViewById(R.id.search_phone);
        search_postingArea_spinner = (Spinner) findViewById(R.id.search_postingArea_spinner);
        search_district_spinner = (Spinner) findViewById(R.id.search_district_spinner);
        search_division_spinner = (Spinner) findViewById(R.id.search_division_spinner);
        search_searchButton = (Button) findViewById(R.id.search_searchButton);


        getJSONFromVolley_1_2(ServerConstants.DOCTOR_POSTING_AREA);

        Set<String> setEmpty = new HashSet<String>();
        setEmpty.add("");

        Set<String> set = sharedPreferences.getStringSet("getJSONFromVolley_1_2", setEmpty);
        System.out.println("Here is set : " + set);
        System.out.println("List here : " + list);
        //editor.remove("getJSONFromVolley_1_2");
        //editor.apply();

    }

    public void getJSONFromVolley_1_2(String url) {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        if (response.contains("Connection failed!")) {
                            //popupTextView.setText(response);
                            //mDialog.show();
                            Toast.makeText(SearchActivity.this, response, Toast.LENGTH_SHORT).show();
                        } else if (response.contains("Please check your ID & Password!")) {
                            //popupTextView.setText(response);
                            //mDialog.show();
                            Toast.makeText(SearchActivity.this, response, Toast.LENGTH_SHORT).show();
                        } else if (response.contains("Improper request method!")) {
                            //popupTextView.setText(response);
                            //mDialog.show();
                            Toast.makeText(SearchActivity.this, response, Toast.LENGTH_SHORT).show();
                        } else if (response.contains("Invalid platform!")) {
                            //popupTextView.setText(response);
                            //mDialog.show();
                            Toast.makeText(SearchActivity.this, response, Toast.LENGTH_SHORT).show();
                        } else if (response.contains("sql error")) {
                            Toast.makeText(SearchActivity.this, response, Toast.LENGTH_SHORT).show();
                        }

                        //server data  retrieve code below...
                        else {
                            Set<String> set = new HashSet<String>();
                            set.add("Select");
                            try {
                                JSONArray jsonArray = new JSONArray(response);
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                                    String output = jsonObject.getString("posting_area");

                                    //debug : for each row - print the two output
                                    //System.out.println("debug : " + (i + 1) + " " + output1);

                                    //unique
                                    if (!set.contains(output) && !output.equals("N/A")) {
                                        set.add(output);
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            System.out.println("Initial set : " + set);
                            list.addAll(set);

                            sharedPreferences = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
                            editor = sharedPreferences.edit();
                            editor.putStringSet("getJSONFromVolley_1_2", set);
                            editor.commit();

                            System.out.println("Initial pref : " + sharedPreferences.getStringSet("getJSONFromVolley_1_2", null));
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (error instanceof TimeoutError) {
                    Toast.makeText(SearchActivity.this, "Timeout error!", Toast.LENGTH_SHORT).show();
                } else if (error instanceof NoConnectionError) {
                    Toast.makeText(SearchActivity.this, "No connection error!", Toast.LENGTH_SHORT).show();
                } else if (error instanceof AuthFailureError) {
                    Toast.makeText(SearchActivity.this, "Authentication failure error!", Toast.LENGTH_SHORT).show();
                } else if (error instanceof NetworkError) {
                    Toast.makeText(SearchActivity.this, "Network error!", Toast.LENGTH_SHORT).show();
                } else if (error instanceof ServerError) {
                    Toast.makeText(SearchActivity.this, "Server error!", Toast.LENGTH_SHORT).show();
                } else if (error instanceof ParseError) {
                    Toast.makeText(SearchActivity.this, "JSON parse error!", Toast.LENGTH_SHORT).show();
                }
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                return params;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("User-Agent", "VetNetwork");  ////security purpose
                return headers;
            }
        };

        MySingleton.getInstance(SearchActivity.this).addToRequestQueue(stringRequest);
    }

}