【问题标题】:How to save Rating of each item in list view?如何在列表视图中保存每个项目的评分?
【发布时间】:2019-12-16 16:24:02
【问题描述】:

1. 我有一个ListView,其中包含图像、人名、人的生日。当用户单击一个项目时,将启动一个新活动以显示该项目的详细信息。在此活动中,我创建了一个评分栏,用户将在其中对每个项目进行评分。

2. 我曾尝试使用SharedPreferences 来保存评分项目的平均计算值。我发现当我保存费率并再次启动应用程序时,这些值并未存储在@987654323 @。

我要实现的主要目标是计算每个评分项目的平均值并将它们保存在SharedPreferences

3.人物类:

    public class PersonInfo {
    private int image;
    private String name;
    private String birthday;
    private float  rating;


    public PersonInfo(int image, String name, String birthday, float rating) {
        this.image = image;
        this.name = name;
        this.birthday = birthday;
        this.rating = rating;
    }

    public float getRating() {
        return rating;
    }

    public void setRating(float rating) {
        this.rating = rating;
    }

    public String getName(){
        return name;
    }
    public int getImage() {
        return image;
    }

    public void setName(String name) {
        this.name = name;
    }


    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

}

人物适配器:

    public class StudentsListAdapter extends ArrayAdapter<PersonInfo>{
    private Context contxt;
    private int rsrc;
    private List<PersonInfo> persons;
    private boolean isAdmin;
    private TextView pName, pBirthday;

public StudentsListAdapter( Context context, int resource, List<PersonInfo> _persons,  boolean _isAadmin) {
        super(context, resource, _persons);
        contxt = context;
        rsrc = resource;
        persons=_persons;
        isAdmin = _isAadmin;
}

@NonNull
    @Override
    public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        LayoutInflater inflater = LayoutInflater.from(contxt);
        View view = inflater.inflate(rsrc, null,false);


        ImageView imageView = view.findViewById(R.id.imgP);
        pName = view.findViewById(R.id.txtView2);
        pBirthday = view.findViewById(R.id.txtView3);

         PersonInfo p = persons.get(position);

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(contxt,ViewItems.class);

                String name = persons.get(position).getName();
                String birth = persons.get(position).getBirthday();
                intent1.putExtra("name",name);
                intent1.putExtra("birth",birth);
                contxt.startActivity(intent1);
            }
        });

        imageView.setImageDrawable(contxt.getResources().getDrawable(p.getImage()));
        pBirthday.setText(p.getBirthday());
        pName.setText(p.getName());
    }
    return view;

}

评价项目:

        public class ViewItems extends AppCompatActivity {

    EditText edName;
    TextView edBirth;
    float myRating = 0;
    Button svRate;
    RatingBar rtBar;
    String position;
    SharedPreferences.Editor editor;

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

        edName = findViewById(R.id.st_editName);
        edBirth = findViewById(R.id.tv_editDate);
        rtBar = findViewById(R.id.ratingBar);

        Bundle extras = getIntent().getExtras();
        String name = extras.getString("name");
        edName.setText(name);
        edName.setEnabled(false);
        edName.setTextColor(Color.BLACK);
        String birth = extras.getString("birth");
        edBirth.setText(birth);
        edBirth.setEnabled(false);
        edBirth.setTextColor(Color.BLACK);

        ImageView image = (ImageView) findViewById(R.id.user_img);
        image.setBackgroundResource(android.R.drawable.btn_star);

        position = getIntent().getStringExtra("position");

        rtBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                int rating1 = (int) rating;
                String message = null;

                myRating = ratingBar.getRating();

                switch (rating1){

                    case 1:
                        message = "Sorry to hear that!";
                        break;

                    case 2:
                        message = "You always accept suggestions!";
                        break;

                    case 3:
                        message = "Good enough!";
                        break;

                    case 4:
                        message = "Great! Thank you!";
                        break;

                    case 5:
                        message = "Awesome! You are the best!";
                        break;

                }

                Toast.makeText(ViewItems.this, message, Toast.LENGTH_SHORT).show();
            }
        });

        svRate = findViewById(R.id.sv_item);

        svRate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i4 = new Intent(ViewItems.this, MainActivity.class);
                SharedPreferences sharedPreferences = getSharedPreferences("SaveRating",Context.MODE_PRIVATE);
                myRating = sharedPreferences.getFloat("rating_float", 0f);
                float total = 0;
                total += rtBar.getRating();
                float average = total / 2;
                rtBar.setRating(average);
                startActivity(i4);
                Toast.makeText(ViewItems.this, "Your rating is:" + (myRating), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

主要活动:

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private TextView edName,edBirth;
    String position;
    String ed_name;
    String ed_birth;
     String username, password;
    ArrayList<PersonInfo> students;
    ArrayList<PersonInfo> students1;
    ListView listView1;
    SharedPreferences sharedPref;
    SharedPreferences.Editor editor;
    float rtBar;

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

        students = new ArrayList<>();
        students1 = new ArrayList<>();
         Intent intent = getIntent();
        if(getIntent() != null){
            username = intent.getStringExtra("Username");
            password = intent.getStringExtra("Password");
             edName = findViewById(R.id.txtView2);
        edBirth = findViewById(R.id.txtView3);

        listView1 = (ListView) findViewById(R.id.li_view);

        students1.add(new PersonInfo(android.R.drawable.btn_star, "Test1", "03/27/1998", 3));
        students1.add(new PersonInfo(android.R.drawable.btn_star, "Test2", "03/27/1998",2));
        students1.add(new PersonInfo(android.R.drawable.btn_star, "Test3", "03/27/1998",1));
        students1.add(new PersonInfo(android.R.drawable.btn_star, "Test4", "03/27/1998",5));

        test1 = new StudentsListAdapter(
                this, R.layout.adapter_view_layout, students1, true);
        listView1.setAdapter(test1);

        if(username!= null && username.equals("test") && password != null && password.equals("123")){

            Log.d(TAG, "onCreate: Started.");
            ListView listView = (ListView) findViewById(R.id.li_view);


        students.add(new PersonInfo(android.R.drawable.btn_star, "Test1", "03/27/1998", 3));
        students.add(new PersonInfo(android.R.drawable.btn_star, "Test2", "03/27/1998",2));
        students.add(new PersonInfo(android.R.drawable.btn_star, "Test3", "03/27/1998",1));
        students.add(new PersonInfo(android.R.drawable.btn_star, "Test4", "03/27/1998",5));


            test1 = new StudentsListAdapter(
                    this, R.layout.adapter_view_layout, students, true);
            listView1.setAdapter(test1);
        }
            else if (username != null && username.equals("test2") && password != null && password.equals("1234"))
            {
                ListView listView = (ListView) findViewById(R.id.li_view);

        students.add(new PersonInfo(android.R.drawable.btn_star, "Test1", "03/27/1998", 3));
        students.add(new PersonInfo(android.R.drawable.btn_star, "Test2", "03/27/1998",2));
        students.add(new PersonInfo(android.R.drawable.btn_star, "Test3", "03/27/1998",1));
        students.add(new PersonInfo(android.R.drawable.btn_star, "Test4", "03/27/1998",5));

                test1 = new StudentsListAdapter(
                        this, R.layout.adapter_view_layout, students,false);
                listView1.setAdapter(test1);


            }

        SharedPreferences sharedPreferences = getSharedPreferences("SaveRating",Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
        editor.putFloat("rating_float", rtBar);
        editor.apply();
        }
    }

 }

我做错了什么?

任何帮助将不胜感激。 谢谢!

【问题讨论】:

    标签: java android listview sharedpreferences ratingbar


    【解决方案1】:

    你甚至不尝试保存任何东西。你只要把 rtBar

    editor.putFloat("rating_float", rtBar);

    即使没有初始化,但如果这是原始类型的数据float,它具有默认值0

    【讨论】:

    • 嗨@EugeneTroyanskii,我已经将MainActivity中的rtBar初始化为全局变量以浮动rtBar = 0;在调试时,我在设置费率后在费率项目中得到了正确的结果。但是我想将每个项目的费率存储在 sharedpreferences 中,这样当我关闭应用程序并重新打开时,我可以看到该项目的保存费率。请看here调试结果。谢谢!
    • @FearLessAZ 存储项目使用数据库或后端部分。 sharedpreferences 是一个错误的选择。而这部分 myRating = sharedPreferences.getFloat("rating_float", 0f);总是 0 所以我不知道结果是否正确:D
    【解决方案2】:

    我想你忘了初始化 rtBar,就像@Eugene 告诉你的那样。您可以通过获取所有学生的平均值来初始化它:

    for (PersonInfo personInfo : students) {
        rtBar += personInfo.getRating();
    }
    // now store it in sharedPrefs
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-23
      • 2021-04-07
      相关资源
      最近更新 更多