Android:将微调器中的选定项目保存到SharedPreferences

时间:2019-05-09 01:20:30

标签: java php android mysql

根据上面的问题,我实际上想测试我从Internet上获得的现有代码。我可以成功地从表中的列中获取数据并显示回该数据。例如,当我选择人名的“ Lim AI Khoon”时,它将在同一活动中显示Lim Ai Khoon名称以及Lim Ai Khoon的徽章ID。现在,如何将已选择的数据保存到sharedPreferences并在下一个活动中显示数据?下面是我的代码 //MainActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Initializing the ArrayList
    students = new ArrayList<String>();

    //Initializing Spinner
    spinner = (Spinner) findViewById(R.id.spinner);

    //Adding an Item Selected Listener to our Spinner
    //As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener
    spinner.setOnItemSelectedListener(this);

    //Initializing TextViews
    tvName = (TextView) findViewById(R.id.tvName);
    tvBadgeID = (TextView) findViewById(R.id.tvBadgeID);
    btnNext = findViewById(R.id.btnNext);


    //This method will fetch the data from the URL
    getData();

    btnNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, Main2Activity.class);
            startActivity(intent);
        }
    });
}

private void getData(){
    //Creating a string request
    StringRequest stringRequest = new StringRequest(Config.DATA_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    JSONObject j = null;
                    try {
                        //Parsing the fetched Json String to JSON Object
                        j = new JSONObject(response);

                        //Storing the Array of JSON String to our JSON Array
                        result = j.getJSONArray(Config.JSON_ARRAY);

                        //Calling method getStudents to get the students from the JSON Array
                        getStudents(result);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

    //Creating a request queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    //Adding request to the queue
    requestQueue.add(stringRequest);
}

private void getStudents(JSONArray j){
    //Traversing through all the items in the json array
    for(int i=0;i<j.length();i++){
        try {
            //Getting json object
            JSONObject json = j.getJSONObject(i);

            //Adding the name of the student to array list
            students.add(json.getString(Config.TAG_NAME));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //Setting adapter to show the items in the spinner
    spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, students));

    SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putString("reviewer",spinner.getSelectedItem().toString());
}


//Method to get student name of a particular position
private String getName(int position){
    String name="";
    try {
        //Getting object of given index
        JSONObject json = result.getJSONObject(position);

        //Fetching name from that object
        name = json.getString(Config.TAG_NAME);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    //Returning the name
    return name;
}

//Doing the same with this method as we did with getName()
private String getCourse(int position){
    String course="";
    try {
        JSONObject json = result.getJSONObject(position);
        course = json.getString(Config.TAG_BADGEID);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return course;
}


//this method will execute when we pic an item from the spinner
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    //Setting the values to textviews for a selected item
    tvName.setText(getName(position));
    tvBadgeID.setText(getCourse(position));
}

//When no item is selected this method would execute
@Override
public void onNothingSelected(AdapterView<?> parent) {
    tvName.setText("");
    tvBadgeID.setText("");
}

// Config.java

public class Config {
//JSON URL
public static final String DATA_URL = "http://10.0.2.2/spinner/getData.php";

//Tags used in the JSON String
public static final String TAG_NAME = "name";
public static final String TAG_BADGEID = "badgeid";

//JSON array name
public static final String JSON_ARRAY = "result";}

1 个答案:

答案 0 :(得分:0)

在此之后您错过了一步

editor.putString("reviewer",spinner.getSelectedItem().toString());

您需要保存更改,在下面输入此行:

editor.commit();

应该可以。