Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //--------------- Main Activity ------------------
- import androidx.appcompat.app.AlertDialog;
- import androidx.appcompat.app.AppCompatActivity;
- import android.content.Context;
- import android.content.DialogInterface;
- import android.graphics.Color;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.AdapterView;
- import android.widget.EditText;
- import android.widget.LinearLayout;
- import android.widget.ListView;
- import android.widget.TextView;
- import com.sdsmdg.tastytoast.TastyToast;
- import java.util.List;
- public class MainActivity extends AppCompatActivity {
- ListView itemsList;
- EditText mask;
- Context context;
- DBHandler db;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- setPointer();
- }
- private void setPointer() {
- this.context = this;
- db = new DBHandler(context);
- mask = findViewById(R.id.uInput);
- itemsList = findViewById(R.id.items_list);
- getData();
- findViewById(R.id.btnAddItem).setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- addItem();
- }
- });
- itemsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
- TextView item = (TextView) view;
- String itemToDelete = item.getText().toString();
- itemToDelete = itemToDelete.substring(itemToDelete.indexOf(' ')).trim();
- askForDeletion(itemToDelete);
- }
- });
- findViewById(R.id.btnFindItem).setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- cleanBackgrounds();
- EditText userInput = findViewById(R.id.uInput);
- String itemName = userInput.getText().toString();
- int index = getPositionFromAdapter(itemName);
- if(index != -1) {
- itemsList.getChildAt(index).setBackgroundColor(Color.MAGENTA);
- } else {
- TastyToast.makeText(context, "No such item", TastyToast.LENGTH_LONG, TastyToast.INFO).show();
- }
- }
- });
- }
- private void askForDeletion(final String itemName) {
- AlertDialog.Builder removeItemDialog = new AlertDialog.Builder(context);
- removeItemDialog.setTitle("Are you sure you want to delete " + itemName + "?");
- removeItemDialog.setPositiveButton("Remove", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- if(itemName.isEmpty() || itemName == null) {
- return;
- }
- if(db.removeItem(itemName)) {
- TastyToast.makeText(context, "Failed to remove item", TastyToast.LENGTH_LONG, TastyToast.INFO).show();
- }
- dialog.dismiss();
- getData();
- }
- });
- removeItemDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- }
- });
- removeItemDialog.show();
- }
- private void addItem() {
- AlertDialog.Builder addItemDialog = new AlertDialog.Builder(context);
- addItemDialog.setTitle("Add Item Dialog");
- final LinearLayout addItemDialogLayout = new LinearLayout(context);
- addItemDialogLayout.setOrientation(LinearLayout.VERTICAL);
- addItemDialogLayout.setPaddingRelative(20, 20, 20, 20);
- final EditText itemName = new EditText(context);
- itemName.setPaddingRelative(20, 20, 20, 20);
- final EditText amount = new EditText(context);
- amount.setPaddingRelative(60, 40, 60, 40);
- itemName.setHint("Enter the new item's name");
- amount.setHint("Enter the new item's amount");
- addItemDialogLayout.addView(itemName);
- addItemDialogLayout.addView(amount);
- addItemDialog.setView(addItemDialogLayout);
- addItemDialog.setPositiveButton("Add", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- if (itemName.getText().toString().isEmpty() ||
- amount.getText().toString().isEmpty()) {
- TastyToast.makeText(context, "Something is missing!", TastyToast.LENGTH_LONG, TastyToast.WARNING).show();
- return;
- }
- try {
- Integer.parseInt(amount.getText().toString());
- } catch(NumberFormatException nfe) {
- TastyToast.makeText(context, "Amount should be a number!", TastyToast.LENGTH_LONG, TastyToast.ERROR).show();
- return;
- }
- createItem(itemName.getText().toString(),
- Integer.parseInt(amount.getText().toString()));
- dialog.dismiss();
- }
- });
- addItemDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- }
- });
- addItemDialog.show();
- }
- private void createItem(String itemName, int amount) {
- if(db.addItem(itemName, amount)) {
- Log.e("SQL", "createItem: OK");
- getData();
- } else {
- Log.e("SQL", "createItem: FAILURE");
- }
- }
- private void getData() {
- ItemAdapter adapter = new ItemAdapter(context, db.getItems());
- itemsList.setAdapter(adapter);
- }
- private int getPositionFromAdapter(String name) {
- for(int i = 0; i < itemsList.getAdapter().getCount(); i++) {
- String str = itemsList.getAdapter().getItem(i).toString();
- str = str.substring(str.indexOf(' ')).trim();
- if(str.matches(name)) {
- return i;
- }
- }
- return -1;
- }
- private void cleanBackgrounds() {
- for(int i = 0; i < itemsList.getCount(); i++) {
- itemsList.getChildAt(i).setBackgroundColor(Color.WHITE);
- }
- }
- }
- //------------- ItemAdapter ---------------------
- import android.content.Context;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.BaseAdapter;
- import android.widget.TextView;
- import java.util.List;
- public class ItemAdapter extends BaseAdapter {
- Context context;
- List<String> items;
- public ItemAdapter(Context context, List<String> items) {
- this.context = context;
- this.items = items;
- }
- @Override
- public int getCount() {
- return items.size();
- }
- @Override
- public Object getItem(int position) {
- return items.get(position);
- }
- @Override
- public long getItemId(int position) {
- return 0;
- }
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- TextView iName = new TextView(context);
- iName.setPadding(100, 30, 100, 30);
- iName.setText(this.items.get(position));
- iName.setTextSize(18);
- return iName;
- }
- public Object getItemByName(String str) {
- for(int i = 0; i < items.size(); i++) {
- if(items.get(i).matches(str)) {
- return items.get(i);
- }
- }
- return null;
- }
- }
- //----------------- DBHandler -----------------------
- import android.content.ContentValues;
- import android.content.Context;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteOpenHelper;
- import android.util.Log;
- import android.widget.ListView;
- import android.widget.Toast;
- import androidx.annotation.Nullable;
- import com.sdsmdg.tastytoast.TastyToast;
- import java.util.ArrayList;
- import java.util.List;
- public class DBHandler extends SQLiteOpenHelper {
- //Database parameters
- private static final String DATABASE_NAME = "groceriesDB.db";
- private static final int DATABASE_VERSION = 1;
- //Table parameters
- private static final String GROCERIES_TABLE = "groceries";
- private static final String COLUMN_ITEM_ID = "item_id";
- private static final String COLUMN_ITEM_NAME = "item_name";
- private static final String COLUMN_ITEM_ANOUNT = "item_amount";
- private static SQLiteDatabase myDB;
- Context context;
- public DBHandler(@Nullable Context context) {
- super(context, DATABASE_NAME, null, DATABASE_VERSION);
- this.context = context;
- myDB = getWritableDatabase();
- }
- @Override
- public void onCreate(SQLiteDatabase db) {
- String CREATE_ITEMS_TABLE = "CREATE TABLE IF NOT EXISTS " + GROCERIES_TABLE + "(" +
- COLUMN_ITEM_ID + " INTEGER PRIMARY KEY, " +
- COLUMN_ITEM_NAME + " TEXT UNIQUE, " +
- COLUMN_ITEM_ANOUNT + " INTEGER)";
- db.execSQL(CREATE_ITEMS_TABLE);
- }
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- //Do nothing
- }
- public boolean addItem(String itemName, int amount) {
- //Validate that the item is not in the database. If not, add the new item to the database
- if(exists(itemName)) {
- TastyToast.makeText(context, "Item with the same name already exists!", Toast.LENGTH_LONG, TastyToast.CONFUSING).show();
- } else {
- ContentValues values = new ContentValues();
- values.put("item_name", itemName);
- values.put("item_amount", amount);
- if(myDB.insert(GROCERIES_TABLE, null, values) != -1) {
- Log.e("addItem: ", "success!!!");
- return true;
- } else {
- Log.e("addItem: ", "failed!!!");
- }
- }
- return false;
- }
- protected boolean removeItem(String itemName) {
- //Validate that the item is not in the database. If not, add the new item to the database
- if(!exists(itemName)) {
- TastyToast.makeText(context, "Item with the same does not exists!", Toast.LENGTH_LONG, TastyToast.CONFUSING).show();
- } else {
- if(myDB.delete(GROCERIES_TABLE, COLUMN_ITEM_NAME + " = ?", new String[] {itemName}) == -1) {
- Log.e("removeItem: ", "success!!!");
- return true;
- } else {
- Log.e("removeItem: ", "failed!!!");
- }
- }
- return false;
- }
- private boolean exists(String itemName) {
- //check if an item with the same name exists in the database
- String query = String.format("SELECT * FROM %s WHERE %s = '%s'",
- GROCERIES_TABLE, COLUMN_ITEM_NAME, itemName);
- Cursor cursor = myDB.rawQuery(query, null);
- boolean b = cursor.moveToFirst();
- cursor.close();
- return b;
- }
- public List<String> getItems() {
- List<String> items = new ArrayList<>();
- Cursor cursor = myDB.rawQuery("SELECT * FROM " + GROCERIES_TABLE, null);
- if(cursor.moveToFirst()) {
- while(!cursor.isAfterLast()) {
- String str = cursor.getInt(cursor.getColumnIndex(COLUMN_ITEM_ANOUNT)) + " " +
- cursor.getString(cursor.getColumnIndex(COLUMN_ITEM_NAME));
- items.add(str);
- cursor.moveToNext();
- }
- }
- cursor.close();
- return items;
- }
- }
- //------------------------- Activity_main.xml --------------------
- <?xml version="1.0" encoding="utf-8"?>
- <androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity">
- <LinearLayout
- android:id="@+id/linearLayout2"
- android:layout_width="0dp"
- android:layout_height="0dp"
- android:orientation="vertical"
- android:layout_marginStart="30dp"
- android:layout_marginEnd="30dp"
- app:layout_constraintBottom_toBottomOf="parent"
- app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toTopOf="parent">
- <TextView
- android:id="@+id/title"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_margin="30dp"
- android:gravity="center"
- android:text="@string/title"
- android:textColor="@color/colorPrimary"
- android:textSize="32sp" />
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:orientation="horizontal">
- <Button
- android:id="@+id/btnFindItem"
- style="@style/Widget.AppCompat.Button.Colored"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_margin="10dp"
- android:text="@string/find" />
- <EditText
- android:id="@+id/uInput"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:layout_marginEnd="20dp"
- android:autofillHints=""
- android:hint="@string/item_name_here"
- android:inputType="text" />
- </LinearLayout>
- <ListView
- style="@style/Widget.AppCompat.ListView"
- android:id="@+id/items_list"
- android:layout_width="match_parent"
- android:layout_height="0dp"
- android:layout_weight="1" />
- <Button
- android:id="@+id/btnAddItem"
- style="@style/Widget.AppCompat.Button.ButtonBar.AlertDialog"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_margin="10dp"
- android:text="@string/add_item"
- android:textSize="18sp" />
- </LinearLayout>
- </androidx.constraintlayout.widget.ConstraintLayout>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement