gpt4 book ai didi

java - 将图像保存到 sqlite 数据库后图像不显示

转载 作者:行者123 更新时间:2023-11-30 00:09:08 25 4
gpt4 key购买 nike

在这个应用程序中,我将产品保存在 sqlite 数据库中。你能帮我理解为什么我要编辑产品时看不到图像吗?添加时我可以看到它,但单击产品进行编辑时看不到它。

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

private static final int EXISTING_PRODUCT_LOADER = 1;

private static final int PICTURE_GALLERY_REQUEST = 1;

private static final String STATE_PICTURE_URI = "STATE_PICTURE_URI";

private Uri mPictureUri;

private Uri mCurrentProductUri;

private EditText mNameEditText;

private EditText mPriceEditText;

private EditText mQuantityEditText;

private EditText mSupplierEditText;

private EditText mMailEditText;

private int mProductQuantity=-1;

private Button mIncreaseQuantityButton;
private Button mDecreaseQuantityButton;

private Button mSelectImageButton;

private ImageView mProductImageView;

private String picturePath;

private String stringUri;

private Button mOrderButton;

final Context mContext = EditorActivity.this;

private boolean mProductHasChanged = false;

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

public static Bitmap getImage(byte[] image) {
return BitmapFactory.decodeByteArray(image, 70, image.length);
}

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

Intent intent = getIntent();
mCurrentProductUri = intent.getData();

if (mCurrentProductUri == null) {
setTitle(getString(R.string.editor_activity_title_new_product));

invalidateOptionsMenu();
} else {
setTitle(getString(R.string.editor_activity_title_edit_product));

getLoaderManager().initLoader(EXISTING_PRODUCT_LOADER, null, this);
}

initialiseViews();

setOnTouchListener();
}
private void setOnTouchListener() {
mNameEditText.setOnTouchListener(mTouchListener);
mPriceEditText.setOnTouchListener(mTouchListener);
mQuantityEditText.setOnTouchListener(mTouchListener);
mSupplierEditText.setOnTouchListener(mTouchListener);
mMailEditText.setOnTouchListener(mTouchListener);
mIncreaseQuantityButton.setOnTouchListener(mTouchListener);
mDecreaseQuantityButton.setOnTouchListener(mTouchListener);
mSelectImageButton.setOnTouchListener(mTouchListener);
mOrderButton.setOnTouchListener(mTouchListener);
}

private void initialiseViews() {
mOrderButton = (Button) findViewById(R.id.order_button);
mOrderButton.setVisibility(View.VISIBLE);
mOrderButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String productName = mNameEditText.getText().toString().trim();
String emailAddress = "mailto:" + mMailEditText.getText().toString().trim();
String subjectHeader = "Order For: " + productName;
String orderMessage = "Please send a unit of " + productName + ". " + " \n\n" + "Thank you.";
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setData(Uri.parse(emailAddress));
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, orderMessage);
intent.putExtra(Intent.EXTRA_SUBJECT, subjectHeader);
startActivity(Intent.createChooser(intent, "Send Mail..."));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
});




mNameEditText = (EditText) findViewById(R.id.edit_name);
mPriceEditText = (EditText) findViewById(R.id.edit_price);
mQuantityEditText = (EditText) findViewById(R.id.edit_quantity);
mSupplierEditText = (EditText) findViewById(R.id.edit_supplier);
mMailEditText= (EditText) findViewById(R.id.edit_supplier_mail);

mIncreaseQuantityButton = (Button) findViewById(R.id.editor_increase);
mIncreaseQuantityButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String quanititynumber = mQuantityEditText.getText().toString();
if (TextUtils.isEmpty(quanititynumber)) {

Toast.makeText(EditorActivity.this, "Quantity field is Empty", Toast.LENGTH_SHORT).show();
return;
} else {
mProductQuantity = Integer.parseInt(quanititynumber);

mProductQuantity++;
mQuantityEditText.setText(String.valueOf(mProductQuantity));
}}
});

mDecreaseQuantityButton = (Button) findViewById(R.id.editor_decrease);
mDecreaseQuantityButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String quanititynumber = mQuantityEditText.getText().toString();

if (TextUtils.isEmpty(quanititynumber)) {

Toast.makeText(EditorActivity.this, "Quantity field is Empty", Toast.LENGTH_SHORT).show();
return;
} else {
mProductQuantity = Integer.parseInt(quanititynumber);

if (mProductQuantity > 0) {
mProductQuantity--;
mQuantityEditText.setText(String.valueOf(mProductQuantity));
}
}}
});

mProductImageView = (ImageView) findViewById(R.id.image);
mSelectImageButton = (Button) findViewById(R.id.upload_image);
mSelectImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

Intent openPictureGallery = new Intent(Intent.ACTION_OPEN_DOCUMENT);

File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

String pictureDirectoryPath = pictureDirectory.getPath();

Uri data = Uri.parse(pictureDirectoryPath);

openPictureGallery.setDataAndType(data, "image/*");

startActivityForResult(openPictureGallery, PICTURE_GALLERY_REQUEST);
}

});
}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
// checking if the request code and result code match our request
if (requestCode == PICTURE_GALLERY_REQUEST && resultCode == Activity.RESULT_OK) {
if (resultData != null) {
try {
//this is the address of the image on the sd cards
mPictureUri = resultData.getData();
int takeFlags = resultData.getFlags();
takeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

picturePath = mPictureUri.toString();
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getContentResolver().takePersistableUriPermission(mPictureUri, takeFlags);
}
} catch (SecurityException e) {
e.printStackTrace();
}
mProductImageView.setImageBitmap(getBitmapFromUri(mPictureUri, mContext, mProductImageView));

} catch (Exception e) {
e.printStackTrace();
//Show the user a Toast mewssage that the Image is not available
Toast.makeText(EditorActivity.this, "Unable to open image", Toast.LENGTH_LONG).show();
}
}
}
}

public Bitmap getBitmapFromUri(Uri uri, Context mContext, ImageView imageView) {

if (uri == null || uri.toString().isEmpty())
return null;

// Get the dimensions of the View
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();

InputStream input = null;
try {
input = this.getContentResolver().openInputStream(uri);

// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeStream(input, null, bmOptions);
if (input != null)
input.close();

int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;

// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);

// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;

input = this.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, bmOptions);
Bitmap.createScaledBitmap(bitmap, 88, 88, false);
input.close();
return bitmap;

} catch (FileNotFoundException fne) {
Log.e("EditorActivity", "Failed to load image.", fne);
return null;
} catch (Exception e) {
Log.e("EditorActivity", "Failed to load image.", e);
return null;
} finally {
try {
input.close();
} catch (IOException ioe) {

}
}
}


private void saveProduct() {

String nameString = mNameEditText.getText().toString().trim();
String quantityString = mQuantityEditText.getText().toString().trim();
String priceString = mPriceEditText.getText().toString().trim();
String supplierString = mSupplierEditText.getText().toString().trim();
String supplierEmailString = mMailEditText.getText().toString().trim();


if (mCurrentProductUri == null &&
TextUtils.isEmpty(nameString) && TextUtils.isEmpty(quantityString) &&
TextUtils.isEmpty(priceString) && TextUtils.isEmpty(supplierString)&& TextUtils.isEmpty(supplierEmailString)) {
return;
}

int quantity = parseInt(quantityString);
double price = Double.parseDouble(mPriceEditText.getText().toString().trim());

ContentValues values = new ContentValues();
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_NAME, nameString);
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_PRICE, priceString);
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_QUANTITY, quantityString);
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER, supplierString);
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER_MAIL, supplierEmailString);

if(mPictureUri!=null) {
picturePath = mPictureUri.toString().trim();
}
else{
picturePath=stringUri;
}

values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_PICTURE, picturePath);

