Форум программистов, компьютерный форум, киберфорум
Программирование Android
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.57/7: Рейтинг темы: голосов - 7, средняя оценка - 4.57
0 / 0 / 0
Регистрация: 13.06.2017
Сообщений: 29

Добрый вечер, не работает корзина при нажатии

10.06.2019, 23:30. Показов 1343. Ответов 1

Студворк — интернет-сервис помощи студентам
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package com.example.shop;
 
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
 
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
 
import com.example.shop.Model.Cart;
import com.example.shop.Prevalent.Prevalent;
import com.example.shop.ViewHolder.CartViewHolder;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.rey.material.widget.TextView;
 
import static com.example.shop.R.id.total_price;
 
public class CartActivity extends AppCompatActivity
{
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private Button NextProcessBtn;
    private TextView txtTotalAmount;
 
    private int overTotalPrice = 0;
 
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);
 
        recyclerView = findViewById(R.id.cart_list);
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
 
 
        NextProcessBtn = (Button) findViewById(R.id.next_process);
        txtTotalAmount = (TextView) findViewById(R.id.total_price);
 
        NextProcessBtn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                txtTotalAmount.setText("Общая цена = " + String.valueOf(overTotalPrice));
 
              Intent intent = new Intent(CartActivity.this,FinalActivity.class);
              intent.putExtra("Общая цена", String.valueOf(overTotalPrice));
              startActivity(intent);
              finish();
            }
        });
    }
 
 
    @Override
    protected void onStart()
    {
        super.onStart();
 
 
        final DatabaseReference cartListRef = FirebaseDatabase.getInstance().getReference().child("Cart");
 
        FirebaseRecyclerOptions<Cart> options =
                new FirebaseRecyclerOptions.Builder<Cart>()
                .setQuery(cartListRef.child("User View")
                        .child(Prevalent.currentOnlineUser.getPhone())
                        .child("Products"), Cart.class)
                        .build();
 
        FirebaseRecyclerAdapter<Cart, CartViewHolder> adapter
                = new FirebaseRecyclerAdapter<Cart, CartViewHolder>(options)
        {
            @Override
            protected void onBindViewHolder(@NonNull CartViewHolder holder, int position, @NonNull final Cart model)
            {
                holder.txtProductQuantity.setText("Кол-во = " + model.getQuantity());
                holder.txtProductPrice.setText("Цена" + model.getPrice() + "P");
                holder.txtProductName.setText(model.getPname());
 
                int onTyprProductTPrice = ((Integer.valueOf(model.getPrice()))) * Integer.valueOf(model.getQuantity());
                overTotalPrice = overTotalPrice + onTyprProductTPrice;
 
                holder.itemView.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        CharSequence options[] = new CharSequence[]
                                {
                                     "Редактировать",
                                        "Удалить"
                                };
                        AlertDialog.Builder builder = new AlertDialog.Builder(CartActivity.this);
                        builder.setTitle("Настройки Корзины");
 
 
                        builder.setItems(options, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i)
                            {
                                if (i == 0)
                                {
                                    Intent intent = new Intent(CartActivity.this, ProductDelActivity.class);
                                    intent.putExtra("pid", model.getPid());
                                    startActivity(intent);
                                }
                                if (i == 1)
                                {
                                    cartListRef.child("User View")
                                            .child(Prevalent.currentOnlineUser.getPhone())
                                            .child("Products")
                                            .child(model.getPid())
                                            .removeValue()
                                            .addOnCompleteListener(new OnCompleteListener<Void>() {
                                                @Override
                                                public void onComplete(@NonNull Task<Void> task)
                                                {
                                                    if (task.isSuccessful())
                                                    {
                                                        Toast.makeText(CartActivity.this, "Товар удален", Toast.LENGTH_SHORT).show();
 
                                                        Intent intent = new Intent(CartActivity.this, HomeActivity.class);
                                                        startActivity(intent);
                                                    }
                                                }
                                            });
                                }
                            }
                        });
                        builder.show();
                    }
                });
            }
 
            @NonNull
            @Override
            public CartViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
            {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_items, parent, false);
                CartViewHolder holder = new CartViewHolder(view);
                return holder;
            }
        };
 
        recyclerView.setAdapter(adapter);
        adapter.startListening();
 
    }
}
XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".CartActivity">
 
    <RelativeLayout
        android:id="@+id/r1"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/R"
        android:layout_alignParentTop="true"
        >
 
        <TextView
            android:id="@+id/total_price"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Общая цена = "
            android:textColor="@color/W"
            android:textSize="20sp"
            android:textAlignment="center"
            android:layout_marginTop="10dp"
            />
 
    </RelativeLayout>
 
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/cart_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/r1"
        android:layout_above="@+id/next_process"
        >
 
 
    </androidx.recyclerview.widget.RecyclerView>
    
    <Button
        android:id="@+id/next_process"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@color/R"
        android:text="Далее"
        android:textColor="@color/W"
        android:textSize="20sp"
 
 
        />
XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    app:cardElevation="15dp">
 
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="10dp"
        android:background="@color/colorAccent">
 
        <TextView
            android:id="@+id/c_product_name"
            android:layout_width="160dp"
            android:layout_height="wrap_content"
            android:text="Имя"
            android:textColor="@color/W"
            android:textSize="14sp"
            android:layout_marginLeft="5dp"
 
            />
 
        <TextView
            android:id="@+id/ca_product_name"
            android:layout_width="160dp"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_marginLeft="5dp"
            android:text="Кол-во"
            android:textAlignment="viewEnd"
            android:textColor="@color/W"
            android:textSize="14sp"
            android:layout_marginRight="5dp"
            />
        <TextView
            android:id="@+id/cart_product_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Цена"
            android:textColor="@color/W"
            android:textSize="14sp"
            android:layout_marginLeft="5dp"
            android:layout_below="@id/ca_product_name"
            android:gravity="center"
            android:layout_marginTop="10dp"
            />
 
 
 
 
    </RelativeLayout>
Вот ошибка
Миниатюры
Добрый вечер, не работает корзина при нажатии  
0
Лучшие ответы (1)
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
10.06.2019, 23:30
Ответы с готовыми решениями:

Добрый вечер, программа работает, но необходимо поменять public на private. Я не знаю как это делается. Спасибо
#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;fstream&gt; #include &lt;cstring&gt; #include &lt;cstdlib&gt; #include &lt;algorithm&gt; ...

Добрый вечер! При отладки следующая ошибка (вложение). Как исправить? VS2015
#define _CRT_SECURE_NO_WARNINGS #include &lt;locale.h&gt; #include &lt;stdio.h&gt; #include &lt;complex&gt; #include &lt;iostream&gt; #include &lt;clocale&gt; ...

Добрый вечер
Есть бюджет 20 тысяч гривен(примерно 47315 рублей) Можете накидать варианты на данном сайте https://xcom.ua/selection/ (не реклама)...

1
1570 / 1168 / 426
Регистрация: 08.05.2012
Сообщений: 5,219
10.06.2019, 23:36
Лучший ответ Сообщение было отмечено куратор2228 как решение

Решение

import com.rey.material.widget.TextView;
TextView в коде не равен TextView в разметке, о чём и говорит ошибка.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
10.06.2019, 23:36
Помогаю со студенческими работами здесь

добрый вечер
помогите решить задачу в делфи 7,под буквой г

добрый вечер
как сделать в делфи так, чтобы было 2 щелчка мыши, мне надо как бы задать мерный участок, чтобы было при этом два клика

Добрый вечер
из за огромной проблеммы всвязи с постоянными перекидываниями на другие сайты не могу понять или увидеть как создать тему с просьбой о...

Добрый вечер, нужна помощь
Добрый вечер. Нужна помощь в небольшой сводке среды программирования для STM32. Суть в том что заканчиваю учебу, тема диплома...

Добрый вечер правильное использование this
Есть таблица и на каждое поле кнопка edit/save как мне получить значение инпута с соответствующего поля? &lt;tr&gt; ...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
Использование SDL3-callbacks вместо функции main() на Android, Desktop и WebAssembly
8Observer8 24.01.2026
Если вы откроете примеры для начинающих на официальном репозитории SDL3 в папке: examples, то вы увидите, что все примеры используют следующие четыре обязательные функции, а привычная функция main(). . .
моя боль
iceja 24.01.2026
Выложила интерполяцию кубическими сплайнами www. iceja. net REST сервисы временно не работают, только через Web. Написала за 56 рабочих часов этот сайт с нуля. При помощи perplexity. ai PRO , при. . .
Модель сукцессии микоризы
anaschu 24.01.2026
Решили писать научную статью с неким РОманом
http://iceja.net/ математические сервисы
iceja 20.01.2026
Обновила свой сайт http:/ / iceja. net/ , приделала Fast Fourier Transform экстраполяцию сигналов. Однако предсказывает далеко не каждый сигнал (см ограничения http:/ / iceja. net/ fourier/ docs ). Также. . .
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь(не выше 3-го порядка) постоянного тока с элементами R, L, C, k(ключ), U, E, J. Программа находит переходные токи и напряжения на элементах схемы классическим методом(1 и 2 з-ны. . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru