Skip to content

Instantly share code, notes, and snippets.

@asafstr2
Created July 9, 2018 20:58
Show Gist options
  • Save asafstr2/1e1bdc034654b0c78859e3da8151fce5 to your computer and use it in GitHub Desktop.
Save asafstr2/1e1bdc034654b0c78859e3da8151fce5 to your computer and use it in GitHub Desktop.
inventory app
package com.example.android.inventory2;
import android.app.LoaderManager;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.example.android.inventory2.data.StoreContract.ProductEntry;
import com.example.android.inventory2.data.StoreDbHelper;
public class CatalogActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
private static final int PRODUCT_LOADER = 0;
StoreCursorAdapter mCursorAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalog);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(CatalogActivity.this, EditorActivity.class);
startActivity(intent);
}
});
ListView petListView = findViewById(R.id.list);
View emptyView = findViewById(R.id.empty_view);
petListView.setEmptyView(emptyView);
mCursorAdapter = new StoreCursorAdapter(this, null);
petListView.setAdapter(mCursorAdapter);
petListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent intent = new Intent(CatalogActivity.this, EditorActivity.class);
Uri currentproductUri = ContentUris.withAppendedId(ProductEntry.CONTENT_URI, id);
intent.setData(currentproductUri);
startActivity(intent);
}
});
getLoaderManager().initLoader(PRODUCT_LOADER, null, this);
SwipeRefreshLayout swipe = findViewById(R.id.swiperefresh);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
SwipeRefreshLayout swipe = findViewById(R.id.swiperefresh);
getLoaderManager().initLoader(PRODUCT_LOADER, null, CatalogActivity.this);
Toast.makeText(getApplicationContext(), R.string.refreshed_successfully, Toast.LENGTH_LONG).show();
swipe.setRefreshing(false);
}
}
);
}
private void insertPet() {
ContentValues values = new ContentValues();
values.put(ProductEntry.COLUMN_PRODUCT_NAME, "earphones");
values.put(ProductEntry.COLUMN_PRICE, 10);
values.put(ProductEntry.COLUMN_SUPPLIER_NAME, "JBL");
values.put(ProductEntry.COLUMN_SUPPLIER_PHONE_NUMBER, "0549012568");
values.put(ProductEntry.COLUMN_QUANTITY, 7);
getContentResolver().insert(ProductEntry.CONTENT_URI, values);
}
private void deleteAllProducts() {
StoreDbHelper mDbHelper;
mDbHelper = new StoreDbHelper(this);
mDbHelper.delete();
mCursorAdapter.swapCursor(null);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_catalog, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_insert_dummy_data:
insertPet();
return true;
case R.id.action_delete_all_entries:
deleteAllProducts();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = {
ProductEntry._ID,
ProductEntry.COLUMN_PRODUCT_NAME,
ProductEntry.COLUMN_SUPPLIER_NAME,
ProductEntry.COLUMN_QUANTITY,
ProductEntry.COLUMN_PRICE,
ProductEntry.COLUMN_SUPPLIER_PHONE_NUMBER
};
return new CursorLoader(this, // Parent activity context
ProductEntry.CONTENT_URI, // Provider content URI to query
projection, // Columns to include in the resulting Cursor
null, // No selection clause
null, // No selection arguments
null); // Default sort order
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mCursorAdapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mCursorAdapter.swapCursor(null);
}
}
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.inventory2.data;
import android.content.ContentResolver;
import android.net.Uri;
import android.provider.BaseColumns;
public final class StoreContract {
private StoreContract() {
}
public static final class ProductEntry implements BaseColumns {
public static final String CONTENT_AUTHORITY = "com.example.android.inventory2";
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
public static final String PATH_STORE = "inventory";
public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, PATH_STORE);
public static final String CONTENT_LIST_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_STORE;
public static final String CONTENT_ITEM_TYPE =
ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_STORE;
public final static String TABLE_NAME = "inventory";
public final static String _ID = BaseColumns._ID;
public final static String COLUMN_PRODUCT_NAME = "product_name";
public final static String COLUMN_SUPPLIER_NAME = "supplier_name";
public final static String COLUMN_SUPPLIER_PHONE_NUMBER = "supplier_phone_number";
public final static String COLUMN_QUANTITY = "quantity";
public final static String COLUMN_PRICE = "price";
public static final String DELETE = " DROP TABLE " + TABLE_NAME;
}
}
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.inventory2.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.android.inventory2.data.StoreContract.ProductEntry;
public class StoreDbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "store.db";
private static final int DATABASE_VERSION = 1;
public StoreDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String SQL_CREATE_INVENTORY_TABLE = "CREATE TABLE " + ProductEntry.TABLE_NAME + " ("
+ ProductEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ ProductEntry.COLUMN_PRODUCT_NAME + " TEXT NOT NULL, "
+ ProductEntry.COLUMN_SUPPLIER_NAME + " TEXT NOT NULL, "
+ ProductEntry.COLUMN_QUANTITY + " INTEGER NOT NULL, "
+ ProductEntry.COLUMN_PRICE + " INTEGER NOT NULL, "
+ ProductEntry.COLUMN_SUPPLIER_PHONE_NUMBER + " TEXT NOT NULL );";
db.execSQL(SQL_CREATE_INVENTORY_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(ProductEntry.DELETE);
onCreate(db);
}
public void delete() {
SQLiteDatabase db = getWritableDatabase();
db.execSQL(ProductEntry.DELETE);
onCreate(db);
}
}
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.inventory2.data;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.example.android.inventory2.R;
import com.example.android.inventory2.data.StoreContract.ProductEntry;
import java.util.Objects;
/**
* {@link ContentProvider} for Pets app.
*/
public class StoreProvider extends ContentProvider {
public static final String LOG_TAG = StoreProvider.class.getSimpleName();
private static final int INVENTORY = 100;
private static final int INVENTORY_ID = 101;
private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
private StoreDbHelper mDbHelper;
static {
sUriMatcher.addURI(StoreContract.ProductEntry.CONTENT_AUTHORITY, StoreContract.ProductEntry.PATH_STORE, INVENTORY);
sUriMatcher.addURI(StoreContract.ProductEntry.CONTENT_AUTHORITY, StoreContract.ProductEntry.PATH_STORE + "/#", INVENTORY_ID);
}
@Override
public boolean onCreate() {
mDbHelper = new StoreDbHelper(getContext());
return true;
}
//gets URI ,projection(returning list of all column chosen in it), selection+selection args for returning specifeid raw,null,null,null) returning courser of the data specified if URI contains selection of ID will auto qurry for it
@Override
public Cursor query(@NonNull Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteDatabase database = mDbHelper.getReadableDatabase();
Cursor cursor;
int match = sUriMatcher.match(uri);
switch (match) {
case INVENTORY:
cursor = database.query(StoreContract.ProductEntry.TABLE_NAME, projection, selection, selectionArgs,
null, null, sortOrder);
break;
case INVENTORY_ID:
selection = StoreContract.ProductEntry._ID + "=?";
selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) };
cursor = database.query(ProductEntry.TABLE_NAME, projection, selection, selectionArgs,
null, null, sortOrder);
break;
default:
throw new IllegalArgumentException("Cannot query unknown URI " + uri);
}
cursor.setNotificationUri(Objects.requireNonNull(getContext()).getContentResolver(), uri);
return cursor;
}
//since new input no need to check for ID in selection+selection args
@Override
public Uri insert(@NonNull Uri uri, ContentValues contentValues) {
final int match = sUriMatcher.match(uri);
switch (match) {
case INVENTORY:
return insertInventory(uri, contentValues);
default:
throw new IllegalArgumentException("Insertion is not supported for " + uri);
}
}
private Uri insertInventory(Uri uri, ContentValues values) {
String product_name = values.getAsString(StoreContract.ProductEntry.COLUMN_PRODUCT_NAME);
if (product_name == null|| TextUtils.isEmpty(product_name)) {
Toast.makeText(getContext(), R.string.name_is_required, Toast.LENGTH_SHORT).show();
return null;
}
String supplier_name = values.getAsString(ProductEntry.COLUMN_SUPPLIER_NAME);
if (supplier_name == null|| TextUtils.isEmpty(supplier_name)) {
Toast.makeText(getContext(), R.string.supplier_is_required, Toast.LENGTH_SHORT).show();
return null; }
Integer supplier_phone_number = values.getAsInteger(StoreContract.ProductEntry.COLUMN_SUPPLIER_PHONE_NUMBER);
if (supplier_phone_number == null ) {
Toast.makeText(getContext(), R.string.phone_is_required, Toast.LENGTH_SHORT).show();
return null; }
Integer quantity = values.getAsInteger(StoreContract.ProductEntry.COLUMN_QUANTITY);
if (quantity != null && quantity < 0) {
Toast.makeText(getContext(), R.string.requires_valid_quantity, Toast.LENGTH_SHORT).show();
return null;
}
Integer price = values.getAsInteger(ProductEntry.COLUMN_PRICE);
if (price != null && price < 0) {
Toast.makeText(getContext(), R.string.requires_valid_price, Toast.LENGTH_SHORT).show();
return null;
}
SQLiteDatabase database = mDbHelper.getWritableDatabase();
long id = database.insert(StoreContract.ProductEntry.TABLE_NAME, null, values);
if (id == -1) {
Log.e(LOG_TAG, "Failed to insert row for " + uri);
return null;
}
Objects.requireNonNull(getContext()).getContentResolver().notifyChange(uri, null);
return ContentUris.withAppendedId(uri, id);
}
@Override
public int update(@NonNull Uri uri, ContentValues contentValues, String selection, String[] selectionArgs) {
Log.d("TAG1", " Store provider URI : "+uri.toString()+"\n");
final int match = sUriMatcher.match(uri);
switch (match) {
case INVENTORY:
return updateProduct(uri, contentValues, selection, selectionArgs);
case INVENTORY_ID:
selection = StoreContract.ProductEntry._ID + "=?";
selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) };
return updateProduct(uri, contentValues, selection, selectionArgs);
default:
throw new IllegalArgumentException("Update is not supported for " + uri);
}
}
private int updateProduct(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
if (values.containsKey(StoreContract.ProductEntry.COLUMN_PRODUCT_NAME)) {
String name = values.getAsString(StoreContract.ProductEntry.COLUMN_PRODUCT_NAME);
if (name == null) {
throw new IllegalArgumentException(" requires a name");
}
}
if (values.containsKey(ProductEntry.COLUMN_SUPPLIER_NAME)) {
String supllierName = values.getAsString(ProductEntry.COLUMN_SUPPLIER_NAME);
if (supllierName == null ) {
throw new IllegalArgumentException(" requires valid phone number");
}
}
if (values.containsKey(StoreContract.ProductEntry.COLUMN_QUANTITY)) {
Integer quantity = values.getAsInteger(StoreContract.ProductEntry.COLUMN_QUANTITY);
Log.d("TAG1", " Store provider quantity : "+quantity.toString()+"\n");
if (quantity < 0) {
throw new IllegalArgumentException("requires valid quantity");
}
}
if (values.containsKey(ProductEntry.COLUMN_PRICE)) {
Integer price = values.getAsInteger(ProductEntry.COLUMN_PRICE);
if (price != null && price < 0) {
throw new IllegalArgumentException("requires valid quantity");
}
}
if (values.containsKey(ProductEntry.COLUMN_SUPPLIER_PHONE_NUMBER)) {
Integer supllierPhoneNumber = values.getAsInteger(ProductEntry.COLUMN_SUPPLIER_PHONE_NUMBER);
if (supllierPhoneNumber != null && supllierPhoneNumber < 0) {
throw new IllegalArgumentException("requires valid quantity");
}
}
if (values.size() == 0) {
return 0;
}
SQLiteDatabase database = mDbHelper.getWritableDatabase();
database.update(StoreContract.ProductEntry.TABLE_NAME, values, selection, selectionArgs);
if (values.size() != 0) {
Objects.requireNonNull(getContext()).getContentResolver().notifyChange(uri, null);
}
return values.size();
}
@Override
public int delete(@NonNull Uri uri, String selection, String[] selectionArgs) {
// Get writeable database
SQLiteDatabase database = mDbHelper.getWritableDatabase();
// Track the number of rows that were deleted
int rowsDeleted;
final int match = sUriMatcher.match(uri);
switch (match) {
case INVENTORY:
// Delete all rows that match the selection and selection args
rowsDeleted = database.delete(StoreContract.ProductEntry.TABLE_NAME, selection, selectionArgs);
break;
case INVENTORY_ID:
// Delete a single row given by the ID in the URI
selection = StoreContract.ProductEntry._ID + "=?";
selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) };
rowsDeleted = database.delete(StoreContract.ProductEntry.TABLE_NAME, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("Deletion is not supported for " + uri);
}
// If 1 or more rows were deleted, then notify all listeners that the data at the
// given URI has changed
if (rowsDeleted != 0) {
Objects.requireNonNull(getContext()).getContentResolver().notifyChange(uri, null);
}
// Return the number of rows deleted
return rowsDeleted;
}
@Override
public String getType(@NonNull Uri uri) {
final int match = sUriMatcher.match(uri);
switch (match) {
case INVENTORY:
return StoreContract.ProductEntry.CONTENT_LIST_TYPE;
case INVENTORY_ID:
return ProductEntry.CONTENT_ITEM_TYPE;
default:
throw new IllegalStateException("Unknown URI " + uri + " with match " + match);
}
}
}
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.inventory2;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.LoaderManager;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.example.android.inventory2.data.StoreContract;
import com.example.android.inventory2.data.StoreContract.ProductEntry;
public class EditorActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
private static final int EXISTING_PRODUCT_LOADER = 0;
private Uri mCurrentProductUri;
private EditText mProductNameEditText;
private EditText mSupplierNmaeEditText;
private EditText mQuantityText;
private EditText mPrice;
private EditText mSupllierPhonenumber;
private boolean mProductHasChanged = false;
private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
mProductHasChanged = true;
return false;
}
};
@SuppressLint("ClickableViewAccessibility")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);
Intent intent = getIntent();
mCurrentProductUri = intent.getData();
if (mCurrentProductUri == null) {
setTitle(getString(R.string.editor_activity_title_new_item));
invalidateOptionsMenu();
} else {
setTitle(getString(R.string.editor_activity_title_edit_product));
getLoaderManager().initLoader(EXISTING_PRODUCT_LOADER, null, this);
}
mProductNameEditText = findViewById(R.id.product_name_edit);
mSupplierNmaeEditText = findViewById(R.id.supplier_name_edit);
mQuantityText = findViewById(R.id.quantity_edit);
mPrice = findViewById(R.id.price_edit);
mSupllierPhonenumber = findViewById(R.id.supplier_phone_number_edit);
final Button increse = findViewById(R.id.increse);
final ImageButton dialer = findViewById(R.id.supplier_phone_number_button);
final Button decrese = findViewById(R.id.decrese);
dialer.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialContactPhone();
}
});
increse.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
increase();
}
});
decrese.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
decrese();
}
});
mProductNameEditText.setOnTouchListener(mTouchListener);
mSupplierNmaeEditText.setOnTouchListener(mTouchListener);
mQuantityText.setOnTouchListener(mTouchListener);
mPrice.setOnTouchListener(mTouchListener);
mSupllierPhonenumber.setOnTouchListener(mTouchListener);
increse.setOnTouchListener(mTouchListener);
decrese.setOnTouchListener(mTouchListener);
}
private void saveProduct() {
String productName = mProductNameEditText.getText().toString().trim();
String supplierName = mSupplierNmaeEditText.getText().toString().trim();
String quantity = mQuantityText.getText().toString().trim();
String price = mPrice.getText().toString().trim();
String supplierPhoneNumber = mSupllierPhonenumber.getText().toString().trim();
if (mCurrentProductUri == null && TextUtils.isEmpty(productName) && TextUtils.isEmpty(supplierName) &&
TextUtils.isEmpty(quantity) && TextUtils.isEmpty(price) && TextUtils.isEmpty(supplierPhoneNumber)) {
return;
}
ContentValues values = new ContentValues();
values.put(StoreContract.ProductEntry.COLUMN_PRODUCT_NAME, productName);
values.put(StoreContract.ProductEntry.COLUMN_SUPPLIER_NAME, supplierName);
values.put(ProductEntry.COLUMN_QUANTITY, quantity);
values.put(ProductEntry.COLUMN_PRICE, price);
values.put(ProductEntry.COLUMN_SUPPLIER_PHONE_NUMBER, supplierPhoneNumber);
if (mCurrentProductUri == null) {
Uri newUri = getContentResolver().insert(ProductEntry.CONTENT_URI, values);
if (newUri == null) {
Toast.makeText(this, getString(R.string.editor_insert_product_failed),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, getString(R.string.editor_insert_product_successful),
Toast.LENGTH_SHORT).show();
}
} else {
int rowsAffected = getContentResolver().update(mCurrentProductUri, values, null, null);
if (rowsAffected == 0) {
Toast.makeText(this, getString(R.string.editor_update_product_failed),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, getString(R.string.editor_update_product_successful),
Toast.LENGTH_SHORT).show();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_editor, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (mCurrentProductUri == null) {
MenuItem menuItem = menu.findItem(R.id.action_delete);
menuItem.setVisible(false);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
saveProduct();
finish();
return true;
case R.id.action_delete:
showDeleteConfirmationDialog();
return true;
case android.R.id.home:
if (!mProductHasChanged) {
NavUtils.navigateUpFromSameTask(EditorActivity.this);
return true;
}
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
NavUtils.navigateUpFromSameTask(EditorActivity.this);
}
};
showUnsavedChangesDialog(discardButtonClickListener);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
if (!mProductHasChanged) {
super.onBackPressed();
return;
}
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
};
showUnsavedChangesDialog(discardButtonClickListener);
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this, mCurrentProductUri, null, null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (cursor == null || cursor.getCount() < 1) {
return;
}
if (cursor.moveToFirst()) {
int productNameColumnIndex = cursor.getColumnIndex(ProductEntry.COLUMN_PRODUCT_NAME);
int supllierNameColumnIndex = cursor.getColumnIndex(ProductEntry.COLUMN_SUPPLIER_NAME);
int quantityColumnIndex = cursor.getColumnIndex(ProductEntry.COLUMN_QUANTITY);
int priceColumnIndex = cursor.getColumnIndex(ProductEntry.COLUMN_PRICE);
int supplierPhonenumberColumnIndex = cursor.getColumnIndex(ProductEntry.COLUMN_SUPPLIER_PHONE_NUMBER);
String productName = cursor.getString(productNameColumnIndex);
String supplierName = cursor.getString(supllierNameColumnIndex);
String quantity = cursor.getString(quantityColumnIndex);
String price = cursor.getString(priceColumnIndex);
String supplierPhoneNumber = cursor.getString(supplierPhonenumberColumnIndex);
mProductNameEditText.setText(productName);
mSupplierNmaeEditText.setText(supplierName);
mQuantityText.setText(quantity);
mPrice.setText(price);
mSupllierPhonenumber.setText(supplierPhoneNumber);
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mProductNameEditText.setText("");
mSupplierNmaeEditText.setText("");
mQuantityText.setText("");
mPrice.setText("");
mSupllierPhonenumber.setText("");
}
private void showUnsavedChangesDialog(
DialogInterface.OnClickListener discardButtonClickListener) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.unsaved_changes_dialog_msg);
builder.setPositiveButton(R.string.discard, discardButtonClickListener);
builder.setNegativeButton(R.string.keep_editing, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (dialog != null) {
dialog.dismiss();
}
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void showDeleteConfirmationDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.delete_dialog_msg);
builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
deleteProduct();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (dialog != null) {
dialog.dismiss();
}
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void deleteProduct() {
if (mCurrentProductUri != null) {
int rowsDeleted = getContentResolver().delete(mCurrentProductUri, null, null);
if (rowsDeleted == 0) {
Toast.makeText(this, getString(R.string.editor_delete_product_failed),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, getString(R.string.editor_delete_product_successful),
Toast.LENGTH_SHORT).show();
}
}
finish();
}
public void dialContactPhone() {
String supplierPhoneNumber = mSupllierPhonenumber.getText().toString().trim();
startActivity(new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", supplierPhoneNumber, null)));
}
@SuppressLint("SetTextI18n")
public void increase() {
String quantity2 = mQuantityText.getText().toString();
if (!TextUtils.isEmpty(quantity2)) {
int quantity = Integer.parseInt(mQuantityText.getText().toString());
quantity++;
mQuantityText.setText(Integer.toString(quantity));
} else {
Toast.makeText(this, getString(R.string.plaese_enter_value), Toast.LENGTH_SHORT).show();
}
}
@SuppressLint("SetTextI18n")
public void decrese() {
String quantity2 = mQuantityText.getText().toString();
if (!TextUtils.isEmpty(quantity2)) {
int quantity = Integer.parseInt(mQuantityText.getText().toString());
if (quantity > 0 && mQuantityText != null) {
quantity--;
mQuantityText.setText(Integer.toString(quantity));
} else {
Toast.makeText(this, getString(R.string.cant_be_under_0), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, getString(R.string.plaese_enter_value), Toast.LENGTH_SHORT).show();
}
}
}
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.inventory2;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.inventory2.data.StoreContract;
public class StoreCursorAdapter extends CursorAdapter {
StoreCursorAdapter(Context context, Cursor c) {
super(context, c, 0 );
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
}
@Override
public void bindView(View view, final Context context, Cursor cursor) {
TextView productNameTextView = view.findViewById(R.id.product_name);
TextView supplierNameTextView = view.findViewById(R.id.supplier_name);
TextView supplierPhoneNumberTextView = view.findViewById(R.id.supplier_phone_number);
TextView quantityTextView = view.findViewById(R.id.quantity);
TextView priceTextView = view.findViewById(R.id.price);
final Button sale = view.findViewById(R.id.sale);
int storeProductColumnIndex = cursor.getColumnIndex(StoreContract.ProductEntry.COLUMN_PRODUCT_NAME);
int supplierNameColumnIndex = cursor.getColumnIndex(StoreContract.ProductEntry.COLUMN_SUPPLIER_NAME);
int supplierPhoneNumberColumnIndex = cursor.getColumnIndex(StoreContract.ProductEntry.COLUMN_SUPPLIER_PHONE_NUMBER);
final int quantityColumnIndex = cursor.getColumnIndex(StoreContract.ProductEntry.COLUMN_QUANTITY);
int priceColumnIndex = cursor.getColumnIndex(StoreContract.ProductEntry.COLUMN_PRICE);
int idColumnIndex = cursor.getColumnIndex(StoreContract.ProductEntry._ID);
String currentProductName = cursor.getString(storeProductColumnIndex);
String currentSupplierName = cursor.getString(supplierNameColumnIndex);
String currentSupplierPhoneNumber = cursor.getString(supplierPhoneNumberColumnIndex);
final int currentQuantity = cursor.getInt(quantityColumnIndex);
String currentprice = cursor.getString(priceColumnIndex);
final int currentId = cursor.getInt(idColumnIndex);
productNameTextView.setText(currentProductName);
supplierNameTextView.setText(currentSupplierName);
supplierPhoneNumberTextView.setText(currentSupplierPhoneNumber);
quantityTextView.setText(Integer.toString(currentQuantity));
priceTextView.setText(currentprice);
sale.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (currentQuantity > 0) {
final Uri mCurrentProductUri = ContentUris.withAppendedId(StoreContract.ProductEntry.CONTENT_URI, currentId);
int mid = currentQuantity;
mid--;
ContentValues values = new ContentValues();
values.put(StoreContract.ProductEntry.COLUMN_QUANTITY, mid);
context.getContentResolver().update(mCurrentProductUri, values, null, null);
} else {
Toast.makeText(context, R.string.product_out_of_stock, Toast.LENGTH_SHORT).show();
}
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment