Problem with sharing image in flutter without package - android

I'm trying to create a natvie functions in flutter to share a image.
I didnt have problem with IOS, but in android and kotlin URI doesn't work.
Can anyone find a solution?
Its my code:
private fun shareImage(name: String, title: String, mimeType: String, path: String): Boolean {
val path = context.filesDir.absolutePath
val file = File("$path/$name")
Uri myUri = Uri.parse("$path/$name")
val shareIntent: Intent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_STREAM, myUri)
type = mimeType
}
startActivity(Intent.createChooser(shareIntent, null))
return true
}
My imports:
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import android.app.Activity
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.Uri
import java.io.File;
Errors:
e: /Users/***/MainActivity.kt: (45, 15): Expecting an element
e: /Users/***/MainActivity.kt: (45, 20): Expecting an element
e: /Users/***/MainActivity.kt: (45, 5): Classifier 'Uri' does not have a companion object, and thus must be initialized here
e: /Users/***/MainActivity.kt: (49, 37): Unresolved reference: myUri
FAILURE: Build failed with an exception.

Related

my android kotlin activity is not finding libhunspell.so

I want to write a activity for my android app that spell-checks words in my language (Czech). I included the .dic and .aff that I need. The app runs normally but when I try to proceed to this activity
package com.example.mainscreen
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat.getSystemService
import androidx.core.content.ContextCompat.startActivity
import com.nikialeksey.hunspell.Hunspell
import com.sun.jna.Native
import com.sun.jna.NativeLibrary
class TextCheck : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_text_check)
val incorrectText = findViewById<TextView>(R.id.incorrectText)
val correctText = findViewById<TextView>(R.id.suggText)
val copyBtn = findViewById<ImageView>(R.id.copyicon)
val backBtn = findViewById<Button>(R.id.backBtn)
val resultTV = intent.getStringExtra("resultTV")
incorrectText.text = resultTV
val libPath = "MainScreen\\app\\libs\\hunspell.jar"
val hunspell = Hunspell("resources/dictionaries/cs_CZ.dic", "resources/dictionaries/cs_CZ.aff")
NativeLibrary.addSearchPath("hunspell", libPath)
val misspelledWords = mutableMapOf<String, List<String>>()
resultTV?.split(" ")?.forEach { word ->
if (hunspell.spell(word)) {
misspelledWords[word] = hunspell.suggest(word)
}
}
if (misspelledWords.isNotEmpty()) {
val correctedText = StringBuilder()
misspelledWords.forEach { (misspelled, suggestions) ->
correctedText.append("$misspelled: ${suggestions.joinToString(", ")}")
correctedText.append("\n")
}
correctText.text = correctedText.toString()
} else {
correctText.text = getString(R.string.textright)
}
copyBtn.setOnClickListener {
val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText("corrected text", correctText.text)
clipboard.setPrimaryClip(clip)
Toast.makeText(this, "Corrected text copied to clipboard", Toast.LENGTH_SHORT).show()
}
backBtn.setOnClickListener {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
}
}
it returns to main page and giving me this error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mainscreen, PID: 28788
java.lang.UnsatisfiedLinkError: Unable to load library 'hunspell':
dlopen failed: library "libhunspell.so" not found
dlopen failed: library "libhunspell.so" not found
dlopen failed: library "libhunspell.so" not found
Native library (android-aarch64/libhunspell.so) not found in resource path (.)
at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:323)
at com.sun.jna.NativeLibrary.getInstance(NativeLibrary.java:483)
at com.sun.jna.Library$Handler.<init>(Library.java:197)
at com.sun.jna.Native.load(Native.java:622)
at com.sun.jna.Native.load(Native.java:596)
at com.nikialeksey.hunspell.Hunspell.<clinit>(Hunspell.java:20)
at com.example.mainscreen.TextCheck.onCreate(TextCheck.kt:35)
at android.app.Activity.performCreate(Activity.java:8129)
at android.app.Activity.performCreate(Activity.java:8109)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1344)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3749)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3942)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:109)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2345)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:233)
at android.os.Looper.loop(Looper.java:344)
at android.app.ActivityThread.main(ActivityThread.java:8212)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:584)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1034)
Suppressed: java.lang.UnsatisfiedLinkError: dlopen failed: library "libhunspell.so" not found
at com.sun.jna.Native.open(Native Method)
at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:211)
... 22 more
Suppressed: java.lang.UnsatisfiedLinkError: dlopen failed: library "libhunspell.so" not found
at com.sun.jna.Native.open(Native Method)
at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:224)
... 22 more
Suppressed: java.lang.UnsatisfiedLinkError: dlopen failed: library "libhunspell.so" not found
at java.lang.Runtime.loadLibrary0(Runtime.java:1077)
at java.lang.Runtime.loadLibrary0(Runtime.java:998)
at java.lang.System.loadLibrary(System.java:1661)
at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:238)
... 22 more
Suppressed: java.io.IOException: Native library (android-aarch64/libhunspell.so) not found in resource path (.)
at com.sun.jna.Native.extractFromResourcePath(Native.java:1145)
at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:295)
... 22 more
what am I doing wrong? I am only a beginner at developing Android apps