if (mCurrentProductUri == null) {

Uri newUri = getContentResolver().insert(ProductContract.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) {
String[] projection = {
ProductContract.ProductEntry._ID,
ProductContract.ProductEntry.COLUMN_PRODUCT_NAME,
ProductContract.ProductEntry.COLUMN_PRODUCT_PRICE,
ProductContract.ProductEntry.COLUMN_PRODUCT_QUANTITY,
ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER,
ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER_MAIL,
ProductContract.ProductEntry.COLUMN_PRODUCT_PICTURE};

return new CursorLoader(this, // Parent activity context
mCurrentProductUri, // Query the content URI for the current product
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 cursor) {
if (cursor == null || cursor.getCount() < 1) {
return;
}

ViewTreeObserver viewTreeObserver = mProductImageView.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mProductImageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
mProductImageView.setImageBitmap(getBitmapFromUri(mPictureUri, mContext, mProductImageView));
}
}
});

if (cursor.moveToFirst()) {
int nameColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_NAME);
int priceColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_PRICE);
int quantityColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_QUANTITY);
int supplierColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER);
int mailColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER_MAIL);
int pictureColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_PICTURE);

String name = cursor.getString(nameColumnIndex);
String price = cursor.getString(priceColumnIndex);
int quantity = cursor.getInt(quantityColumnIndex);
String supplier = cursor.getString(supplierColumnIndex);
String mail = cursor.getString(mailColumnIndex);
stringUri = cursor.getString(pictureColumnIndex);

Uri uriData = Uri.parse(stringUri);


mNameEditText.setText(name);
mPriceEditText.setText(price);
mQuantityEditText.setText(String.valueOf(quantity));
mSupplierEditText.setText(supplier);
mMailEditText.setText(mail);
if (mPictureUri!=null){
if (stringUri!=null)
mProductImageView.setImageURI(uriData);
else {
Bitmap bM = getBitmapFromUri(mPictureUri, mContext, mProductImageView);
mProductImageView.setImageBitmap(bM);
}}

}
}

@Override
public void onLoaderReset(Loader<Cursor> loader) {
mNameEditText.setText("");
mPriceEditText.setText("");
mQuantityEditText.setText("");
mSupplierEditText.setText("");
mMailEditText.setText("");
mProductImageView.setImageResource(R.drawable.ic_add_a_photo_black_24dp);
}


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();
}
}

完整代码的链接是:https://drive.google.com/open?id=1aQFcWHinIqqXHbTyssfPYTD20o9E2piA如果您在这里找不到 java 文件,它们是:https://drive.google.com/drive/folders/1VKp0CoJlJssSdKzK4ctk26KFY0_xIDzU?usp=sharing

最佳答案

在您的 onLoadFinished 中,您假设 mPictureURI 已设置且不为空。现在您已经在 mProductImageView 上设置了一个用于更改的监听器。无论您在 mProductImageView 下面写/设置什么,最终在监听器中它被设置回 mPictureURI,它是空的,因此显示一个空的图像空间。

请看下面的代码(也验证它有效)。

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

if (cursor.moveToFirst()) {
int nameColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_NAME);
int priceColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_PRICE);
int quantityColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_QUANTITY);
int supplierColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER);
int mailColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER_MAIL);
int pictureColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_PICTURE);

String name = cursor.getString(nameColumnIndex);
String price = cursor.getString(priceColumnIndex);
int quantity = cursor.getInt(quantityColumnIndex);
String supplier = cursor.getString(supplierColumnIndex);
String mail = cursor.getString(mailColumnIndex);
stringUri = cursor.getString(pictureColumnIndex);

mPictureUri = Uri.parse(stringUri);


mNameEditText.setText(name);
mPriceEditText.setText(price);
mQuantityEditText.setText(String.valueOf(quantity));
mSupplierEditText.setText(supplier);
mMailEditText.setText(mail);
}

ViewTreeObserver viewTreeObserver = mProductImageView.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mProductImageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
if(mPictureUri !=null) {
mProductImageView.setImageBitmap(getBitmapFromUri(mPictureUri, mContext, mProductImageView));
}
}
}
});
}

关于java - 将图像保存到 sqlite 数据库后图像不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48477272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com