我正在使用Android Studio开发画廊应用程序,以其名称存储在数据库中。但是,当我尝试将空图像添加到数据库时,停止运行。当用户收到空数据时,应该显示一条敬酒消息,如请选择一张图片或插入名称。我在保存按钮的onClick
方法中尝试了一些方法,但是没有用。这是我尝试过的:
public void save (View view) {
String artName = editText.getText().toString();
//sikistirma islemi
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
selectedImage.compress(Bitmap.CompressFormat.PNG,50,outputStream);
byte[] byteArray = outputStream.toByteArray();
try {
if(artName!=null && outputStream!=null)
{
database = this.openOrCreateDatabase("Arts", MODE_PRIVATE, null);
database.execSQL("CREATE TABLE IF NOT EXISTS arts (name VARCHAR, image BLOB)"); //BLOB is dataType for images
String sqlString = "INSERT INTO arts (name, image) VALUES (?, ?)";
SQLiteStatement statement = database.compileStatement(sqlString);
statement.bindString(1, artName);
statement.bindBlob(2, byteArray);
statement.execute();
}
else
{
Toast.makeText(getApplicationContext(), "PPlease select an image or insert the name", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
答案 0 :(得分:0)
假设selectedImage是一个位图对象,则可以在代码中将其插入到数据库之前检查其是否为空
public void save (View view) {
String artName = editText.getText().toString();
if(selectedImage!=null)
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
selectedImage.compress(Bitmap.CompressFormat.PNG,50,outputStream);
byte[] byteArray = outputStream.toByteArray();
try {
if(artName!=null )
{
database = this.openOrCreateDatabase("Arts", MODE_PRIVATE, null);
database.execSQL("CREATE TABLE IF NOT EXISTS arts (name VARCHAR, image BLOB)"); //BLOB is dataType for images
String sqlString = "INSERT INTO arts (name, image) VALUES (?, ?)";
SQLiteStatement statement = database.compileStatement(sqlString);
statement.bindString(1, artName);
statement.bindBlob(2, byteArray);
statement.execute();
}
else
{
Toast.makeText(getApplicationContext(), "Please insert the name", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
else
{
// If the bitmap object is null display user toast to select the image
Toast.makeText(getApplicationContext(), "Please select some image", Toast.LENGTH_LONG).show();
}
}