How do you SAVE user rating in rating bar?

前端 未结 1 1686
夕颜
夕颜 2021-01-29 04:41

Hello all :) I have a rating bar and it works but the rating doesn\'t save when the user leaves the page. How do you save the user rating?

Here\'s the code

相关标签:
1条回答
  • 2021-01-29 05:02

    You can use SharedPreferences for that..

    Save the ratings in SharedPreferences before leaving the app and retrieve the ratings from SharedPreferences and set it in the ratings bar when you come back to the application..

    SharedPreferences wmbPreference1,wmbPreference2;    
    SharedPreferences.Editor editor;
    
    //wmbPreference for Shared Prefs that lasts forever
    wmbPreference1 = PreferenceManager.getDefaultSharedPreferences(this);  
    
    //installsp for Shared Prefs that lasts only just once each time program is running
    wmbPreference2 =getApplicationContext().getSharedPreferences("MYKEY",Activity.MODE_PRIVATE);
    

    To save values

    SharedPreferences.Editor editor = wmbPreference1.edit();
    editor.putString("MYKEY", "12345");
    editor.commit();
    

    You can retrieve the values like

    String Phonenumber = wmbPreference1.getString("MYKEY", "");
    

    where MYKEY is the keyname by which you can identify the value..


    EDIT


    Change your code like this

    SharedPreferences wmbPreference1;    
    SharedPreferences.Editor editor;
    @Override
    protected void onCreate(Bundle savedInstanceState) {    
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_item_activity_1);  
    ratingText = (TextView) findViewById(R.id.rating);
    ((RatingBar) findViewById(R.id.ratingBar1))
    .setOnRatingBarChangeListener(this);  
    wmbPreference1 = PreferenceManager.getDefaultSharedPreferences(this);      
    }
    
    @Override
    public void onRatingChanged(RatingBar ratingBar, float rating,
    boolean fromTouch) {
    final int numStars = ratingBar.getNumStars();
    editor = wmbPreference1.edit();
    editor.putInt("numStars", numStars);
    editor.commit();
    

    And when you come back do this,ie when you want to retrieve the ratings

    int ratings = wmbPreference1.getInt("numStars", 0);
    ratingText.setText(rating + "/" + String.valueOf(ratings));
    

    Here ratings will hold the ratings which was set earlier..

    0 讨论(0)
提交回复
热议问题