I'm trying to read an excel file from external storage using apache POI and having trouble

I want to parse an excel file in "external storage" with apache POI on an android phone. I put the file in the downloads folder when I downloaded it. I can always expect it to be there, not on a cloud, not being edited by other apps, not ephemeral in any way. The Apache POI workbookfactory needs a FileInputStream. After trying many different things I am burnt out.
Other similar questions on here involve huge swaths of code that deal in images and fanciful sources. All the examples I find use startActivityForResult which is DEPRECATED. So I tried some registerForActivityResult using contracts. No dice. Anyone know why the mime type "application/vnd.ms-excel.sheet.macroEnabled.12" doesn't work for xlsm files but images/png does? I also tried copying the file from content URI to local/app/scoped/cachedir storage and I wasn't successful either.
I was expecting the ability to point to a file and say "into the Apache POI excel file wood chipper with you!" and like in Fargo the Apache POI would spit little red cell values all over Log.d and eventually I'll do stuff with that information.
import android.content.ContentResolver
import android.net.Uri
import android.os.Bundle
import android.os.ParcelFileDescriptor
import android.provider.OpenableColumns
import android.util.Log
import android.widget.Button
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import org.apache.commons.compress.utils.IOUtils
import org.apache.poi.ss.usermodel.WorkbookFactory
import java.io.*
import java.nio.channels.FileChannel
fun readingxl(input: InputStream?) {
//Workbook wb = Workbookfactory.create(new File(bob.getPath()))
//Log.d("wtf",bob.toString())
//val input = FileInputStream("./text.xlsm")
//val xlWb = WorkbookFactory.create(input)
//val input = FileInputStream(bob.getPath())
val xlWb = WorkbookFactory.create(input)
Log.d("wtf","b")
//val xlWb = WorkbookFactory.create(input)
Log.d("wtf","c")
val xlWs = xlWb.getSheet("Daily Recording")
Log.d("wtf","d")
for (j in 44..50) {
for (i in 0..11) {
//Log.d("wtf",((("${xlWs.getRow(j).getCell(i)}, ")).toString()))
Log.d("wtf", "${xlWs.getRow(j).getCell(i)}, ")
}
}
}
fun ContentResolver.getFileName(fileUri: Uri): String {
var name = ""
val returnCursor = this.query(fileUri, null, null, null, null)
if (returnCursor != null) {
val nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
returnCursor.moveToFirst()
name = returnCursor.getString(nameIndex)
returnCursor.close()
}
return name
}
class MainActivity : AppCompatActivity() {
val getContent = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
// 'ActivityResultCallback': Handle the returned Uri
if (uri != null) {
Log.d("wtf",uri.getPath().toString())
val inputStream = applicationContext.contentResolver.openInputStream(uri)
readingxl(inputStream)
/*
val parcelFileDescriptor = applicationContext.contentResolver.openFileDescriptor(uri, "r", null)
parcelFileDescriptor?.let {
val inputStream = FileInputStream(parcelFileDescriptor.fileDescriptor)
val file = File(applicationContext.cacheDir, "text.xlsm")//applicationContext.contentResolver.getFileName(uri))
val outputStream = FileOutputStream(file)
IOUtils.copy(inputStream, outputStream)
}*/
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
///storage/emulated/0/Download
var button = findViewById<Button>(R.id.button)
button.setOnClickListener{
//getContent.launch("*/*")
getContent.launch("*/*")
}
}
}

