public class Editor extends AppCompatActivity implements LoaderManager.LoaderCallbacks { private static final String TAG =… [609099]

public class Editor extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<Cursor> {

private static final String TAG = Editor.class.getSimpleName();

public static final int PICK_IMAGE_REQUEST = 20;
public static final int EXTERNAL_STORAGE_REQUEST_PERMISSION_CODE = 21;
//Identifier for the inventory data loader
private static final int EXISTING_INVENTORY_LOADER = 0;
//General Product QUERY PROJECTION
public final String[] PRODUCT_C OLUMNS = {
DatabaseEntry._ID,
DatabaseEntry.COLUMN_NAME,
DatabaseEntry.COLUMN_QUANTITY,
DatabaseEntry.COLUMN_PRICE,
DatabaseEntry.COLUMN_DESCRIPTION,
DatabaseEntry.COLUMN_ITEMS_SOLD,
DatabaseEntry.COLUMN_SUPPLIER,
DatabaseEntry.COLUMN_IMAGE
};

private Uri mProductUri;

//Product UI elements
private ImageView mProductPhoto;
private EditText mProductName;
private EditText mProductDescription;

private EditText mProductInventory;
private EditText mItemSold;
private EditText mProductPrice;
private EditText mSupplier;
//Product Action Elements
private ImageButton plusAction;
private ImageButton minusAction;
private ImageButton deleteAction;
private ImageButton orderAction;
private ImageButton updateAction;
private TextView lUpdateSave;
private TextView lOrder;
private TextView lDelete;

private String m CurrentImageUri = "no images";
private String mSendEmail;
private String mSendProduct;
private int mSendQuantity = 50;
private int quantityItem = 0;
//Validation Variables
private boolean mProductHasChanged = false;

private Vie w.OnTouchListener mTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
mProductHasChanged = true;
return false;
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);

//Cast UI
mProductPhoto = (ImageView) findViewById(R.id.image_product_photo);
mProductName = (EditText) findViewById(R.id.inventory_item_name_edittext);
mProductDescription = (EditText) findViewById(R.id.inventory_item_description_edittext);
mProductInventory = (EditText) findViewById(R.id.inventory_item_current_quanti ty_edittext);
mItemSold = (EditText) findViewById(R.id.current_sales_edittext);
mProductPrice = (EditText) findViewById(R.id.inventory_item_price_edittext);
mSupplier = (EditText) findViewById(R.id.suplier_edittext);

//moni tor activity so we can protect user
mProductPhoto.setOnTouchListener(mTouchListener);
mProductName.setOnTouchListener(mTouchListener);
mProductDescription.setOnTouchListener(mTouchListener);
mProductInventory.setOnTouchListe ner(mTouchListener);
mItemSold.setOnTouchListener(mTouchListener);
mProductPrice.setOnTouchListener(mTouchListener);
mSupplier.setOnTouchListener(mTouchListener);

//Cast ActionButtons
deleteAction = (ImageButton) fi ndViewById(R.id.delete_product_button);
orderAction = (ImageButton) findViewById(R.id.order_supplier_button);

updateAction = (ImageButton) findViewById(R.id.save_product_button);
lUpdateSave = (TextView) findViewById(R.id.update_save_label);
lOrder = (TextView) findViewById(R.id.order_label);
lDelete = (TextView) findViewById(R.id.delete_label);

plusAction = (ImageButton) findViewById(R.id.plus_but ton);
plusAction.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
increaseQuantity();
}
});

minusAction = (ImageButton) findViewById(R.id.mi nus_button);
minusAction.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
decreaseQuantity();
}
});

//Make the photo click listener to upd ate itself
mProductPhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onPhotoUpdate(view);

}
});

updateAction.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
saveProduct();
}
});

deleteAction.setOnClickListener(new View.OnClickListen er() {
@Override
public void onClick(View view) {
deleteConfirmationDialog();
}
});

orderAction.setOnClickListener(new View.OnClickListener() {
@Override
public vo id onClick(View view) {
sendOrder();
}
});

