Рейтинговый бар получает 0 в представлении переработчика - PullRequest
2 голосов
/ 23 декабря 2019

В моем приложении у меня есть представление рециркулятора, которое содержит название и адрес ресторана, и я просто попытался добавить к нему строку рейтинга, и я получаю все данные из базы данных SQL, и я использую залп для подключения к нему, каждыйвсе работает отлично, и я даже могу отправить рейтинг ресторана, но когда я пытаюсь получить данные, я получаю 0 и проверяю REST API и Json, когда я устанавливаю окончательное значение рейтинга без базы данных в своем классе адаптера Recycler. работает, но когда я пытаюсь установить данные в моем MainActivity и получить их в моем держателе bindview, он получает 0, помогите

MainActivty

public void sendRequest(){

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, request_url, null, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                restaurants.clear();
                for (int i = 0; i < response.length(); i++) {
                    Restaurant restaurant = new Restaurant();

                    try {
                        JSONObject jsonObject = response.getJSONObject(i);
                        restaurant.setId(jsonObject.getInt("restaurant_id"));
                        restaurant.setName(jsonObject.getString("restaurant_name"));
                        restaurant.setAddress(jsonObject.getString("restaurant_address"));
                        restaurant.setImage(jsonObject.getInt("restaurant_image_type"));
                        restaurant.setHasNote(jsonObject.getBoolean("restaurant_has_note"));
                        restaurant.setRating((float) jsonObject.getInt("restaurant_rating"));
                        swipeRefreshLayout.setRefreshing(false);
                    } catch (JSONException e) {
                        swipeRefreshLayout.setRefreshing(false);
                        Log.i("VolleyGetError",e.toString());
                        e.printStackTrace();
                    }
                    restaurants.add(restaurant);
                    adapter.notifyDataSetChanged();
                    shimmerContainer.stopShimmerAnimation();
                    shimmerContainer.setVisibility(View.GONE);
                }
                fastfoodRecyclerView.setAdapter(adapter);
                swipeRefreshLayout.setRefreshing(false);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("Volley Error:", String.valueOf(error));
            }
        });
        RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
        queue.add(jsonArrayRequest);

    }

Мой класс POJO

public Restaurant() {
    }

    public Restaurant(String name, String address,int type){
        this.name = name;
        this.address = address;
        this.type = type;
    }

    public Restaurant(int id, String name, String address,int type){
        this.id = id;
        this.name = name;
        this.address = address;
        this.type = type;
    }

    public Restaurant(int id,  String name, String address, int type,int image,int count) {
        this.id = id;
        this.name = name;
        this.address = address;
        this.type = type;
        this.image = image;
        this.count = count;
    }

    public Restaurant(int id,  String name, String address, int type,int image,int count,float rating) {
        this.id = id;
        this.name = name;
        this.address = address;
        this.type = type;
        this.image = image;
        this.count = count;
        this.rating = rating;
    }

    public float getRating() {
        return rating;
    }

    public int getCount() {
        return count;
    }

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

    public void setCount (int count) {this.count = count;}

    public int getId() { return id;}

    public void  setId (int id) { this.id = id;}

    public String getName() {
        return name;
    }

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

    public boolean isHasNote(){
        return hasNote;
    }

    public void setHasNote(boolean hasNote){
        this.hasNote = hasNote;
    }

    public String getAddress() { return address;}

    public void setAddress(String address) { this.address = address;}

    public void setType(int type) {this.type = type;}

    public int getType() {return type;}

    public int getImage() {return image;}

    public void setImage(int image) {this.image = image;}
}

Мой адаптер класса Recycler

        TextView listviewName,listviewAddress;
        ImageView icon,noteIcon,deleteicon;
        RelativeLayout viewBackground, viewForeground;
        RatingBar ratingBar;

        MyViewHolder(View view){
            super(view);
            ratingBar = view.findViewById(R.id.rating_bar);
            listviewName = view.findViewById(R.id.listview_name);
            listviewAddress = view.findViewById(R.id.listview_address);
            icon = view.findViewById(R.id.type_ic);
            noteIcon = view.findViewById(R.id.note_icon);
            deleteicon = view.findViewById(R.id.delete_icon);
            deleteicon.setVisibility(View.GONE);
            viewBackground = view.findViewById(R.id.view_background);
            viewForeground = view.findViewById(R.id.view_foreground);
            view.setOnCreateContextMenuListener(this);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.onRestaurantSelected(restaurantListFiltered.get(getAdapterPosition()));
                }
            });
        }
        @Override
        public void onCreateContextMenu(ContextMenu menu,View v,ContextMenu.ContextMenuInfo menuInfo) {
            AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
            menu.add(0, 1, 0, "Edit");
            menu.add(0, 2, 1, "Remove");
            menu.add(0, 3, 2, "Add Note");
            menu.add(0, 4, 3, "All Notes");
        }
    }
    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout,parent,false);
        Animation animation = AnimationUtils.loadAnimation(context, R.anim.fadein);
        itemView.startAnimation(animation);
        return new MyViewHolder(itemView);
    }
    @Override
    public void onBindViewHolder(@NonNull final MyViewHolder holder, int position) {

        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                setPosition(holder.getAdapterPosition());
                return false;
            }
        });
        Restaurant restaurant = restaurantList.get(position);
        holder.listviewName.setText(restaurant.getName());
        holder.listviewAddress.setText(restaurant.getAddress());
        holder.ratingBar.setRating(restaurant.getRating());
        switch (restaurant.getImage()) {
            case RestaurantContract.EntryRestaurants.RESTAURANT_TYPE_DELIVERY:
                holder.icon.setImageResource(R.drawable.phoneorderr);
                break;
            case RestaurantContract.EntryRestaurants.RESTAURANT_TYPE_SITDOWN:
                holder.icon.setImageResource(R.drawable.sitdownn);
                break;
            case RestaurantContract.EntryRestaurants.RESTAURANT_TYPE_TAKEAWAY:
                holder.icon.setImageResource(R.drawable.takeaway);
                break;
        }
        holder.noteIcon.setImageResource(R.drawable.notepadicon);
        if(restaurant.isHasNote()) {
            holder.noteIcon.setVisibility(View.VISIBLE);
        }else {
            holder.noteIcon.setVisibility(View.INVISIBLE);
        }

    }

Мой JSON

    {
        "restaurant_id": "97",
        "restaurant_name": "tt",
        "restaurant_address": "rr",
        "restaurant_type": "0",
        "restaurant_has_note": "0",
        "restaurant_image_type": "2",
        "restaurant_rating": "3"
    }
]

1 Ответ

0 голосов
/ 23 декабря 2019

Во-первых, у вас класс POJO как Restaurant. Добавьте значение ниже к своему rating полю

public Restaurant(){
public float rating = 0.0f;
}

Во-вторых, вам нужно будет прослушать изменения в вашей рейтинговой строке на вашем MyViewHolder, как показано ниже:

  ratingBar = (RatingBar) view.findViewById(R.id.rating_bar);
        ratingBar .setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
        @Override
        public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
            restaurants.get(getPosition()).rating = ratingBar.getRating();
        }
    });

Я вижу вася уже реализовал arraylist с именем restaurantList, я все же упомянул реализацию ниже для справки:

Затем в вашем адаптере вам нужно будет реализовать arraylist для извлеченияданные для вашего ratingBar

static List<Restaurant> restaurants= new ArrayList<>(); //restaurantList in your 

Инициируйте его в своем конструкторе.

this.restaurants = restaurants;//restaurantList in your case

Затем в вашем onBindViewHolder

List<String> restro= new ArrayList<String>();

     for(int i=0;i<restaurants.size();i++){
        restro.add(String.valueOf(restaurants.rating));//restaurantList in your case
    }

Надежда, которая помогает.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...