-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathMainActivity.java
81 lines (69 loc) · 2.88 KB
/
MainActivity.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
package com.example.productapp;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDb;
EditText editProductName, editQuantity, editPrice;
Button btnAddProduct, btnViewProducts;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DatabaseHelper(this);
editProductName = findViewById(R.id.editText_productName);
editQuantity = findViewById(R.id.editText_quantity);
editPrice = findViewById(R.id.editText_price);
btnAddProduct = findViewById(R.id.button_add);
btnViewProducts = findViewById(R.id.button_view);
addProduct();
viewAllProducts();
}
public void addProduct() {
btnAddProduct.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isInserted = myDb.insertData(editProductName.getText().toString(),
editQuantity.getText().toString(),
editPrice.getText().toString());
if (isInserted) {
Toast.makeText(MainActivity.this, "Produto Inserido", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Erro ao Inserir Produto", Toast.LENGTH_LONG).show();
}
}
});
}
public void viewAllProducts() {
btnViewProducts.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Cursor res = myDb.getAllData();
if (res.getCount() == 0) {
showMessage("Erro", "Nenhum Produto Encontrado");
return;
}
StringBuilder buffer = new StringBuilder();
while (res.moveToNext()) {
buffer.append("ID: ").append(res.getString(0)).append("\n");
buffer.append("Nome: ").append(res.getString(1)).append("\n");
buffer.append("Quantidade: ").append(res.getString(2)).append("\n");
buffer.append("Preço: ").append(res.getString(3)).append("\n\n");
}
showMessage("Lista de Produtos", buffer.toString());
}
});
}
public void showMessage(String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}