App crash when i use VideoUIKit-Android Agora

when i build smaple project , app has been crashed
when i see logcat , i see this:
90-30676/io.agora.agora_android_uikit E/agora.io: jni_generator_helper.h: (line 131): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
what do i do ?
My code:
package io.agora.agora_android_uikit
import android.Manifest
import android.graphics.Color
import android.os.Bundle
import android.view.ViewGroup
import android.widget.Button
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import io.agora.agorauikit_android.AgoraButton
import io.agora.agorauikit_android.AgoraConnectionData
import io.agora.agorauikit_android.AgoraSettings
import io.agora.agorauikit_android.AgoraVideoViewer
import io.agora.agorauikit_android.requestPermission
import io.agora.rtc2.Constants
private const val PERMISSION_REQ_ID = 22
private val REQUESTED_PERMISSIONS = arrayOf<String>(
Manifest.permission.RECORD_AUDIO,
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
#ExperimentalUnsignedTypes
class MainActivity : AppCompatActivity() {
var agView: AgoraVideoViewer? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
try {
agView = AgoraVideoViewer(
this, AgoraConnectionData("*******"),
)
} catch (e: Exception) {
println("Could not initialise AgoraVideoViewer. Check your App ID is valid. ${e.message}")
return
}
val set = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT
)
this.addContentView(agView, set)
if (AgoraVideoViewer.requestPermission(this)) {
agView!!.join("test", role = Constants.CLIENT_ROLE_BROADCASTER)
} else {
val joinButton = Button(this)
// this#MainActivity.runOnUiThread(java.lang.Runnable {
runOnUiThread {
Runnable { joinButton.text = "Allow Camera and Microphone, then click here" }
}
// })
joinButton.setOnClickListener {
if (AgoraVideoViewer.requestPermission(this)) {
// (joinButton.parent as ViewGroup).removeView(joinButton)
agView!!.join("test", role = Constants.CLIENT_ROLE_BROADCASTER)
}
}
// joinButton.setBackgroundColor(Color.GREEN)
// joinButton.setTextColor(Color.RED)
this.addContentView(
joinButton,
FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, 300)
)
}
}
i want to solve my issue
Please wrap with function and make annotations there instead of mentioning in the main content view and wrap using UI thread.And refer sample github agora sdk github for reference - https://github.com/AgoraIO-Community/VideoUIKit-Android

Kotlin- Sceneform - Load .sfb models from server direct. Not working

Iam and AR android app. I can load my .sfb files from asset. i want to load from direct server in order to secure my assets. Its loading from asset folder. not from direct server. iam using below code pls help me to solve this.
package com.example.a320_ar
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import com.google.ar.core.Anchor
import com.google.ar.core.Plane
import com.google.ar.sceneform.AnchorNode
import com.google.ar.sceneform.HitTestResult
import com.google.ar.sceneform.SkeletonNode
import com.google.ar.sceneform.animation.ModelAnimator
import com.google.ar.sceneform.rendering.ModelRenderable
import com.google.ar.sceneform.ux.ArFragment
import com.google.ar.sceneform.ux.TransformableNode
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File
class MainActivity : AppCompatActivity() {
lateinit var arFragment: ArFragment
private lateinit var model: Uri
private var rendarable: ModelRenderable?=null
private var animator: ModelAnimator? = null
//private var modellink:String = "A320_Anim.sfb"
private var modellink:String = "http://10.0.0.193:90/fbx/A320_Anim.sfb"
#RequiresApi(Build.VERSION_CODES.N)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
arFragment = sceneform_fragment as ArFragment
arFragment.setOnTapArPlaneListener { hitResult, plane, motionEvent ->
if (plane.type != Plane.Type.HORIZONTAL_UPWARD_FACING) {
return#setOnTapArPlaneListener
}
var anchor = hitResult.createAnchor()
btnStart.setOnClickListener {
placeObject(
arFragment,
anchor,
Uri.parse(modellink)
)
}
}
}
#RequiresApi(Build.VERSION_CODES.N)
private fun animateModel(name: String) {
animator?.let { it->
if(it.isRunning){
it.end()
}
}
rendarable?.let { modelRenderable ->
val data = modelRenderable.getAnimationData(name)
animator = ModelAnimator(data,modelRenderable)
animator?.start()
}
}
#RequiresApi(Build.VERSION_CODES.N)
private fun placeObject(arFragment: ArFragment, anchor: Anchor?, model: Uri?) {
ModelRenderable.builder()
.setSource(arFragment.context,model)
.build()
.thenAccept{
rendarable = it
addtoScene(arFragment, anchor, it)
}
.exceptionally {
val builder = AlertDialog.Builder(this)
builder.setMessage( it.message).setTitle("Error")
val dialog = builder.create()
dialog.show()
return#exceptionally null
}
}
private fun addtoScene(arFragment: ArFragment, anchor: Anchor?, it: ModelRenderable?) {
val anchorNode = AnchorNode(anchor)
val skeletonNode = SkeletonNode()
skeletonNode.renderable = rendarable
Toast.makeText(this,"inside add scene",Toast.LENGTH_SHORT).show()
val node = TransformableNode(arFragment.transformationSystem)
node.addChild(skeletonNode)
node.setParent(anchorNode)
node.setOnTapListener { v: HitTestResult?, event: MotionEvent? ->
//msgText.text = "Tapped me...$anchorNode --- $anchor --- $skeletonNode"
// var bt = findViewById<Button>(R.id.btnDel)
//bt.visibility = View.VISIBLE
//removeAnchorNode(anchorNode)
//bt.setOnClickListener { removeAnchorNode(anchorNode) }
}
arFragment.arSceneView.scene.addChild(anchorNode)
}
}
its working fine no errors. but its not showing my object on fragment.
private var modellink:String = "http://10.0.0.193:90/fbx/A320_Anim.sfb" (not loading .sfb)
private var modellink:String = "A320_Anim.sfb" (Loading the .sfb- woring fine)
please help me to load the model directly from server. i used all the permissions correctly.
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
Thanks in advance,
Syed Abdul Rahim
Are you still using the old 1.6 version of Sceneform? You could try the new maintained version and also discard the sfb format and switch to glTF. The maintained version is up to date related to android dependencies and ARCore/Filament.
Well to your second question, if you want to secure your assets you have to serve it from a password protected API-Endpoint, but you have to host your own server, maybe some simpler solutions exists. Strings or text files can be directly secured with on board libraries (https://developer.android.com/guide/topics/security/cryptography)

How do I find the selected element from a ListView in Kotlin?

I'm trying to make an app that gets a list of contacts and puts them into a ListView. I plan on saving the phone number into a variable, but for now I have it being displayed into a Toast message so I can confirm the value is correct.
AddNewAlarm.kt
package com.example.safetybuddy
import android.content.ContentResolver
import android.database.Cursor
import android.location.Location.convert
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.ContactsContract
import android.telephony.PhoneNumberUtils
import android.view.View
import android.widget.AdapterView
import android.widget.Button
import android.widget.SimpleCursorAdapter
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.get
import kotlinx.android.synthetic.main.activity_add_new_alarm.*
import kotlinx.android.synthetic.main.activity_users.*
import java.util.logging.Logger.global
class AddNewAlarm : AppCompatActivity() {
#RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_new_alarm)
// code to make the button work
val button = findViewById<Button>(R.id.btnAdd)
button.setOnClickListener{
// populate the listView
populate()
}
// get the number when an item is clicked
listView.setOnItemClickListener{ _,_,pos,_ ->
Toast.makeText(this, listView.getItemAtPosition(pos).toString(), Toast.LENGTH_SHORT).show()
}
}
private fun populate(){
// defines the columns
var cols = listOf<String>(
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone._ID
).toTypedArray()
var from = listOf<String>(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER).toTypedArray()
var to = intArrayOf(android.R.id.text1, android.R.id.text2)
var rs = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, cols, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME) // sorts by display name
var adapter = SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, rs, from, to, 0)
listView.adapter = adapter
}
}
I am able to populate the ListView, but it doesn't display the phone numbers when I tap the item
listview.getItemAtPosition(pos) returns CursorWrapper, You have to fetch column values from CursorWrapper.
listView.setOnItemClickListener{ _,_,pos,_ ->
val cw : CursorWrapper = listView.getItemAtPosition(pos) as CursorWrapper;
val str: String = cw.getString(1);
Toast.makeText(this, str, Toast.LENGTH_SHORT).show()
}

Categories

Resources