java - 错误:无法在房间数据库中找到符号 @TypeConverters({Converters_kotlin.class})
问题描述
我正在开发一个应用程序,我打算将数据保存到 RoomDatabase 中。
当我尝试 sart 我的应用程序时,我得到了标题上的错误。
我不知道它是否将 kotlin 类与其他 java 类结合使用。
我的 kotlin 文件是 Converters.class,用于将 Image 保存到数据库中。
转换器.kotlin
class Converters_kotlin {
@TypeConverter
fun fromBitmap(bitmap:Bitmap): ByteArray{
val outputStream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
return outputStream.toByteArray()
}
@TypeConverter
fun toBitmap(byteArray: ByteArray):Bitmap{
return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size)
}
}
Birddb.java
@Database(
entities = {BirdRoom.class},
version = 1
)
@TypeConverters({Converters_kotlin.class})
public abstract class Birddb extends RoomDatabase {
private static volatile Birddb INSTANCE;
private static final int NUMBER_OF_THREADS = 1;
static final ExecutorService databaseWriteExecutor = Executors.newFixedThreadPool(NUMBER_OF_THREADS);
public abstract BirdDAO birdDAO();
public static Birddb getDatabase(final Context context) {
if (INSTANCE == null) {
synchronized (Birddb.class) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
Birddb.class, "user_database")
.build();
}
}
}
return INSTANCE;
}
}
以及我调用数据库的片段:
CaptureFragment.java
public class CaptureFragment extends Fragment {
private CaptureViewModel mViewModel;
private ImageButton btnCamara;
private ImageView mPhotoImageView;
public static final int REQUEST_CODE_TAKE_PHOTO = 0 /*1*/;
private String mCurrentPhotoPath;
private Uri photoURI;
private EditText Ettitulo;
public static CaptureFragment newInstance() {
return new CaptureFragment();
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
Ettitulo = (EditText) container.findViewById(R.id.EtInstantanea);
mPhotoImageView = (ImageView) container.findViewById(R.id.imgCapture);
mPhotoImageView.setImageDrawable(null);
btnCamara = (ImageButton) container.findViewById(R.id.btnCapture);
btnCamara.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//1.Open the camera.
if (v == mPhotoImageView) {
if (ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) getContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
} else {
ActivityCompat.requestPermissions((Activity) getContext(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
225);
}
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) getContext(),
Manifest.permission.CAMERA)) {
} else {
ActivityCompat.requestPermissions((Activity) getContext(),
new String[]{Manifest.permission.CAMERA},
226);
}
} else {
dispatchTakePictureIntent();
}
}
//2. Recover the photo and write into internal storage.
//TODO: Use AlerrtDiolog para solicitar nombre de la foto.
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//Send the Jornal, and keep into DB.
String titulo = Ettitulo.getText().toString();
Bundle bundle = new Bundle();
bundle.putString("edtValue", titulo);
bundle.putString("image", mCurrentPhotoPath);
//Swicth the () -> fragment
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
JournalFragment jf = new JournalFragment();
jf.setArguments(bundle);
transaction.replace(container.getId(),jf);
transaction.commit();
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
Toast.makeText(getContext(), "Foto NO añadida a su diario personal.", Toast.LENGTH_LONG).show();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
Intent intento1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File foto = new File(getActivity().getExternalFilesDir(null), mCurrentPhotoPath);
intento1.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(foto));
startActivity(intento1);
//3. Set the photo into the ImageView,
Bitmap bitmap1 = BitmapFactory.decodeFile(getActivity().getExternalFilesDir(null)+"/"+Ettitulo.getText().toString());
Drawable d = new BitmapDrawable(getResources(), bitmap1);
mPhotoImageView.setImageDrawable(d);
//4. Ask if the user want to keep that pjoto into his jornal.
AlertDialog.Builder builder1 = new AlertDialog.Builder(getContext());
builder1.setMessage("¿Le gustaría guardar esta foto en su diario?");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Instancio la BBDD local..
Birddb db = Room.databaseBuilder(getContext(),
Birddb.class, "database-name").build();
//Añado el objeto Bird a la BBDD local.
BirdDAO birdDAO = db.birdDAO();
//List<Bird> users = userDao.getAll();
AsyncTask.execute(new Runnable() {
@Override
public void run() {
//Guardar Objeto Bird en la BBDD.
String descripcion = Ettitulo.getText().toString();
BirdRoom bird = new BirdRoom(descripcion, mCurrentPhotoPath);
Birddb.getDatabase(getContext()).birdDAO().insertBird(bird);
Toast.makeText(getContext(), "Ejemplar añadido correctamente a su diario", Toast.LENGTH_LONG).show();
}
});
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getContext(), "No se ha añadido la foto actual a su diario", Toast.LENGTH_LONG).show();
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
});
return inflater.inflate(R.layout.fragment_capture, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewModel = new ViewModelProvider(this).get(CaptureViewModel.class);
}
private void checkExternalStoragePermission() {
if (ContextCompat.checkSelfPermission((Activity)getContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
Log.e(TAG, "Permission not granted WRITE_EXTERNAL_STORAGE.");
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) getContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
} else {
ActivityCompat.requestPermissions((Activity) getContext(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
225);
}
}if (ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
Log.e(TAG, "Permission not granted CAMERA.");
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) getContext(),
Manifest.permission.CAMERA)) {
} else {
ActivityCompat.requestPermissions((Activity) getContext(),
new String[]{Manifest.permission.CAMERA},
226);
}
}
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "MyPicture");
values.put(MediaStore.Images.Media.DESCRIPTION, "Photo taken on " + System.currentTimeMillis());
photoURI = getActivity().getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//Uri photoURI = FileProvider.getUriForFile(AddActivity.this, "com.example.android.fileprovider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_CODE_TAKE_PHOTO);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_TAKE_PHOTO && resultCode == RESULT_OK) {
Bitmap bitmap;
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), photoURI);
mPhotoImageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Ì如果您猜到如何解决,请提前感谢!
[编辑]
添加 Android Studio 错误返回的捕获。
解决方案
推荐阅读
- python - 我可以使用 connectedComponents 或 findContours 更好地识别正方形吗?在 python 上使用 opencv
- android - 在 Play 商店控制台中获取设备屏幕分辨率的统计信息
- css - ie中的垂直对齐占位符
- java - 如何在不同的片段/活动中维护 android 中的会话?
- r - R中的冲突过滤器命令
- docker - 如何在docker中复制子文件夹
- javascript - 我们在 JSPDF 中有右边距属性吗?
- asp.net - 在 ASP.NET 中使用 Html.ActionLink() 与 asp 属性创建链接,例如
- python - python get tommorows date dd.mm.yy问题
- java - 如果在生产者之后启动,Kafka 消费者不会读取生产者发送的消息