Advertisement
eranseg

Groceries DB

Nov 7th, 2019
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 14.81 KB | None | 0 0
  1. //--------------- Main Activity ------------------
  2.  
  3. import androidx.appcompat.app.AlertDialog;
  4. import androidx.appcompat.app.AppCompatActivity;
  5.  
  6. import android.content.Context;
  7. import android.content.DialogInterface;
  8. import android.graphics.Color;
  9. import android.os.Bundle;
  10. import android.util.Log;
  11. import android.view.View;
  12. import android.widget.AdapterView;
  13. import android.widget.EditText;
  14. import android.widget.LinearLayout;
  15. import android.widget.ListView;
  16. import android.widget.TextView;
  17.  
  18. import com.sdsmdg.tastytoast.TastyToast;
  19.  
  20. import java.util.List;
  21.  
  22. public class MainActivity extends AppCompatActivity {
  23.  
  24.     ListView itemsList;
  25.     EditText mask;
  26.     Context context;
  27.     DBHandler db;
  28.  
  29.     @Override
  30.     protected void onCreate(Bundle savedInstanceState) {
  31.         super.onCreate(savedInstanceState);
  32.         setContentView(R.layout.activity_main);
  33.         setPointer();
  34.     }
  35.  
  36.     private void setPointer() {
  37.         this.context = this;
  38.         db = new DBHandler(context);
  39.         mask = findViewById(R.id.uInput);
  40.         itemsList = findViewById(R.id.items_list);
  41.         getData();
  42.         findViewById(R.id.btnAddItem).setOnClickListener(new View.OnClickListener() {
  43.             @Override
  44.             public void onClick(View v) {
  45.                 addItem();
  46.             }
  47.         });
  48.         itemsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  49.             @Override
  50.             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  51.                 TextView item = (TextView) view;
  52.                 String itemToDelete = item.getText().toString();
  53.                 itemToDelete = itemToDelete.substring(itemToDelete.indexOf(' ')).trim();
  54.                 askForDeletion(itemToDelete);
  55.             }
  56.         });
  57.         findViewById(R.id.btnFindItem).setOnClickListener(new View.OnClickListener() {
  58.             @Override
  59.             public void onClick(View v) {
  60.                 cleanBackgrounds();
  61.                 EditText userInput = findViewById(R.id.uInput);
  62.                 String itemName = userInput.getText().toString();
  63.                 int index = getPositionFromAdapter(itemName);
  64.                 if(index != -1) {
  65.                     itemsList.getChildAt(index).setBackgroundColor(Color.MAGENTA);
  66.                 } else {
  67.                     TastyToast.makeText(context, "No such item", TastyToast.LENGTH_LONG, TastyToast.INFO).show();
  68.                 }
  69.             }
  70.         });
  71.     }
  72.  
  73.     private void askForDeletion(final String itemName) {
  74.         AlertDialog.Builder removeItemDialog = new AlertDialog.Builder(context);
  75.         removeItemDialog.setTitle("Are you sure you want to delete " + itemName + "?");
  76.         removeItemDialog.setPositiveButton("Remove", new DialogInterface.OnClickListener() {
  77.             @Override
  78.             public void onClick(DialogInterface dialog, int which) {
  79.                 if(itemName.isEmpty() || itemName == null) {
  80.                     return;
  81.                 }
  82.                 if(db.removeItem(itemName)) {
  83.                     TastyToast.makeText(context, "Failed to remove item", TastyToast.LENGTH_LONG, TastyToast.INFO).show();
  84.                 }
  85.                 dialog.dismiss();
  86.                 getData();
  87.             }
  88.         });
  89.         removeItemDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
  90.             @Override
  91.             public void onClick(DialogInterface dialog, int which) {
  92.                 dialog.dismiss();
  93.             }
  94.         });
  95.         removeItemDialog.show();
  96.     }
  97.  
  98.     private void addItem() {
  99.         AlertDialog.Builder addItemDialog = new AlertDialog.Builder(context);
  100.         addItemDialog.setTitle("Add Item Dialog");
  101.         final LinearLayout addItemDialogLayout = new LinearLayout(context);
  102.         addItemDialogLayout.setOrientation(LinearLayout.VERTICAL);
  103.         addItemDialogLayout.setPaddingRelative(20, 20, 20, 20);
  104.  
  105.         final EditText itemName = new EditText(context);
  106.         itemName.setPaddingRelative(20, 20, 20, 20);
  107.         final EditText amount = new EditText(context);
  108.         amount.setPaddingRelative(60, 40, 60, 40);
  109.         itemName.setHint("Enter the new item's name");
  110.         amount.setHint("Enter the new item's amount");
  111.  
  112.         addItemDialogLayout.addView(itemName);
  113.         addItemDialogLayout.addView(amount);
  114.  
  115.         addItemDialog.setView(addItemDialogLayout);
  116.         addItemDialog.setPositiveButton("Add", new DialogInterface.OnClickListener() {
  117.             @Override
  118.             public void onClick(DialogInterface dialog, int which) {
  119.                 if (itemName.getText().toString().isEmpty() ||
  120.                         amount.getText().toString().isEmpty()) {
  121.                     TastyToast.makeText(context, "Something is missing!", TastyToast.LENGTH_LONG, TastyToast.WARNING).show();
  122.                     return;
  123.                 }
  124.                 try {
  125.                     Integer.parseInt(amount.getText().toString());
  126.                 } catch(NumberFormatException nfe) {
  127.                     TastyToast.makeText(context, "Amount should be a number!", TastyToast.LENGTH_LONG, TastyToast.ERROR).show();
  128.                     return;
  129.                 }
  130.                 createItem(itemName.getText().toString(),
  131.                            Integer.parseInt(amount.getText().toString()));
  132.                 dialog.dismiss();
  133.             }
  134.         });
  135.         addItemDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
  136.             @Override
  137.             public void onClick(DialogInterface dialog, int which) {
  138.                 dialog.dismiss();
  139.             }
  140.         });
  141.         addItemDialog.show();
  142.     }
  143.  
  144.     private void createItem(String itemName, int amount) {
  145.         if(db.addItem(itemName, amount)) {
  146.             Log.e("SQL", "createItem: OK");
  147.             getData();
  148.         } else {
  149.             Log.e("SQL", "createItem: FAILURE");
  150.  
  151.         }
  152.     }
  153.  
  154.     private void getData() {
  155.         ItemAdapter adapter = new ItemAdapter(context, db.getItems());
  156.         itemsList.setAdapter(adapter);
  157.     }
  158.    
  159.     private int getPositionFromAdapter(String name) {
  160.         for(int i = 0; i < itemsList.getAdapter().getCount(); i++) {
  161.             String str = itemsList.getAdapter().getItem(i).toString();
  162.             str = str.substring(str.indexOf(' ')).trim();
  163.             if(str.matches(name)) {
  164.                 return i;
  165.             }
  166.         }
  167.         return -1;
  168.     }
  169.  
  170.     private void cleanBackgrounds() {
  171.         for(int i = 0; i < itemsList.getCount(); i++) {
  172.             itemsList.getChildAt(i).setBackgroundColor(Color.WHITE);
  173.         }
  174.     }
  175. }
  176.  
  177. //------------- ItemAdapter ---------------------
  178.  
  179. import android.content.Context;
  180. import android.view.View;
  181. import android.view.ViewGroup;
  182. import android.widget.BaseAdapter;
  183. import android.widget.TextView;
  184.  
  185. import java.util.List;
  186.  
  187. public class ItemAdapter extends BaseAdapter {
  188.  
  189.     Context context;
  190.     List<String> items;
  191.  
  192.     public ItemAdapter(Context context, List<String> items) {
  193.         this.context = context;
  194.         this.items = items;
  195.     }
  196.  
  197.     @Override
  198.     public int getCount() {
  199.         return items.size();
  200.     }
  201.  
  202.     @Override
  203.     public Object getItem(int position) {
  204.         return items.get(position);
  205.     }
  206.  
  207.     @Override
  208.     public long getItemId(int position) {
  209.         return 0;
  210.     }
  211.  
  212.     @Override
  213.     public View getView(int position, View convertView, ViewGroup parent) {
  214.         TextView iName = new TextView(context);
  215.         iName.setPadding(100, 30, 100, 30);
  216.         iName.setText(this.items.get(position));
  217.         iName.setTextSize(18);
  218.         return iName;
  219.     }
  220.  
  221.     public Object getItemByName(String str) {
  222.         for(int i = 0; i < items.size(); i++) {
  223.             if(items.get(i).matches(str)) {
  224.                 return items.get(i);
  225.             }
  226.         }
  227.         return null;
  228.     }
  229. }
  230.  
  231. //----------------- DBHandler -----------------------
  232.  
  233. import android.content.ContentValues;
  234. import android.content.Context;
  235. import android.database.Cursor;
  236. import android.database.sqlite.SQLiteDatabase;
  237. import android.database.sqlite.SQLiteOpenHelper;
  238. import android.util.Log;
  239. import android.widget.ListView;
  240. import android.widget.Toast;
  241.  
  242. import androidx.annotation.Nullable;
  243.  
  244. import com.sdsmdg.tastytoast.TastyToast;
  245.  
  246. import java.util.ArrayList;
  247. import java.util.List;
  248.  
  249. public class DBHandler extends SQLiteOpenHelper {
  250.  
  251.     //Database parameters
  252.     private static final String DATABASE_NAME = "groceriesDB.db";
  253.     private static final int DATABASE_VERSION = 1;
  254.  
  255.     //Table parameters
  256.     private static final String GROCERIES_TABLE = "groceries";
  257.     private static final String COLUMN_ITEM_ID = "item_id";
  258.     private static final String COLUMN_ITEM_NAME = "item_name";
  259.     private static final String COLUMN_ITEM_ANOUNT = "item_amount";
  260.  
  261.     private static SQLiteDatabase myDB;
  262.     Context context;
  263.  
  264.     public DBHandler(@Nullable Context context) {
  265.         super(context, DATABASE_NAME, null, DATABASE_VERSION);
  266.         this.context = context;
  267.         myDB = getWritableDatabase();
  268.     }
  269.  
  270.     @Override
  271.     public void onCreate(SQLiteDatabase db) {
  272.         String CREATE_ITEMS_TABLE = "CREATE TABLE IF NOT EXISTS " + GROCERIES_TABLE + "(" +
  273.                                     COLUMN_ITEM_ID + " INTEGER PRIMARY KEY, " +
  274.                                     COLUMN_ITEM_NAME + " TEXT UNIQUE, " +
  275.                                     COLUMN_ITEM_ANOUNT + " INTEGER)";
  276.         db.execSQL(CREATE_ITEMS_TABLE);
  277.     }
  278.  
  279.     @Override
  280.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  281.         //Do nothing
  282.     }
  283.  
  284.     public boolean addItem(String itemName, int amount) {
  285.         //Validate that the item is not in the database. If not, add the new item to the database
  286.         if(exists(itemName)) {
  287.             TastyToast.makeText(context, "Item with the same name already exists!", Toast.LENGTH_LONG, TastyToast.CONFUSING).show();
  288.         } else {
  289.             ContentValues values = new ContentValues();
  290.             values.put("item_name", itemName);
  291.             values.put("item_amount", amount);
  292.             if(myDB.insert(GROCERIES_TABLE, null, values) != -1) {
  293.                 Log.e("addItem: ", "success!!!");
  294.                 return true;
  295.             } else {
  296.                 Log.e("addItem: ", "failed!!!");
  297.             }
  298.         }
  299.         return false;
  300.     }
  301.  
  302.     protected boolean removeItem(String itemName) {
  303.         //Validate that the item is not in the database. If not, add the new item to the database
  304.         if(!exists(itemName)) {
  305.             TastyToast.makeText(context, "Item with the same does not exists!", Toast.LENGTH_LONG, TastyToast.CONFUSING).show();
  306.         } else {
  307.             if(myDB.delete(GROCERIES_TABLE, COLUMN_ITEM_NAME + " = ?", new String[] {itemName}) == -1) {
  308.                 Log.e("removeItem: ", "success!!!");
  309.                 return true;
  310.             } else {
  311.                 Log.e("removeItem: ", "failed!!!");
  312.             }
  313.         }
  314.         return false;
  315.     }
  316.  
  317.     private boolean exists(String itemName) {
  318.         //check if an item with the same name exists in the database
  319.         String query = String.format("SELECT * FROM %s WHERE %s = '%s'",
  320.                                      GROCERIES_TABLE, COLUMN_ITEM_NAME, itemName);
  321.  
  322.         Cursor cursor = myDB.rawQuery(query, null);
  323.         boolean b = cursor.moveToFirst();
  324.         cursor.close();
  325.         return b;
  326.     }
  327.  
  328.     public List<String> getItems() {
  329.         List<String> items = new ArrayList<>();
  330.         Cursor cursor = myDB.rawQuery("SELECT * FROM " + GROCERIES_TABLE, null);
  331.         if(cursor.moveToFirst()) {
  332.             while(!cursor.isAfterLast()) {
  333.                 String str = cursor.getInt(cursor.getColumnIndex(COLUMN_ITEM_ANOUNT)) + " " +
  334.                              cursor.getString(cursor.getColumnIndex(COLUMN_ITEM_NAME));
  335.                 items.add(str);
  336.                 cursor.moveToNext();
  337.             }
  338.         }
  339.         cursor.close();
  340.         return items;
  341.     }
  342. }
  343.  
  344. //------------------------- Activity_main.xml --------------------
  345.  
  346. <?xml version="1.0" encoding="utf-8"?>
  347. <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  348.     xmlns:app="http://schemas.android.com/apk/res-auto"
  349.     xmlns:tools="http://schemas.android.com/tools"
  350.     android:layout_width="match_parent"
  351.     android:layout_height="match_parent"
  352.     tools:context=".MainActivity">
  353.  
  354.     <LinearLayout
  355.         android:id="@+id/linearLayout2"
  356.         android:layout_width="0dp"
  357.         android:layout_height="0dp"
  358.         android:orientation="vertical"
  359.         android:layout_marginStart="30dp"
  360.         android:layout_marginEnd="30dp"
  361.         app:layout_constraintBottom_toBottomOf="parent"
  362.         app:layout_constraintEnd_toEndOf="parent"
  363.         app:layout_constraintStart_toStartOf="parent"
  364.         app:layout_constraintTop_toTopOf="parent">
  365.  
  366.         <TextView
  367.             android:id="@+id/title"
  368.             android:layout_width="match_parent"
  369.             android:layout_height="wrap_content"
  370.             android:layout_margin="30dp"
  371.             android:gravity="center"
  372.             android:text="@string/title"
  373.             android:textColor="@color/colorPrimary"
  374.             android:textSize="32sp" />
  375.  
  376.         <LinearLayout
  377.             android:layout_width="match_parent"
  378.             android:layout_height="wrap_content"
  379.             android:orientation="horizontal">
  380.  
  381.             <Button
  382.                 android:id="@+id/btnFindItem"
  383.                 style="@style/Widget.AppCompat.Button.Colored"
  384.                 android:layout_width="wrap_content"
  385.                 android:layout_height="wrap_content"
  386.                 android:layout_margin="10dp"
  387.                 android:text="@string/find" />
  388.  
  389.             <EditText
  390.                 android:id="@+id/uInput"
  391.                 android:layout_width="match_parent"
  392.                 android:layout_height="match_parent"
  393.                 android:layout_marginEnd="20dp"
  394.                 android:autofillHints=""
  395.                 android:hint="@string/item_name_here"
  396.                 android:inputType="text" />
  397.         </LinearLayout>
  398.  
  399.         <ListView
  400.             style="@style/Widget.AppCompat.ListView"
  401.             android:id="@+id/items_list"
  402.             android:layout_width="match_parent"
  403.             android:layout_height="0dp"
  404.             android:layout_weight="1" />
  405.  
  406.         <Button
  407.             android:id="@+id/btnAddItem"
  408.             style="@style/Widget.AppCompat.Button.ButtonBar.AlertDialog"
  409.             android:layout_width="match_parent"
  410.             android:layout_height="wrap_content"
  411.             android:layout_margin="10dp"
  412.             android:text="@string/add_item"
  413.             android:textSize="18sp" />
  414.     </LinearLayout>
  415. </androidx.constraintlayout.widget.ConstraintLayout>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement