I am trying to solve this issue but i didn#t find enything until now. So my Image View its a string and i am trying to call it with Glide.with and many more but unfortunately no success until now. It should be a simple Line of code but i am not finding it.
class ImageInformation : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_image_information)
val image = intent.getParcelableExtra<ImageModel>("image")
if (image != null){
val downloadUrl: TextView = findViewById(R.id.downloadUrla)
val previewUrl : ImageView = findViewById(R.id.previewUrls)
val id: TextView = findViewById(R.id.idsa)
val filename: TextView = findViewById(R.id.fileNamea)
val filesize: TextView = findViewById(R.id.filesizea)
val contentType: TextView = findViewById(R.id.contentTypea)
val createdBy: TextView = findViewById(R.id.createdBya)
val createdTimestamp: TextView = findViewById(R.id.createdTimestampa)
val creationSource: TextView = findViewById(R.id.creationSourcea)
val domainIdentityType: TextView = findViewById(R.id.domainIdentityTypea)
val domainIdentityValue: TextView = findViewById(R.id.domainIdentityValuea)
val tags: TextView = findViewById(R.id.tagsa)
val description: TextView = findViewById(R.id.descriptiona)
downloadUrl.text = image.downloadUrl
TO DO, Preview URL
//previewUrl.setImageResource(image.previewUrl)//Required Int not a String.
//Glide.with(this).load( previewUrl).into(previewUrl)
//Glide.with(Activity()).load(previewUrl).centerInside().into(previewUrl)
//previewUrl.setImageResource(image.previewUrl)
//Glide.with(Activity()).load(previewUrl).into(image.previewUrl)
//Glide.with(this).load(previewUrl).centerInside().into(image.previewUrl)
//previewUrl.setImageResource(image.previewUrl)
//Nothing from the above lines doesn#t work.
id.text = image.id
filename.text = image.fileName
filesize.text = image.filesize.toString()
contentType.text = image.contentType
createdBy.text = image.createdBy
createdTimestamp.text = image.createdTimestamp
creationSource.text = image.creationSource
domainIdentityType.text = image.domainIdentityType
domainIdentityValue.text = image.domainIdentityValue
tags.text = image.tags.toString()
description.text = image.description
}
}
}
Try this:
Glide.with(context)
.load(image.downloadUrl) // here we are telling Glide what it needs to load
.into(previewUrl) // here we are telling Glide where to load it into (your imageView)
I must say your naming of you ImageView (previewUrl) does make it very hard to read, it might be better to rename it to something like previewImageView.
Related
I want to make an application that calculates the differences between the current date and another date. I add "reset" button to change other date to current date. I want to save new date as default when i click button.
What can I do so that the changes I made do not go away when I restart the application and are permanent?
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
DateDifferenceApp()
}
}
}
#Composable
fun DateDifferenceApp() {
val calendar = Calendar.getInstance().time
val currentDate1 = DateFormat.getDateInstance().format(calendar)
val time = DateFormat.getTimeInstance(DateFormat.SHORT).format(calendar)
val currentDate = remember { Calendar.getInstance().time }
var otherDate by remember {
mutableStateOf(
Calendar.getInstance().apply {
set(Calendar.YEAR, 2023)
set(Calendar.MONTH, Calendar.FEBRUARY)
set(Calendar.DAY_OF_MONTH, 12)
}.time
)
}
val diff = currentDate.time - otherDate.time
val diffInDays = TimeUnit.MILLISECONDS.toDays(diff)
val startingDate = DateFormat.getDateInstance().format(otherDate)
Button(onClick = { otherDate = currentDate },
modifier = Modifier.size(150.dp)
) {
Text("Reset",fontSize = 24.sp)
}
enter image description here
I have been trying to code a step tracker app. When I build the app, it doesn't show any errors but when I run it, it crashes and throws this:
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Float
at com.example.fitnesstracker.MainActivity.loadData(MainActivity.kt:159)
at com.example.fitnesstracker.MainActivity.onCreate(MainActivity.kt:48)
I have implemented everything that I need but it won't start.
Here is the code for the saveData() and loadData() where I have the error:
private fun saveData() {
val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putFloat("key1", previoustotalSteps)
editor.apply()
}
private fun loadData(){
val sharedPreferences= getSharedPreferences("myPrefs", Context.MODE_PRIVATE)
val savedNumber = sharedPreferences.getFloat("key1", 0f)
Log.d("MainActivity", "$savedNumber")
previoustotalSteps = savedNumber
}
These lines are after the setContentView in the onCreate method:
loadData()
resetSteps()
sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
And these are the other functions that I use:
override fun onSensorChanged(event: SensorEvent?) {
if(running){
val stepstaken = findViewById<TextView>(R.id.steps_taken_id)
val progressBar = findViewById<CircularProgressBar>(R.id.circularProgressBar)
totalSteps = event!!.values[0]
val currentSteps = totalSteps.toInt() - previoustotalSteps.toInt()
stepstaken.text = currentSteps.toString()
progressBar.apply {
setProgressWithAnimation(currentSteps.toFloat())
}
}
}
private fun resetSteps(){
val stepstaken = findViewById<TextView>(R.id.steps_taken_id)
stepstaken.setOnClickListener {
Toast.makeText(this, "Long tap for step reset.", Toast.LENGTH_SHORT).show()
}
stepstaken.setOnLongClickListener {
previoustotalSteps = totalSteps
stepstaken.text = 0.toString()
saveData()
true
}
}
Also the step counter doesn't work. It stays at 0 no matter how much I move my phone.
I am a beginner developer. I'm sorry for my english.
I am trying to make a barcode reader application. I use MLKit and CameraX.
I want to analyze only the part of the preview that is in the rectangle. Now the preview is being analyzed in full. I only want to analize what is in the rectangle. I tried to use the ViewPort, but it seems I didn't quite understand what it was for, because it could not solve the problem. I looked for solutions on the Internet, but my problem remained relevant. I think that before analysis it is necessary to crop the image and only then analyze it, but is this true?
My layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="false"
tools:background="#android:color/white"
tools:context=".ui.BarcodeScanningFragment">
<androidx.camera.view.PreviewView
android:id="#+id/viewFinder"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.t_ovchinnikova.android.scandroid_2.ui.ViewFinderOverlay
android:id="#+id/overlay"
android:layerType="software"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
Camera class:
class CameraSource (private val overlay: ViewFinderOverlay) {
private lateinit var cameraExecutor: ExecutorService
val preview : Preview = Preview.Builder()
.build()
fun startCamera() {
val cameraProviderFuture = ProcessCameraProvider.getInstance(overlay.context)
cameraProviderFuture.addListener(Runnable {
//Используется для привязки жизненного цикла камер к владельцу жизненного цикла
val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
bindCameraUseCases(cameraProvider)
}, ContextCompat.getMainExecutor(overlay.context))
}
#SuppressLint("UnsafeOptInUsageError")
private fun bindCameraUseCases(cameraProvider: ProcessCameraProvider) {
val imageAnalysis = ImageAnalysis.Builder()
.setTargetResolution(Size(overlay.width, overlay.height))
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.build()
val orientationEventListener = object : OrientationEventListener(overlay.context) {
override fun onOrientationChanged(orientation : Int) {
// Monitors orientation values to determine the target rotation value
val rotation : Int = when (orientation) {
in 45..134 -> Surface.ROTATION_270
in 135..224 -> Surface.ROTATION_180
in 225..314 -> Surface.ROTATION_90
else -> Surface.ROTATION_0
}
imageAnalysis.targetRotation = rotation
}
}
orientationEventListener.enable()
cameraExecutor = Executors.newSingleThreadExecutor()
val analyzer = BarcodeAnalyzer()
imageAnalysis.setAnalyzer(cameraExecutor, analyzer)
var cameraSelector : CameraSelector = CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK)
.build()
val useCaseGroup = UseCaseGroup.Builder()
.addUseCase(preview)
.addUseCase(imageAnalysis)
.build()
cameraProvider.bindToLifecycle(overlay.context as LifecycleOwner, cameraSelector, useCaseGroup)
}
}
class ViewFinderOverlay:
class ViewFinderOverlay(context: Context, attrs: AttributeSet) : View(context, attrs) {
private val boxPaint: Paint = Paint().apply {
color = ContextCompat.getColor(context, R.color.barcode_reticle_stroke)
style = Paint.Style.STROKE
strokeWidth = context.resources.getDimensionPixelOffset(R.dimen.barcode_stroke_width).toFloat()
}
private val scrimPaint: Paint = Paint().apply {
color = ContextCompat.getColor(context, R.color.barcode_reticle_background)
}
private val eraserPaint: Paint = Paint().apply {
strokeWidth = boxPaint.strokeWidth
xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
}
private val boxCornerRadius: Float =
context.resources.getDimensionPixelOffset(R.dimen.barcode_reticle_corner_radius).toFloat()
var boxRect: RectF? = null
fun setViewFinder() {
val overlayWidth = width.toFloat()
val overlayHeight = height.toFloat()
val boxWidth = overlayWidth * 80 /100
val boxHeight = overlayHeight * 36 / 100
val cx = overlayWidth / 2
val cy = overlayHeight / 2
boxRect = RectF(cx - boxWidth / 2, cy - boxHeight / 2, cx + boxWidth / 2, cy + boxHeight / 2)
invalidate()
}
override fun draw(canvas: Canvas) {
super.draw(canvas)
boxRect?.let {
canvas.drawRect(0f, 0f, canvas.width.toFloat(), canvas.height.toFloat(), scrimPaint)
eraserPaint.style = Paint.Style.FILL
canvas.drawRoundRect(it, boxCornerRadius, boxCornerRadius, eraserPaint)
eraserPaint.style = Paint.Style.STROKE
canvas.drawRoundRect(it, boxCornerRadius, boxCornerRadius, eraserPaint)
// Draws the box.
canvas.drawRoundRect(it, boxCornerRadius, boxCornerRadius, boxPaint)
}
}
}
ViewFinderOverlay - a view that is superimposed on the camera preview.
Screen:
[1]: https://i.stack.imgur.com/cYvFP.jpg
Image analyzer:
#SuppressLint("UnsafeOptInUsageError")
override fun analyze(imageProxy: ImageProxy) {
val mediaImage = imageProxy.image
if (mediaImage != null) {
val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees)
val scanner = BarcodeScanning.getClient()
scanner.process(image)
.addOnSuccessListener { barcodes ->
barcodes?.firstOrNull().let { barcode ->
val rawValue = barcode?.rawValue
rawValue?.let {
}
}
}
imageProxy.close()
}
}
Help me please. I would be glad to any advice.
You can take a look at LifecycleCameraController. It takes care of creating use cases as well as configuring ViewPort.
However AFAIK, MLKit doesn't respect the crop rect. What you can do is checking the MLKit result, and discard any barcode whose coordinates are outside of the crop rect.
I wrote a simple temperature converter app, everything is working fine except when user leaves EditText blank/null but selects one of the radio buttons, The App crashes.
Here is the Kotlin Code:
class MainActivity : AppCompatActivity() {
lateinit var etTemp: EditText
lateinit var radioGroup: RadioGroup
lateinit var btnConverter :Button
lateinit var tempConverted: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "Zeeshan's Temperature Converter"
etTemp = findViewById(R.id.etTemp)
radioGroup = findViewById(R.id.radioGroup)
btnConverter = findViewById(R.id.btnConverter)
tempConverted = findViewById(R.id.tempConverted)
btnConverter.setOnClickListener {
val id = radioGroup.checkedRadioButtonId
val radioButton = findViewById<RadioButton>(id)
if (radioButton == findViewById(R.id.radioC)){
val temp =etTemp.text.toString().toInt()
val result = temp * 9/5 + 32
tempConverted.setText(result.toString())
}
else if (radioButton == findViewById(R.id.radioF)){
val tempy =etTemp.text.toString().toInt()
val resulty = (tempy - 32) / 1.8
tempConverted.setText(resulty.toString())
}
else{
Toast.makeText(this#MainActivity, "Select one conversion scale", Toast.LENGTH_SHORT).show()
}
}
}
}
You should check if etTemp.text.ToString() == "" (that is empty string) if it is, then do not try to convert it into int. The problem appears when you try to convert "null" value to int.
Inside the listener add a check for for EditText to check whether it is empty or not,
btnConverter.setOnClickListener {
// Add the validation check here ... like this -> if(etTemp.length() > 0){
val id = radioGroup.checkedRadioButtonId
val radioButton = findViewById<RadioButton>(id)
if (radioButton == findViewById(R.id.radioC)){
val temp =etTemp.text.toString().toInt()
val result = temp * 9/5 + 32
tempConverted.setText(result.toString())
}
else if (radioButton == findViewById(R.id.radioF)){
val tempy =etTemp.text.toString().toInt()
val resulty = (tempy - 32) / 1.8
tempConverted.setText(resulty.toString())
}
else{
Toast.makeText(this#MainActivity, "Select one conversion scale", Toast.LENGTH_SHORT).show()
}
// Close the check here -> }
else{
// Prompt the user to put some text in the field - this is called form validation before processing
// Toast.makeText(.....).show
}
}
check if the user has entered some input or not, one way is like below (Kotlin):
if(!etTemp.text.isNullOrEmpty())
{
temp =etTemp.text.toString().toInt()
}
In the raw directory I have files named rhode1.mp3 to rhode49.mp3.
I need to randomly play one of these files so I'm randomly generating a number and attaching it to R.raw.rhode to use as URI (uri1 in the code below), but it crashes the app. When I replace uri1 with R.raw.rhode1 for example it works and the audio file plays.
I tried writing R.raw.rhode$note1.mp3 and it still didn't work. Also tried:
("R.raw.rhode" + note1.toString() + ".mp3")
And:
("R.raw.rhode" + note1.toString())
override fun onCreate (savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var mediaplayer: MediaPlayer? = null
val letsgo = findViewById<Button>(R.id.start)
val think = findViewById<SeekBar>(R.id.think)
val extime = findViewById<SeekBar>(R.id.extime)
val rpt = findViewById<SeekBar>(R.id.rpt)
val rtime = findViewById<SeekBar>(R.id.rtime)
var note1: Int
var uri1: Uri
letsgo.setOnClickListener {
note1 = Random.nextInt(49) + 1
uri1 = Uri.parse("R.raw.rhode" + note1.toString())
mediaplayer = MediaPlayer.create(applicationContext, uri1)
mediaplayer!!.start()
}
}
R.resourceType.resourceName is a valid symbol from the point of the programming language. But it is, obviously, not an URL/URI.
Here is a sample of how to construct a resource URI: https://stackoverflow.com/a/7979084/3050249