//Check where we came from
Intent intent = getIntent();
mProductUri = intent.getData();

if (mProductUri == null) {

setTitle(getString(R.string.add_product_title));
lUpdateSave.setText(R.string.save_product_label);
orderAction.setVisibility(View.GONE);
lOrder.setVisibility(View.GONE);
deleteAction.setVisibility (View.GONE);
lDelete.setVisibility(View.GONE);

} else {
setTitle(getString(R.string.edit_product_title));
lUpdateSave.setText(R.string.update_product_label);

orderAction.setVisibility(View.VISIBLE);
lOrder.setVisibility(View.VISIBLE);
deleteAction.setVisibility(View.VISIBLE);
lDelete.setVisibility(View.VISIBLE);
getLoaderManager().initLoader(EXISTING_INVENTORY_LOADER, null, this);
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.editor, menu);
return true;

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

switch (item.getItemId()) {
case R.id.settings:
return true;

case android.R.id.home:
if (!mProductHasChanged) {
NavUtils.navigateUpFromSameTask(Editor.this);
return true;
}

DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInte rface dialogInterface, int i) {
NavUtils.navigateUpFromSameTask(Editor.this);
}
};

unsavedChangesDialog(discardButtonClickListener);
return true;

}

return super.onOptionsItemSelected(item);

}

public void onPhotoUpdate(View view) {

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_GRANTED) {
getPhoto();
} else {
String[] permisionRequest = {Manifest.permission.READ_EXTERNAL_STORAGE};
requestPermissions(permisionRequest, EXTERNAL_STORAGE_REQUEST_PERMISSION_CODE);
}
} else {
getPhoto();
}

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull Str ing[] permissions, @NonNull
int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == EXTERNAL_STORAGE_REQUEST_PERMISSION_CODE && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
//We got "The GO" from the user
getPhoto();
} else {
Toast.makeText(this, R.string.err_external_storage_permissions, Toast.LENGTH_LONG).show();
}
}

private void getPhoto() {
// invoke the image gallery using an implict intent.
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);

// where do we want to find the data?
File pictureDirectory =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureDirectoryPath = pictureDirectory.getPath();
// finally, get a URI representation
Uri data = Uri.parse(pictu reDirectoryPath);

// set the data and type. Get all image types.
photoPickerIntent.setDataAndType(data, "image/*");

// we will invoke this activity, and get something back from it.
startActivityForResult(photoPickerIntent , PICK_IMAGE_REQUEST);
}

@Override
public void onBackPressed() {
//Go back if we have no changes
if (!mProductHasChanged) {
super.onBackPressed();
return;
}

//otherwise Protect user from loosing info
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();

}
};

// Show that there are unsaved changes
unsavedChangesDialog(discardButtonClickListener);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
if (data != null) {
Uri mProductPhotoUri = data.getData();
mCurrentImageUri = mProductPhotoUri.toString();
Log.d(TAG, "Selected images " + mProductPhotoUri);

//We use Glide to import images
Glide.with(this).load(mProductPhotoUri)
.placeho lder(android.R.drawable.ic_btn_speak_now)
.crossFade()
.fitCenter()
.into(mProductPhoto);
}
}
}

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {

return new CursorLoader(this,
mProductUri,
PRODUCT_COLUMNS,
null,
null,
null);
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (cursor == null || cursor.getCount() < 1) {
return;
}

if (cursor.moveToFirst()) {

int i_COLUMN_NAME = 1;
int i_COLUMN_QU ANTITY = 2;
int i_COLUMN_PRICE = 3;
int i_COLUMN_DESCRIPTION = 4;
int i_COLUMN_ITEMS_SOLD = 5;
int i_COLUMN_SUPPLIER = 6;
int i_COLUMN_IMAGE = 7;

// Extract values from current cursor
String name = cursor.getString(i_COLUMN_NAME);
int quantity = cursor.getInt(i_COLUMN_QUANTITY);
float price = cursor.getFloat(i_COLUMN_PRICE);

String description = cursor.getString(i_COLUMN_DESCRIPTION);
int itemSold = cursor.getInt(i_COLUMN_ITEMS_SOLD);
String supplier = cursor.getString(i_COLUMN_SUPPLIER);
mCurrentImageUri = cursor.getString(i_COLUMN_IMAGE);

mSendEmail = "gmail@" + supplier + ".com";
mSendProduct = name;

//We updates fields to values on DB
mProductName.setText(name);
mProductPrice.setText(String.valueOf(price));
mProductInventory.setText(String.valueOf(quantity));
mProductDescription.setText(description);
mItemSold.setText(String.valueOf(itemSold));
mSupplier.setText(supplier);
//Update photo using Glide
Glide.with(this).load(mCurrentImageUri)
.placeholder(R.mipmap.ic_launcher)
.error(ic_insert_placeholder)
.crossFade()
.fitCenter()
.into(mProductPhoto);
}

}

//Update or save product
private void sa veProduct() {

//Read Values from text field
String salesString = mItemSold.getText().toString().trim();
String priceString = mProductPrice.getText().toString().trim();
String supplierString = mSupplier.getText().toString().trim();
String nameString = mProductName.getText().toString().trim();
String descriptionString = mProductDescription.getText().toString().trim();
String inventoryString = mProductInventory.getText().toString();

//Check if is new or if an update
if (TextUtils.isEmpty(nameString) || TextUtils.isEmpty(descriptionString)
|| TextUtils.isEmpty(inventoryString) || TextUtils.isEmpty(salesString)
|| TextUtils.isEmpty(priceString) || TextUtils.isEmpty(supplierString)) {

Toast.makeText(this, R.string.err_missing_textfields, Toast.LENGTH_SHORT).show();
// No change has been made so we can return
return;
}

//We set values for insert update
ContentValues values = new ContentValues();

values.put(DatabaseEntry.COLUMN_NAME, nameString);
values.put(DatabaseEntry.COLUMN_DESCRIPTION, descriptionString);
values .put(DatabaseEntry.COLUMN_QUANTITY, inventoryString);
values.put(DatabaseEntry.COLUMN_ITEMS_SOLD, salesString);
values.put(DatabaseEntry.COLUMN_PRICE, priceString);
values.put(DatabaseEntry.COLUMN_SUPPLIER, supplierString);
values.put(DatabaseEntry.COLUMN_IMAGE, mCurrentImageUri);

if (mProductUri == null) {

Uri insertedRow = getContentResolver().insert(DatabaseEntry.CONTENT_URI, values);

if (insertedRow == null) {
Toast.makeText(this, R.string.err_inserting_product, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, R.string.ok_updated, Toast.LENGTH_LONG).show();
Intent intent = new Intent(this, MainA ctivity.class);
startActivity(intent);
}
} else {
// We are Updating
int rowUpdated = getContentResolver().update(mProductUri, values, null, null);

if (rowUpdated == 0) {
Toast.makeText(this, R.string.err_inserting_product, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, R.string.ok_updated, Toast.LENGTH_LONG).show();
Intent intent = new Intent(this, MainActivity.clas s);
startActivity(intent);

}

}

}

@Override
public void onLoaderReset(Loader<Cursor> loader) {
mProductName.setText("");
mProductPrice.setText("");
mProductInventory.setText("");
mProductDescription.setText("");
mItemSold.setText("");
mSupplier.setText("");

}

private void unsavedChangesDialog(
DialogInterface.OnClickListener discardButtonClickListener) {
// Create an AlertDialog .Builder and set the message, and click listeners
// for the postivie and negative buttons on the dialog.
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();
}
}
});

// Create and show the AlertDialog
AlertDialog alertDialog = builder.create();

alertDialog.show();
}

/**
* Prompt the user to confirm that they want to delete this pet.
*/
private void deleteConfirmationDialog() {
// Create an AlertDialog.Builder and set the message, and click listeners
// for the postivie and negative buttons on the dialog.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.delete_dialog_msg);
builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
public void onC lick(DialogInterface dialog, int id) {
// User clicked the "Delete" button, so delete the pet.
deleteOrder();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked the "Cancel" button, so dismiss the dialog
// and continue editing the pet.
if (dialog != null) {
dialo g.dismiss();
}
}
});

