Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

Вот код , твоя задача добавить еще 5 товаров : package com.example.myapp2; public class…

  1. User

    Вот код , твоя задача добавить еще 5 товаров : package com.example.myapp_2;

    public class Product { private String name; private String description; private int imageResource; private float rating;

    public Product(String name, String description, int imageResource, float rating) { this.name = name; this.description = description; this.imageResource = imageResource; this.rating = rating; }

    public String getName() { return name; }

    public String getDescription() { return description; }

    public int getImageResource() { return imageResource; }

    public float getRating() { return rating; }

    public void setRating(float rating) { this.rating = rating; } } package com.example.myapp_2;

    import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView;

    import androidx.recyclerview.widget.RecyclerView;

    import java.util.List;

    public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> { private List products; private Context context;

    public ProductAdapter(Context context, List products) { this.context = context; this.products = products; }

    @Override public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.item_product, parent, false); return new ProductViewHolder(view); }

    @Override public void onBindViewHolder(ProductViewHolder holder, int position) { Product product = products.get(position); holder.productImage.setImageResource(product.getImageResource()); holder.productName.setText(product.getName()); holder.productDescription.setText(product.getDescription()); holder.productRating.setText(String.format(“%.1f”, product.getRating())); }

    @Override public int getItemCount() { return products.size(); }

    public class ProductViewHolder extends RecyclerView.ViewHolder { ImageView productImage; TextView productName; TextView productDescription; TextView productRating;

    public ProductViewHolder(View view) { super(view); productImage = view.findViewById(R.id.product_image); productName = view.findViewById(R.id.product_name); productDescription = view.findViewById(R.id.product_description); productRating = view.findViewById(R.id.product_rating);

    view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showRatingDialog(getAdapterPosition()); } }); } }

    private void showRatingDialog(final int position) { final RatingDialog ratingDialog = new RatingDialog(context); ratingDialog.setRating(products.get(position).getRating()); ratingDialog.setOnRatingChangedListener(new RatingDialog.OnRatingChangedListener() { @Override public void onRatingChanged(float newRating) { products.get(position).setRating(newRating); notifyDataSetChanged(); } }); ratingDialog.show(); } } package com.example.myapp_2;

    import android.app.AlertDialog; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.RatingBar; import android.widget.TextView;

    public class RatingDialog extends AlertDialog implements RatingBar.OnRatingBarChangeListener { private RatingBar ratingBar; private TextView ratingMessage; private float rating; private OnRatingChangedListener listener;

    public RatingDialog(Context context) { super(context); View view = LayoutInflater.from(context).inflate(R.layout.dialog_rating, null); ratingBar = view.findViewById(R.id.rating_bar); ratingMessage = view.findViewById(R.id.rating_message); ratingBar.setOnRatingBarChangeListener(this); setView(view); }

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

    public void setOnRatingChangedListener(OnRatingChangedListener listener) { this.listener = listener; }

    @Override public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) { this.rating = rating; String message = String.format(getContext().getString(R.string.rating_message), String.valueOf(rating)); ratingMessage.setText(message);

    // Сохраняем оценку в SharedPreferences SharedPreferences prefs = getContext().getSharedPreferences(“MyPrefs”, Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.putFloat(“rating”, rating); editor.apply(); }

    @Override public void onStart() { super.onStart(); onRatingChanged(ratingBar, rating, true); }

    @Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); rating = savedInstanceState.getFloat(“rating”); ratingBar.setRating(rating); }

    public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(); outState.putFloat(“rating”, rating); }

    @Override public void onStop() { super.onStop(); if (listener != null) { listener.onRatingChanged(rating); } }

    public interface OnRatingChangedListener { void onRatingChanged(float newRating); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_first, container, false);

    recyclerView = v.findViewById(R.id.recycler_view_products); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); productAdapter = new ProductAdapter(getContext(), products); recyclerView.setAdapter(productAdapter);

    viewPager = v.findViewById(R.id.view_pager); SliderAdapter adapter = new SliderAdapter(getActivity(), imageUrls); viewPager.setAdapter(adapter);

    // Получаем оценки из SharedPreferences SharedPreferences prefs = getContext().getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE); rating1 = prefs.getFloat(“rating1”, 0.0f); rating2 = prefs.getFloat(“rating2”, 0.0f); rating3 = prefs.getFloat(“rating3”, 0.0f);

    // Устанавливаем оценки в соответствующие товары products.get(0).setRating(rating1); products.get(1).setRating(rating2); products.get(2).setRating(rating3);final Handler handler = new Handler(); final Runnable runnable = new Runnable() { @Override public void run() { int currentItem = viewPager.getCurrentItem(); int totalItems = viewPager.getAdapter().getCount(); int nextItem = currentItem == totalItems - 1 ? 0 : currentItem + 1; viewPager.setCurrentItem(nextItem); handler.postDelayed(this, 3000); } }; handler.postDelayed(runnable, 3000);

        return v;
    }
    
    private List<Product> getProducts() {
        List<Product> products = new ArrayList<>();
    
        Product product1 = new Product("Product 1", "Description 1", R.drawable.food_3_1jpg, 0.0f);
        products.add(product1);
    
        Product product2 = new Product("Product 2", "Description 2", R.drawable.food_1_1, 0.0f);
        products.add(product2);
    
        Product product3 = new Product("Product 3", "Description 3", R.drawable.food_1_4, 0.0f);
        products.add(product3);
    
        return products;
    }
    
    
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {//После того как отрисовались лементы
        super.onViewCreated(view,savedInstanceState);
        initView(view);
    
    }
    private void initView(View view){
        Button btnClick = (Button) view.findViewById(R.id.btn_2);
        Button btnClick2 = (Button) view.findViewById(R.id.btn_3);
        btnClick.setOnClickListener(this);
        btnClick2.setOnClickListener(this);
    
        Button btnClick3 = (Button) view.findViewById(R.id.button);
        btnClick3.setOnClickListener(this);
    
        Button btnClick4 = (Button) view.findViewById(R.id.change_btn);
        btnClick4.setOnClickListener(this);
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
    
    
    
    
    
    
        Bundle bundle = this.getArguments();
        if (bundle != null) {
            int myInt = bundle.getInt("hello world", 123);
            String strI = Integer.toString(myInt);
            Toast.makeText(getActivity(),strI,Toast.LENGTH_SHORT).show();
        }
    
    
    
    
    
    
    
    
    }
    
    @Override
    public void onStart() {
        super.onStart();
    
    
    
    }
    
    @Override
    public void onResume() {
        super.onResume();
    
    }
    
    @Override
    public void onPause(){
        super.onPause();
    

    // Сохраняем оценки в SharedPreferences SharedPreferences.Editor editor = getContext().getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE).edit(); editor.putFloat("rating1", products.get(0).getRating()); editor.putFloat("rating2", products.get(1).getRating()); editor.putFloat("rating3", products.get(2).getRating()); editor.apply(); }

    @Override
    public void onStop() {
        super.onStop();
    
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
    
    }
    
    private void  changeFragment(){
        getFragmentManager().beginTransaction().replace(R.id.nav_container,new SecondFragment()).addToBackStack(null).commit();
    }
    private void  changeFragment2(){
        getFragmentManager().beginTransaction().replace(R.id.nav_container,new ThirdFragment()).addToBackStack(null).commit();
    }
    private void  changeFragment3(){
        getFragmentManager().beginTransaction().replace(R.id.nav_container,new ListFragment()).addToBackStack(null).commit();
    }
    private void  changeFragment4(){
        getFragmentManager().beginTransaction().replace(R.id.nav_container,new RecycleFragment()).addToBackStack(null).commit();
    }
    Context context;
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_2:
                changeFragment4();
                break;
            case R.id.btn_3:
    
                createFile("test4.txt", "Мой финальный текстовый документ");
                //createTextFileInDirectory("test1.txt");
    
    
                break;
            case R.id.button:
    
                changeFragment3();
                break;
            case R.id.change_btn:
                changeFragment4();
                break;
        }
    }
    
    
    @Override
    public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
    
    }
    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
    // Сохраняем оценки в Bundle
        outState.putFloat("rating1", rating1);
        outState.putFloat("rating2", rating2);
        outState.putFloat("rating3", rating3);
    }
    
    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
        if (savedInstanceState != null) {
    // Восстанавливаем оценки из Bundle
            rating1 = savedInstanceState.getFloat("rating1");
            rating2 = savedInstanceState.getFloat("rating2");
            rating3 = savedInstanceState.getFloat("rating3");
    
    // Устанавливаем оценки в соответствующие товары
            products.get(0).setRating(rating1);
            products.get(1).setRating(rating2);
            products.get(2).setRating(rating3);
        }
    }
    
    
    // Метод, который создает список товаров
    

    } (укажи подробно в каких класса и в каких меттодах нужно произвести конкретные изменения чтобы добавить 5 новых товаров)

  2. Assistant

    Для добавления 5 новых товаров нужно произвести следующие изменения:

    1. В классе Product добавить конструкторы для каждого из 5 товаров:

    public Product(String name, String description, int imageResource, float rating) { this.name = name; this.description = description; this.imageResource = imageResource; this.rating = rating; }

    public Product(String name, String description, int imageResource) { this.name = name; this.description = description; this.imageResource = imageResource; this.rating = 0.0f; }

    1. В классе FirstFragment в методе getProducts() добавить код для создания новых товаров:

    private List getProducts() { List products = new ArrayList<>();

    Product product1 = new Product("Product 1", "Description 1", R.drawable.food_3_1jpg, 0.0f); products.add(product1);

    Product product2 = new Product("Product 2", "Description 2", R.drawable.food_1_1, 0.0f); products.add(product2);

    Product product3 = new Product("Product 3", "Description 3", R.drawable.food_1_4, 0.0f); products.add(product3);

    Product product4 = new Product("Product 4", "Description 4", R.drawable.food_2_1, 0.0f); products.add(product4);

    Product product5 = new Product("Product 5", "Description 5", R.drawable.food_2_2, 0.0f); products.add(product5);

    Product product6 = new Product("Product 6", "Description 6", R.drawable.food_2_3); products.add(product6);

    Product product7 = new Product("Product 7", "Description 7", R.drawable.food_3_2); products.add(product7);

    Product product8 = new Product("Product 8", "Description 8", R.drawable.food_3_3); products.add(product8);

    Product product9 = new Product("Product 9", "Description 9", R.drawable.food_4_1); products.add(product9);

    Product product10 = new Product("Product 10", "Description 10", R.drawable.food_4_2); products.add(product10);

    return products; }

    1. В классе FirstFragment в методе onResume() добавить код для обновления адаптера:

    @Override public void onResume() { super.onResume();

    productAdapter.notifyDataSetChanged(); }

    После этих изменений будет создано 10 товаров и они будут отображены в списке товаров в приложении. Также при переходе на экран списка товаров и обратно список будет обновляться, чтобы отобразить текущие оценки товаров.

  3. User

    оценка новых товаров сбрасывается после перезапуска приложения .Исправь это

  4. Assistant

    Чтобы оценка новых товаров не сбрасывалась после перезапуска приложения, нужно использовать SharedPreferences для сохранения оценок и получения их при повторном запуске приложения.

    1. В классе Product добавить переменную id для каждого товара:
    private String name;
    private String description;
    private int imageResource;
    private float rating;
    private String id;
    
    public Product(String name, String description, int imageResource, float rating, String id) {
        this.name = name;
        this.description = description;
        this.imageResource = imageResource;
        this.rating = rating;
        this.id = id;
    }
    
    public String getId() {
        return id;
    }
    
    public void setId(String id) {
        this.id = id;
    }
    
    1. В классе FirstFragment в методе getProducts() добавить присвоение id каждому товару:
    Product product1 = new Product("Product 1", "Description 1", R.drawable.food_3_1jpg, 0.0f, "product1");
    products.add(product1);
    
    Product product2 = new Product("Product 2", "Description 2", R.drawable.food_1_1, 0.0f, "product2");
    products.add(product2);
    
    Product product3 = new Product("Product 3", "Description 3", R.drawable.food_1_4, 0.0f, "product3");
    products.add(product3);
    
    Product product4 = new Product("Product 4", "Description 4", R.drawable.food_2_1, 0.0f, "product4");
    products.add(product4);
    
    Product product5 = new Product("Product 5", "Description 5", R.drawable.food_2_2, 0.0f, "product5");
    products.add(product5);
    
    1. В методе createProducts() добавить код для сохранения оценки каждого товара в SharedPreferences:
    private void createProducts() {
        SharedPreferences prefs = getContext().getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE);
        rating1 = prefs.getFloat("rating1", 0.0f);
        rating2 = prefs.getFloat("rating2", 0.0f);
        rating3 = prefs.getFloat("rating3", 0.0f);
        rating4 = prefs.getFloat("rating4", 0.0f);
        rating5 = prefs.getFloat("rating5", 0.0f);
    
        Product product1 = new Product("Product 1", "Description 1", R.drawable.food_3_1jpg, rating1, "product1");
        products.add(product1);
    
        Product product2 = new Product("Product 2", "Description 2", R.drawable.food_1_1, rating2, "product2");
        products.add(product2);
    
        Product product3 = new Product("Product 3", "Description 3", R.drawable.food_1_4, rating3, "product3");
        products.add(product3);
    
        Product product4 = new Product("Product 4", "Description 4", R.drawable.food_2_1, rating4, "product4");
        products.add(product4);
    
        Product product5 = new Product("Product 5", "Description 5", R.drawable.food_2_2, rating5, "product5");
        products.add(product5);
        
        productAdapter.notifyDataSetChanged();
    }
    
    1. В методе setOnRatingChangedListener() класса ProductAdapter добавить код для сохранения оценки товара в SharedPreferences после ее изменения:
    @Override
    public void onRatingChanged(float newRating) {
        products.get(position).setRating(newRating);
        notifyDataSetChanged();
    
        // Сохраняем оценку в SharedPreferences
        SharedPreferences prefs = context.getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE);
        String id = products.get(position).getId();
        prefs.edit().putFloat("rating" + id, newRating).apply();
    }
    

    Теперь приложение будет сохранять оценки каждого товара в SharedPreferences и получать их при повторном запуске приложении, таким образом, оценки новых товаров будут сохраняться после перезапуска приложения.

  5. User

    а теперь добавь столько же товаров (важно чтобы товары были другими ) на SecondFragment (учитывая то что мы уже реализовали нужные класс , то возможно потребуется изменить только сам класс SecondFragment)

  6. Assistant

    Чтобы добавить столько же товаров на SecondFragment, нужно произвести следующие изменения:

    1. В классе Product добавить конструкторы для каждого из 5 товаров:
    public Product(String name, String description, int imageResource, float rating, String id) {
        this.name = name;
        this.description = description;
        this.imageResource = imageResource;
        this.rating = rating;
        this.id = id;
    }
    
    public Product(String name, String description, int
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.