// Create and show the AlertDialog

AlertDialog alertDialog = builder.create();
alertDialog.show();
}

/**
* Perform the deletion of the database.
*/
private void deleteOrder() {

if (mProductUri != null) {

int rowsDeleted = getContentResolver().delete(mProductUri, null, null);

// Show a toast message depending on whether or not the delete was successful.
if (rowsDeleted == 0) {
// If no rows were deleted, then there was an error with the delete.
Toast.makeText(this, getString(R.string.editor_delete_pet_failed),
Toast.LENGTH_SHORT).show();
} else {
// Otherwise, the delete was successful and we can display a toast.
Toast.makeText(this, getString(R.string.editor_delete_pet_successful),
Toast.LENGTH_SHORT).show();
}
}

// Close the activity
finish();
}

//Order from supplier
private void sendOrder() {
String[] TO = {mSendEmail};
Intent emailIntent = new Intent(Intent.ACTION_SEND);

emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Order " + mSendProduct);
emailIntent.putExtra(In tent.EXTRA_TEXT, "Please ship " + mSendProduct +
" in number of " + mSendQuantity);

try {
startActivity(Intent.createChooser(emailIntent, "Send mail…"));
} catch (android.content.ActivityNotFoundException ex) {
ex.printStackTrace();
}
}

private void increaseQuantity() {
quantityItem = Integer.parseInt(mProductInventory.getText().toString().trim());
int maximumIncreaseQuantity = 1000;
if (quantityItem < maximu mIncreaseQuantity) {
mProductHasChanged = true;
quantityItem++;
mProductInventory.setText(String.valueOf(quantityItem));
}
}

private void decreaseQuantity() {
quantityItem = Integer.parseInt(mPro ductInventory.getText().toString().trim());
if (quantityItem > 0) {
mProductHasChanged = true;
quantityItem -= 1;
mProductInventory.setText(String.valueOf(quantityItem));
}
}
}

Similar Posts

  • FUNDAȚIA PENTRU CULTURĂ ȘI ÎNVĂȚĂMÂNT IOAN [613530]

    FUNDAȚIA PENTRU CULTURĂ ȘI ÎNVĂȚĂMÂNT “IOAN SLAVICI” TIMIȘOARA UNIVERSITATEA “IOAN SLAVICI” TIMIȘOARA FACULTATEA DE INGINERIE DOMENIUL CALCULATOARE ȘI TEHNOLOGIA INFORMAȚIEI FORMA DE ÎNVĂȚĂMÂNT – ZI PROIECT DE DIPLOMĂ COORDONATOR ȘTIINȚIFIC ABSOLVENT: [anonimizat]. Vladutiu Mircea Cristi Roxana Doralina TIMIȘOARA 2019 FUNDAȚIA PENTRU CULTURĂ ȘI ÎNVĂȚĂMÂNT “IOAN SLAVICI” T IMIȘOARA UNIVERSITATEA “IOAN SLAVICI” TIMIȘOARA FACULTATEA DE INGINERIE…

  • MĂSURAREAoMĂRIMILORoELECTRICEo [617508]

    MĂSURAREAoMĂRIMILORoELECTRICEo 65 og III.gMĂSURAREAgMĂRIMILORgACTIVEg g g g 3.1.MăsurareagcurenŃilorgșigtensiunilorgcuggalvanometrulgg p 3.1.1.pGalvanometrulpdepc.c.pp o Esteounoaparatodeomareosensibilitateodestinatodetectăriiosauomăsurăriiocuren Ńilorocontinuiodeo intensităŃiofoarteomicio(10 -6o÷10 -12 oA)osauoaotensiunilorocontinueodeovaloareomicăo(10 -4o÷10 -9V).oo Istoriceșteovorbind,oprimeleomăsurătoriodeoc.c.os-auoexecutatocuogalvano metrulocuosuspensieopeofiro deotorsiune,opredecesoruloaparateloromagnetoelectriceocuobobinăomobilă.oPerfecŃionat,ogalvanomet rulocuo suspensieoesteoutilizatocaoaparatodeolaborator,opentruomăsurăriocareonuopresupuno deplasăriofrecvente,odaro sensibilitateomare.o Galvanometreleosuntoaparateodeotipomagnetoelectric,odiferindoconstructivo întreoeleoprin:oo /head2rightomodulUdeUrealizareUaUcircuituluiUmagnetic:UU /square4o câmpomagneticoradial;oo /square4o câmpomagneticouniform;oo /head2rightorealizareaUsuspensiei: osimplăosauodublă,opeobenziosauofireodeotorsiune;oo /head2rightodispozitivulUdeUcitire:U /square4o optic:o -o interior;o -o oexterior;oo /square4o cuoacoindicator;oo /head2rightosistemulUdeUfixare.UU Celeomaiosensibileogalvanometreosuntoceleocuosimplăosuspensieoșiodispozitiv oopticoexteriorodeo citireoaodeviaŃiiloro(fig.o3.1).oPeotimpuloneutilizării,oechipam entulomobiloseoblochează,oastfeloîncâtofirulodeo suspensieosăonuofieosolicitatoinutil.oo o o o ScărileoexterioareodeocitireointroduconeliniarităŃiopt.o α>40…

  • Organizarea și supravegherea protec ției muncii în Republica Moldova , [628250]

    UNIVERSITATEA DE STAT DIN MOLDOVA Cu titlu de manuscris C.Z.U.: 349.2 (043.3) PĂSCĂLUȚĂ FELICIA FORMELE CONTROLULUI RESPECT ĂRII LEGISLA ȚIEI ÎN DOMENIUL SECURIT ĂȚII ȘI SĂNĂTĂȚII ÎN MUNCĂ 553.05 – DREPTUL MUNCII ȘI PROTECȚIEI SOCIALE Teză de doctor în drept Conducător științific: ROMANDA Ș Nicolae doctor în drept, profesor universitar, specialitatea: 553.05 dreptul muncii și…

  • Administratie publica, specializarea Administratie publlica [606417]

    Universitatea “Nicolae Titulescu”, Facultatea de Relatii internationale si Administratie publica”, specializarea Administratie publlica LUCRARE DE LICENTA Cu tema: Functia publica si functionarul public Coordonator stiintific: Prof . univ. doct. Elena Emilia Stefan Absolvent: [anonimizat] 2018 Introducere Pentru lucrarea de licenta am ales ca tema sa fie “Functionarul public si functia publica”,aceasta fiind structurata pe trei…

  • Specializare Montanologie ID [303924]

    Universitatea „Lucian Blaga” [anonimizat]: Conf. univ. dr. ing. Mariana DUMITRU Student: [anonimizat] 2017 Universitatea „Lucian Blaga” [anonimizat]: Conf. univ. dr. ing. Mariana DUMITRU Student: [anonimizat] 2017 [anonimizat] a diminua frecările dintre suprafețe. Lubrifiantul prezent între suprafețele în mișcare relativă trebuie să îndeplinească următoarele funcții: Funcția mecanică. [anonimizat] o peliculă de ulei pentru a evita contactul…

  • DETECTING ENTANGLEMENT OF UNKNOWN CONTINUOUS VARIABLE STATES WITH RANDOM [622371]

    DETECTING ENTANGLEMENT OF UNKNOWN CONTINUOUS VARIABLE STATES WITH RANDOM MEASUREMENTS TATIANA MIHAESCU (1,2), HERMANN KAMPERMANN (1), DAGMAR BRUSS (1), AURELIAN ISAR (2,3), GIULIO GIANFELICI (1) (1) Heinrich-Heine-Universität Düsseldorf, Institut für Theoretische Physik III, D-40225 Düsseldorf, Germany (2) Department of Theoretical Physics, National Institute of Physics and Nuclear Engineering, RO-077125 Bucharest- Magurele, Romania (3) Faculty of…