How to use DecodeStream class of com.github.kittinunf.fuel.util package

Best Fuel code snippet using com.github.kittinunf.fuel.util.DecodeStream

Kkiapay.kt

Source:Kkiapay.kt Github

copy

Full Screen

1package co.opensi.kkiapay.uikit2import android.app.Activity3import android.content.Context4import android.content.Intent5import android.graphics.Bitmap6import android.graphics.BitmapFactory7import android.util.Log8import androidx.annotation.ColorRes9import androidx.annotation.RawRes10import androidx.appcompat.app.AppCompatActivity11import androidx.core.content.ContextCompat12import co.opensi.kkiapay.Error13import co.opensi.kkiapay.MomoPay14import co.opensi.kkiapay.STATUS15import co.opensi.kkiapay.Transaction16import co.opensi.kkiapay.uikit.KKiapayApi.Companion.checkTransactionStatus17import co.opensi.kkiapay.uikit.Me.Companion.KKIAPAY_REQUEST_CODE18import co.opensi.kkiapay.uikit.Me.Companion.KKIAPAY_URL19import co.opensi.kkiapay.uikit.SandBoxKKiapayApi.Companion.sandboxCheckTransactionStatus20import com.github.kittinunf.fuel.Fuel21import com.github.kittinunf.fuel.core.FileDataPart22import com.github.kittinunf.fuel.core.HeaderValues23import com.github.kittinunf.fuel.core.Method24import com.github.kittinunf.fuel.core.Parameters25import com.github.kittinunf.fuel.core.requests.upload26import com.github.kittinunf.fuel.util.FuelRouting27import com.google.gson.Gson28import org.apache.commons.codec.binary.Base6429import org.json.JSONObject30import java.io.ByteArrayInputStream31import java.io.ByteArrayOutputStream32import java.io.File33import java.io.FileOutputStream34import java.util.*35/**36 * @author Armel FAGBEDJI ( armel.fagbedji@opensi.co )37 * created at 01/03/201938 */39object Kkiapay{40 private lateinit var me: Me41 /**42 * Initialize SDK.43 * This function didn't check your API keys but keep it for future requests44 * @param apiKey developer prod / test API keys check https://kkiapay.me45 * @param context Application Context46 * @param sdkConfig SDK configurations. It is optional47 */48 @JvmOverloads49 @JvmStatic50 fun init(context: Context,51 apiKey:String,52 sdkConfig: SdkConfig = SdkConfig()) {53 me = Me(context, apiKey, sdkConfig)54 }55 /**56 * Recover the Kkiapay instance to perform actions57 * @return [Me] Instance of Kkiapay58 * @exception [IllegalAccessException] If the SDK was not initialized before use59 */60 @JvmStatic61 fun get(): Me {62 if (!Kkiapay::me.isInitialized)63 throw IllegalAccessException("You must initialise Kkiapay SDK in the onCreate methode of your App's" +64 " Application first")65 return me66 }67}68class Me internal constructor(context: Context, private val apiKey: String, private val sdkConfig: SdkConfig) {69 private var requestPaymentAction: RequestPaymentAction? = null70 private var sdkListener: ((STATUS, String?) -> Unit)? = null71 /**72 * MomoPay Instance73 */74 val momoPay: MomoPay75 init {76 KKiapayApi.apiKey = apiKey77 sdkConfig.run {78 convertColorToString(context)79 convertImageResToImageUrl(context)80 }81 momoPay = MomoPay(apiKey)82 }83 /**84 * Make a payment request85 * @param activity Payment activity86 * @param amount Amount to be paid87 * @param reason Payment description88 * @param name The name of the client89 * @param phone The customer's phone number90 * @param sandbox Make request on sandbox91 * @param data The callback redirect data92 * @exception [IllegalAccessException] If a listener was not configured on the UI-SDK93 */94 @JvmOverloads95 fun requestPayment(activity: AppCompatActivity,96 amount: String,97 reason: String,98 name: String,99 phone: String = "",100 callback: String = KKIAPAY_REDIRECT_URL,101 data: String = "",102 sandbox: Boolean = sdkConfig.enableSandbox103 ){104 sdkListener ?: throw IllegalAccessException("Sdk Listener is null, you must setup one before the call of" +105 " \"requestPayment\" methode")106 sdkConfig.enableSandbox = sandbox107 KKIAPAY_REDIRECT_URL = callback108 val user = User(amount, reason, name, apiKey, callback, phone, sandbox = sandbox, data = data)109 requestPaymentAction = RequestPaymentAction(user)110 requestPaymentAction?.invoke(activity, sdkConfig)111 }112 /**113 * Configure a listener for the UI-SDK, to manage the information returned by the latter114 * @param listener mandatory115 */116 fun setListener(listener: (STATUS, String?) -> Unit): Me {117 sdkListener = listener118 return this119 }120 /**121 * Remove UI-SDK listener122 */123 fun removeSdkListener(){124 sdkListener = null125 }126 /**127 * To call in onActivityResult of your activity to manage the return response128 * the UI-SDK using the [sdkListener] which was initially informed129 */130 fun handleActivityResult(requestCode: Int, resultCode: Int, data: Intent?){131 if (requestCode == KKIAPAY_REQUEST_CODE && resultCode == Activity.RESULT_OK){132 data?.run {133 if (hasExtra(KKIAPAY_TRANSACTION_ID)){134 val transactionId = getStringExtra(KKIAPAY_TRANSACTION_ID)135 transactionId?.let {136 (if (sdkConfig.enableSandbox) ::sandboxCheckTransactionStatus137 else ::checkTransactionStatus).invoke(it)138 .responseString { _, _, result ->139 result.fold({ resutlString ->140 val transaction = Gson().fromJson<Transaction>(resutlString, Transaction::class.java)141 sdkListener?.invoke(when(transaction.status){142 "SUCCESS" -> STATUS.SUCCESS143 "INVALID_TRANSACTION" -> STATUS.INVALID_TRANSACTION144 "TRANSACTION_NOT_FOUND" -> STATUS.TRANSACTION_NOT_FOUND145 "FAILED" -> STATUS.FAILED146 else -> STATUS.UNKNOWN147 },148 transaction.transactionId)149 }){fuelError ->150 Log.i("Kkiapay.me", fuelError.toString())151 val theError = Gson().fromJson<Error>(String(fuelError.errorData), Error::class.java)152 theError?.let {error ->153 sdkListener?.invoke(when(error.status) {154 4001 -> STATUS.INVALID_PHONE_NUMBER155 4003 -> STATUS.INVALID_API_KEY156 else -> STATUS.FAILED157 }, null)158 } ?: kotlin.run {159 sdkListener?.invoke(STATUS.FAILED, null)160 }161 }162 }163 } ?: kotlin.run {164 sdkListener?.invoke(STATUS.SUCCESS, null)165 }166 } else167 sdkListener?.invoke(STATUS.SUCCESS, null)168 } ?: let {169 sdkListener?.invoke(STATUS.SUCCESS, null)170 }171 } else{172 sdkListener?.invoke(STATUS.FAILED, null)173 }174 }175 companion object {176 internal const val KKIAPAY_URL = "https://widget-v2.kkiapay.me"177 internal var KKIAPAY_REDIRECT_URL = "http://redirect.kkiapay.me"178 const val KKIAPAY_REQUEST_CODE = 0xABC179 internal const val KKIAPAY_TRANSACTION_ID = "me.kkiapay.uikit.KKIAPAY_TRANSACTION_ID"180 }181}182/**183 * Configure and customize the UI-SDK.184 * Possibility to configure the color [themeColor]185 * and the shop logo [imageResource]186 */187data class SdkConfig(@RawRes private val imageResource: Int = -1, @ColorRes internal val themeColor: Int = -1, var enableSandbox: Boolean = false){188 internal var imageUrl: String = ""189 internal var color: String = ""190 internal fun convertColorToString(context: Context){191 if (themeColor != -1){192 color = String.format("#%06x", ContextCompat.getColor(context, themeColor) and 0xffffff)193 Log.i("Kkiapay.me", color)194 }195 }196 internal fun convertImageResToImageUrl(context: Context){197 if (imageResource != -1){198 val stream = context.resources.openRawResource(imageResource)199 var bitmap = BitmapFactory.decodeStream(stream)200 bitmap = reduceBitmap(bitmap)201 val file = File(context.cacheDir, "${UUID.randomUUID()}.png")202 FileOutputStream(file).use {203 bitmap.compress(Bitmap.CompressFormat.PNG, 0, it)204 it.flush()205 }206 KKiapayApi.uploadFile(file)207 ?.responseString { _, _, result ->208 result.fold({resutlString ->209 val uploadKey = Gson().fromJson<List<Map<String, String>>>(resutlString, List::class.java)210 .first()["fd"]?.trim()211 imageUrl = KKiapayApi.getUploadedFile(uploadKey)?.url?.toString() ?: ""212 }){213 Log.e("Kkiapay.me", it.toString())214 }215 }216 }217 }218 private fun reduceBitmap(original: Bitmap): Bitmap {219 val out = ByteArrayOutputStream()220 original.compress(Bitmap.CompressFormat.WEBP, 100, out)221 return BitmapFactory.decodeStream(ByteArrayInputStream(out.toByteArray()))222 }223}224internal class RequestPaymentAction(private val user: User) {225 operator fun invoke(activity: AppCompatActivity, sdkConfig: SdkConfig){226 activity.startActivityForResult(227 Intent(activity, CustomTabActivity::class.java).apply {228 putExtra(CustomTabActivity.EXTRA_URL,229 "$KKIAPAY_URL/?=${user.toBase64(activity.applicationContext, sdkConfig)}")230 putExtra(CustomTabActivity.EXTRA_THEME,231 sdkConfig.themeColor)232 }, KKIAPAY_REQUEST_CODE)233 }234}235internal data class User(val amount: String = "",236 val reason: String = "",237 val name: String = "",238 val key: String = "",239 val callback: String,240 val phone: String = "",241 val sdk: String = "android",242 val theme: String = "",243 val url: String = "",244 val sandbox: Boolean,245 val host: String? = "",246 val data: String = ""247) {248 fun toBase64(context: Context, sdkConfig: SdkConfig) : String{249 val preConvertion = this.copy(250 theme = sdkConfig.color,251 url = sdkConfig.imageUrl,252 host = context.applicationContext.packageName253 )254 val userJson = Gson().toJson(preConvertion).toString()255 return String(Base64.encodeBase64(userJson.toByteArray()))256 }257}258private sealed class SandBoxKKiapayApi : FuelRouting {259 override val basePath: String260 get() = "https://api-sandbox.kkiapay.me"261 override val headers: Map<String, HeaderValues>?262 get() = mapOf("x-api-key" to listOf(KKiapayApi.apiKey))263 override val method: Method264 get() = Method.POST265 override val body: String?266 get() = null267 override val bytes: ByteArray?268 get() = null269 override val params: Parameters?270 get() = emptyList()271 private class SandBoxCheckTansactionStatus(private val transactionId: String): SandBoxKKiapayApi() {272 override val path: String273 get() = "/api/v1/transactions/status"274 override val headers: Map<String, HeaderValues>?275 get() = super.headers?.plus("Content-Type" to listOf("application/json"))276 override val body: String?277 get() = JSONObject().putOpt("transactionId", transactionId).toString()278 }279 companion object {280 internal fun sandboxCheckTransactionStatus(transactionId: String) =281 Fuel.request(SandBoxCheckTansactionStatus(transactionId))282 }283}284private sealed class KKiapayApi : FuelRouting {285 override val basePath: String286 get() = "https://api.kkiapay.me"287 override val headers: Map<String, HeaderValues>?288 get() = mapOf("x-api-key" to listOf(apiKey))289 override val method: Method290 get() = Method.POST291 override val body: String?292 get() = null293 override val bytes: ByteArray?294 get() = null295 override val params: Parameters?296 get() = emptyList()297 private class UploadFile(private val classification: String = "android_client_store_icon"): KKiapayApi(){298 override val path: String299 get() = "/utils/upload"300 override val params: List<Pair<String, Any?>>?301 get() = listOf("type" to classification)302 }303 private class CheckTansactionStatus(private val transactionId: String): KKiapayApi() {304 override val path: String305 get() = "/api/v1/transactions/status"306 override val headers: Map<String, HeaderValues>?307 get() = super.headers?.plus("Content-Type" to listOf("application/json"))308 override val body: String?309 get() = JSONObject().putOpt("transactionId", transactionId).toString()310 }311 private class GetUploadedFile(private val fileKey: String): KKiapayApi() {312 override val path: String313 get() = "/utils/file/$fileKey"314 override val method: Method315 get() = Method.GET316 }317 companion object {318 internal lateinit var apiKey: String319 internal fun uploadFile(file: File?) =320 file?.run { Fuel.request(UploadFile())321 .upload()322 .add { FileDataPart(this, name = "file") } }323 internal fun checkTransactionStatus(transactionId: String) =324 Fuel.request(CheckTansactionStatus(transactionId))325 internal fun getUploadedFile(fileKey: String?) =326 fileKey?.run{327 Fuel.request(GetUploadedFile(fileKey))328 }329 }330}...

Full Screen

Full Screen

AdminActivity.kt

Source:AdminActivity.kt Github

copy

Full Screen

1package com.example.projecthomedecor2import android.Manifest3import android.R.attr4import android.app.Activity5import android.content.ClipData6import android.content.ClipboardManager7import android.content.Context8import android.content.Intent9import android.content.pm.PackageManager10import android.graphics.Bitmap11import android.graphics.BitmapFactory12import android.net.Uri13import java.io.ByteArrayOutputStream14import android.opengl.ETC1.encodeImage15import android.os.Build16import android.os.Bundle17import android.util.Base6418import android.view.MenuItem19import android.view.View20import android.widget.Toast21import androidx.appcompat.app.AppCompatActivity22import com.github.kittinunf.fuel.Fuel23import com.github.kittinunf.fuel.core.Headers24import kotlinx.android.synthetic.main.fragment_add_items_admin.*25import kotlinx.android.synthetic.main.fragment_login.*26import java.io.File27import java.io.InputStream28class AdminActivity : AppCompatActivity() {29 override fun onCreate(savedInstanceState: Bundle?) {30 super.onCreate(savedInstanceState)31 setContentView(R.layout.activity_admin)32 if (savedInstanceState == null) {33 supportFragmentManager.beginTransaction().add(34 R.id.adminframe,35 AdminMenuFragment()36 ).addToBackStack(null).commit()37 }38 }39 var imgnum: String? = null40 var img1Uri: Uri? = null41 var img2Uri: Uri? = null42 var img3Uri: Uri? = null43 fun goaddproductstock(item: MenuItem) {44 supportFragmentManager.beginTransaction().add(45 R.id.adminframe,46 AddItemsAdminFragment()47 ).commit()48 }49 fun addimage1(view: View) {50 imgnum = "pic1"51 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {52 if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) ==53 PackageManager.PERMISSION_DENIED54 ) {55 //permission denied56 val permissions = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE);57 //show popup to request runtime permission58 requestPermissions(permissions, PERMISSION_CODE);59 } else {60 //permission already granted61 pickImageFromGallery();62 }63 } else {64 //system OS is < Marshmallow65 pickImageFromGallery();66 }67 }68 fun addimage2(view: View) {69 imgnum = "pic2"70 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {71 if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) ==72 PackageManager.PERMISSION_DENIED73 ) {74 //permission denied75 val permissions = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE);76 //show popup to request runtime permission77 requestPermissions(permissions, PERMISSION_CODE);78 } else {79 //permission already granted80 pickImageFromGallery();81 }82 } else {83 //system OS is < Marshmallow84 pickImageFromGallery();85 }86 }87 fun addimage3(view: View) {88 imgnum = "pic3"89 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {90 if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) ==91 PackageManager.PERMISSION_DENIED92 ) {93 //permission denied94 val permissions = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE);95 //show popup to request runtime permission96 requestPermissions(permissions, PERMISSION_CODE);97 } else {98 //permission already granted99 pickImageFromGallery();100 }101 } else {102 //system OS is < Marshmallow103 pickImageFromGallery();104 }105 }106 private fun pickImageFromGallery() {107 //Intent to pick image108 val intent = Intent(Intent.ACTION_PICK)109 intent.type = "image/*"110 startActivityForResult(intent, IMAGE_PICK_CODE)111 }112 companion object {113 //image pick code114 private val IMAGE_PICK_CODE = 1000;115 //Permission code116 private val PERMISSION_CODE = 1001;117 }118 //handle requested permission result119 override fun onRequestPermissionsResult(120 requestCode: Int,121 permissions: Array<out String>,122 grantResults: IntArray123 ) {124 when (requestCode) {125 PERMISSION_CODE -> {126 if (grantResults.size > 0 && grantResults[0] ==127 PackageManager.PERMISSION_GRANTED128 ) {129 //permission from popup granted130 pickImageFromGallery()131 } else {132 //permission from popup denied133 Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show()134 }135 }136 }137 }138 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {139 super.onActivityResult(requestCode, resultCode, data)140 if (resultCode == Activity.RESULT_OK && requestCode == IMAGE_PICK_CODE) {141 if (imgnum == "pic1") {142 imageView.setImageURI(data?.data)143 img1Uri = data?.data144 }145 if (imgnum == "pic2") {146 image2.setImageURI(data?.data)147 img2Uri = data?.data148 }149 if (imgnum == "pic3") {150 image3.setImageURI(data?.data)151 img3Uri = data?.data152 }153 var mos = data?.data154 var a = mos?.path as String155 DatabaseApi156 }157 }158 private fun encodeImage(bm: Bitmap): String? {159 val baos = ByteArrayOutputStream()160 bm.compress(Bitmap.CompressFormat.JPEG, 100, baos)161 val b = baos.toByteArray()162 return Base64.encodeToString(b, Base64.DEFAULT)163 }164 fun btn_delete_image1(view: View) {165 imageView.setImageResource(0)166 img1Uri = null167 }168 fun btn_delete_image2(view: View) {169 image2.setImageResource(0)170 img2Uri = null171 }172 fun btn_delete_image3(view: View) {173 image3.setImageResource(0)174 img3Uri = null175 }176 fun btn_save_add_product(view: View) {177 if (img1Uri == null) {178 //Toast.makeText(applicationContext, "มึงต้องใส่รูปแรกนะ", Toast.LENGTH_LONG).show()179 return180 }181 var typeArray = arrayListOf<Int>()182 var type_product_add: String = ""183 if (cb_bedroom.isChecked) {184 typeArray.add(1)185 type_product_add += " " + cb_bedroom.text;186 }187 if (cb_workroom.isChecked) {188 typeArray.add(2)189 type_product_add += " " + cb_workroom.text;190 }191 if (cb_chickenroom.isChecked) {192 typeArray.add(3)193 type_product_add += " " + cb_chickenroom.text;194 }195 if (cb_storeroom.isChecked) {196 typeArray.add(4)197 type_product_add += " " + cb_storeroom.text;198 }199 if (cb_livingroom.isChecked) {200 typeArray.add(5)201 type_product_add += " " + cb_livingroom.text;202 }203 if (cb_bathroom.isChecked) {204 typeArray.add(6)205 type_product_add += " " + cb_bathroom.text;206 }207 if (cb_drawingroom.isChecked) {208 typeArray.add(7)209 type_product_add += " " + cb_drawingroom.text;210 }211 if (cb_foodroom.isChecked) {212 typeArray.add(8)213 type_product_add += " " + cb_foodroom.text;214 }215 var type_product_add_new =216 if (type_product_add.isNotEmpty()) type_product_add else "Please select type product."217 var name_product = add_nameitem.text.toString()218 var price_product = add_priceitem.text.toString().toInt()219 var balance_stock = add_warehouseitem.text.toString().toInt()220 var imgLink = arrayListOf<Int>()221 if (img1Uri != null) {222 imgLink.add(1)223 }224 if (img2Uri != null) {225 imgLink.add(2)226 }227 if (img3Uri != null) {228 imgLink.add(3)229 }230 var productid = DatabaseApi.addProduct(231 name_product,232 price_product.toFloat(),233 imgLink.toString(),234 typeArray.toString(),235 balance_stock236 )237 if (img1Uri != null) {238 val imageStream: InputStream? = contentResolver.openInputStream(img1Uri!!)239 val selectedImage = BitmapFactory.decodeStream(imageStream)240 val encodedImage = encodeImage(selectedImage) as String241 Fuel.post("http://pc.mosmai.me:10080/product.php?tokenid=${Global.accessToken.toString()}&product_id=${productid}&img_num=1")242 .header(Headers.CONTENT_TYPE, "application/json")243 .body("${encodedImage}")244 .also { println(it) }245 .response { result ->246 Toast.makeText(247 applicationContext,248 result.toString(),249 Toast.LENGTH_LONG250 ).show()251 }252 }253 if (img2Uri != null) {254 val imageStream: InputStream? = contentResolver.openInputStream(img2Uri!!)255 val selectedImage = BitmapFactory.decodeStream(imageStream)256 val encodedImage = encodeImage(selectedImage) as String257 Fuel.post("http://pc.mosmai.me:10080/product.php?tokenid=${Global.accessToken.toString()}&product_id=${productid}&img_num=2")258 .header(Headers.CONTENT_TYPE, "application/json")259 .body("${encodedImage}")260 .also { println(it) }261 .response { result ->262 Toast.makeText(263 applicationContext,264 result.toString(),265 Toast.LENGTH_LONG266 ).show()267 }268 }269 if (img3Uri != null) {270 val imageStream: InputStream? = contentResolver.openInputStream(img3Uri!!)271 val selectedImage = BitmapFactory.decodeStream(imageStream)272 val encodedImage = encodeImage(selectedImage) as String273 Fuel.post("http://pc.mosmai.me:10080/product.php?tokenid=${Global.accessToken.toString()}&product_id=${productid}&img_num=3")274 .header(Headers.CONTENT_TYPE, "application/json")275 .body("${encodedImage}")276 .also { println(it) }277 .response { result ->278 Toast.makeText(279 applicationContext,280 result.toString(),281 Toast.LENGTH_LONG282 ).show()283 }284 }285 supportFragmentManager.popBackStack()286 }287 fun goeditproducestock(item: MenuItem) {288 supportFragmentManager.beginTransaction().add(289 R.id.adminframe,290 SearchEditItemAdminFragment()291 ).addToBackStack(null).commit()292 }293 fun gocheckorder(item: MenuItem) {294 supportFragmentManager.beginTransaction().add(295 R.id.adminframe,296 CheckStatusOrderAdminFragment()297 ).addToBackStack(null).commit()298 }299}...

Full Screen

Full Screen

UpdateRecommendationsService.kt

Source:UpdateRecommendationsService.kt Github

copy

Full Screen

1package com.hackathon.iitb.services2import android.app.*3import android.content.Context4import android.content.Intent5import android.util.Log6import com.hackathon.iitb.model.Show7import android.support.v4.app.NotificationCompat8import com.hackathon.iitb.R9import java.io.IOException10import android.graphics.BitmapFactory11import android.graphics.Bitmap12import android.preference.PreferenceManager13import android.util.Base6414import com.github.kittinunf.fuel.Fuel15import com.github.kittinunf.fuel.core.FuelManager16import com.github.kittinunf.fuel.core.Request17import com.google.gson.Gson18import com.google.gson.reflect.TypeToken19import com.hackathon.iitb.DetailsActivity20import com.hackathon.iitb.model.password21import com.hackathon.iitb.model.server22import com.hackathon.iitb.model.username23import com.hackathon.iitb.receivers.MyReceiver24import org.jetbrains.anko.runOnUiThread25import java.net.HttpURLConnection26import java.net.URL27class UpdateRecommendationsService : IntentService("UpdateRecommendationsService") {28 private val MAX_RECOMMENDATIONS = 329 private val mNotificationManager by lazy { getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager }30 override fun onHandleIntent(intent: Intent?) {31 val prefs = PreferenceManager.getDefaultSharedPreferences(this)32 val value = Gson().fromJson<ArrayList<Long>>(33 prefs.getString("ignore_list", "[]"),34 object : TypeToken<ArrayList<Long>>() {}.type35 )36 val base64 = Base64.encodeToString("$username:$password".toByteArray(), Base64.NO_WRAP)37 FuelManager.instance.baseHeaders = mapOf("Authorization" to "Basic $base64")38 val x: Request = Fuel.get("http://$server/api/recommendation/shows/?format=json")39 x.response { _, _, result ->40 val z = String(result.get())41 Log.d("suthar", "Body: $z")42 val recommendations = Gson().fromJson<ArrayList<Show>>(z, object : TypeToken<ArrayList<Show>>() {}.type)43 var count = 044 for (show in recommendations) {45 if (value.contains(show.id)) {46 Log.d("suthar", "Ignored Show")47 continue48 }49 val image = getBitmapFromURL(show.image_url)50 runOnUiThread {51 val priority = MAX_RECOMMENDATIONS - count52 val builder =53 NotificationCompat.Builder(applicationContext, "What's New")54 .setContentTitle(show.name)55 .setContentText("Watch Now")56 .setPriority(priority)57 .setLocalOnly(true)58 .setAutoCancel(true)59 .setColor(applicationContext.resources.getColor(R.color.fastlane_background))60 .setCategory(Notification.CATEGORY_RECOMMENDATION)61 .setLargeIcon(image)62 .setStyle(NotificationCompat.BigPictureStyle().bigPicture(image))63 .setSmallIcon(android.R.drawable.ic_menu_report_image) //Change this icon64 .setContentIntent(buildPendingIntent(show))65 .addAction(66 android.R.drawable.alert_light_frame,67 "Ignore",68 buildPendingIntent("ignore", show)69 )70 .addAction(71 android.R.drawable.alert_light_frame,72 "Remind Later",73 buildPendingIntent("remind", show)74 )75 //.setExtras(extras)76 val notification = builder.build()77 mNotificationManager.notify(show.id.toInt(), notification)78 }79 if (++count >= MAX_RECOMMENDATIONS) {80 break81 }82 }83 }84 }85 private fun buildPendingIntent(show: Show): PendingIntent {86 val detailsIntent = Intent(this, DetailsActivity::class.java)87 detailsIntent.putExtra("Movie", show)88 val stackBuilder = TaskStackBuilder.create(this)89 stackBuilder.addParentStack(DetailsActivity::class.java)90 stackBuilder.addNextIntent(detailsIntent)91 // Ensure a unique PendingIntents, otherwise all92 // recommendations end up with the same PendingIntent93 detailsIntent.action = java.lang.Long.toString(show.id)94 return stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)95 }96 private fun buildPendingIntent(action: String, show: Show): PendingIntent {97 val intent = Intent(this, MyReceiver::class.java)98 intent.action = action99 intent.putExtra("show", show)100 return PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)101 }102 private fun getBitmapFromURL(src: String): Bitmap? {103 return try {104 val url = URL(src)105 val connection = url.openConnection() as HttpURLConnection106 connection.doInput = true107 connection.connect()108 val input = connection.inputStream109 BitmapFactory.decodeStream(input)110 } catch (e: IOException) {111 // Log exception112 null113 }114 }115}...

Full Screen

Full Screen

MainActivity.kt

Source:MainActivity.kt Github

copy

Full Screen

1package com.monolith.picturetest2import android.content.Intent3import android.graphics.Bitmap4import android.graphics.BitmapFactory5import android.os.Bundle6import android.os.Handler7import android.util.Base648import android.widget.Button9import android.widget.ImageView10import android.widget.Toast11import androidx.appcompat.app.AppCompatActivity12import com.github.kittinunf.fuel.httpPost13import com.github.kittinunf.result.Result14import java.io.ByteArrayOutputStream15import java.io.File16class MainActivity : AppCompatActivity() {17 var image: Bitmap? = null18 override fun onCreate(savedInstanceState: Bundle?) {19 super.onCreate(savedInstanceState)20 setContentView(R.layout.activity_main)21 var pictureButton: Button = findViewById(R.id.btnLoad)22 var clearButton: Button = findViewById(R.id.btnClear)23 var convertButton: Button = findViewById(R.id.btnConvert)24 var reconvertButton: Button = findViewById(R.id.btnReconvert)25 var connectButton: Button = findViewById(R.id.btnConnect)26 //ボタンが押されたらギャラリーを開く27 pictureButton.setOnClickListener {28 val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {29 addCategory(Intent.CATEGORY_OPENABLE)30 type = "image/*"31 }32 startActivityForResult(intent, READ_REQUEST_CODE)33 }34 clearButton.setOnClickListener {35 ImageClear()36 }37 convertButton.setOnClickListener {38 Convert()39 }40 reconvertButton.setOnClickListener {41 ReConvert()42 }43 connectButton.setOnClickListener {44 Connect()45 }46 }47 //READ_REQUEST_CODEの定義48 companion object {49 private const val READ_REQUEST_CODE: Int = 4250 }51 //写真が選択された後の動き52 override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {53 super.onActivityResult(requestCode, resultCode, resultData)54 if (resultCode != RESULT_OK) {55 return56 }57 when (requestCode) {58 READ_REQUEST_CODE -> {59 try {60 resultData?.data?.also { uri ->61 val inputStream = contentResolver?.openInputStream(uri)62 image = Bitmap.createScaledBitmap(63 BitmapFactory.decodeStream(inputStream),64 250,65 250,66 true67 )68 val imageView = findViewById<ImageView>(R.id.imageView)69 imageView.setImageBitmap(image)70 }71 } catch (e: Exception) {72 Toast.makeText(this, "エラーが発生しました", Toast.LENGTH_LONG).show()73 }74 }75 }76 }77 //画面上の画像データを削除78 fun ImageClear() {79 val imageView = findViewById<ImageView>(R.id.imageView)80 imageView.setImageIcon(null)81 }82 //画面上の画像を保存しtxtデータに変換83 fun Convert(){84 /*val file = File("$filesDir", "pictureBuffer.png")85 FileOutputStream(file).use { fileOutputStream ->86 image!!.compress(Bitmap.CompressFormat.PNG, 50, fileOutputStream)87 fileOutputStream.flush()88 }89 val newFile = File("$filesDir", "pictureBuffer.txt")90 file.renameTo(newFile)*/91 val baos = ByteArrayOutputStream()92 image!!.compress(Bitmap.CompressFormat.PNG, 100, baos)93 val b = baos.toByteArray()94 FileWrite(Base64.encodeToString(b, Base64.NO_WRAP))95 }96 //保存されたtxtデータをpngに変換し画面に表示97 fun ReConvert() {98 val file = File("$filesDir", "pictureBuffer.txt")99 val newFile = File("$filesDir", "pictureBuffer.png")100 file.renameTo(newFile)101 val buf: Bitmap = BitmapFactory.decodeFile("$filesDir/pictureBuffer.png")102 Handler().post {103 findViewById<ImageView>(R.id.imageView).setImageBitmap(buf)104 }105 }106 fun setStringImage(data: String) {107 val decodedByte: ByteArray = Base64.decode(data, 0)108 val buf= BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.size)109 findViewById<ImageView>(R.id.imageView).setImageBitmap(buf)110 }111 fun Connect() {112 val POSTDATA = HashMap<String, String>()113 POSTDATA.put("", "")114 "https://compass-user.work/s.php".httpPost(POSTDATA.toList())115 .response { _, response, result ->116 when (result) {117 is Result.Success -> {118 setStringImage(String(response.data))119 }120 is Result.Failure -> {121 }122 }123 }124 }125 fun FileWrite(str: String) {126 var strbuf=str.replace("<br />","")127 val file = File("$filesDir/", "pictureBuffer.txt")128 file.writeText(strbuf)129 }130}...

Full Screen

Full Screen

LearningDetailContentsFragment.kt

Source:LearningDetailContentsFragment.kt Github

copy

Full Screen

1package com.example.awsclflearning.Fragment2import android.graphics.Bitmap3import android.graphics.BitmapFactory4import android.os.Bundle5import android.view.LayoutInflater6import android.view.Menu7import android.view.MenuInflater8import android.view.MenuItem9import android.view.View10import android.view.ViewGroup11import android.webkit.WebResourceRequest12import android.webkit.WebView13import android.webkit.WebViewClient14import com.example.awsclflearning.R15import com.example.awsclflearning.Util.FirebaseAnalyticsUtil16import com.github.kittinunf.result.Result.Success17import com.github.kittinunf.fuel.httpGet18import com.github.kittinunf.result.Result.Failure19import kotlinx.android.synthetic.main.fragment_learning_detail_contents.*20class LearningDetailContentsFragment(21 _learningTitle: String,22 _learningContent: String,23 _learningContentImageUrl: String24) : BaseFragment() {25 val learningTitle = _learningTitle26 val learningContent = _learningContent27 val learningContentImageUrl = _learningContentImageUrl28 var isFavorite: Boolean = false29 override fun onCreateView(30 inflater: LayoutInflater, container: ViewGroup?,31 savedInstanceState: Bundle?32 ): View? {33 FirebaseAnalyticsUtil.recordScreenView(getString(R.string.firebase_screen_name_aws_learning_detail))34 setHasOptionsMenu(true)35 return inflater.inflate(R.layout.fragment_learning_detail_contents, container, false)36 }37 override fun onViewCreated(view: View, savedInstanceState: Bundle?) {38 super.onViewCreated(view, savedInstanceState)39 if (learningContent.contains("https://")) {40 learning_scroll_view.visibility = View.GONE41 webview.loadUrl(learningContent)42 webview.setWebViewClient(object: WebViewClient() {43 override fun shouldOverrideUrlLoading(44 view: WebView?,45 request: WebResourceRequest?46 ): Boolean {47 return false48 }49 override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {50 super.onPageStarted(view, url, favicon)51 loading_progress_bar.visibility = View.VISIBLE52 }53 override fun onPageFinished(view: WebView?, url: String?) {54 super.onPageFinished(view, url)55 loading_progress_bar.visibility = View.GONE56 }57 })58 } else {59 webview.visibility = View.GONE60 learning_title.text = learningTitle61 learning_content.text = learningContent62 setupLearningContentImage()63 }64 }65 /** ToolBarのオプション項目をセット **/66 override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {67 inflater.inflate(R.menu.learning_detail_contents_menu, menu)68 }69 /** ToolBarのオプションタップ時の処理 **/70 override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {71 R.id.favorite -> {72 if (!isFavorite) {73 item.setIcon(R.drawable.ic_baseline_star_24)74 isFavorite = true75 } else {76 item.setIcon(R.drawable.ic_baseline_star_outline_24)77 isFavorite = false78 }79 true80 }81 else -> {82 super.onOptionsItemSelected(item)83 }84 }85 fun setupLearningContentImage() {86 // UrlがNullか空文字の場合はNoImage87 if (learningContentImageUrl.isNullOrEmpty()) {88 learning_content_img.setImageResource(R.drawable.no_img)89 return90 }91 val async = learningContentImageUrl.httpGet().response { request, response, result ->92 when (result) {93 is Success -> {94 val bitmap = BitmapFactory.decodeStream(response.body().toStream())95 learning_content_img.setImageBitmap(bitmap)96 }97 is Failure -> {98 // Urlが不正で画像取得できない場合はNoImage99 learning_content_img.setImageResource(R.drawable.no_img)100 }101 }102 }103 async.join()104 }105}...

Full Screen

Full Screen

MarkdownImageGetter.kt

Source:MarkdownImageGetter.kt Github

copy

Full Screen

1package gitlin.kothub.utilities.markdown2import android.content.Context3import android.graphics.BitmapFactory4import android.graphics.Canvas5import android.graphics.drawable.BitmapDrawable6import android.graphics.drawable.Drawable7import android.os.AsyncTask8import android.text.Html9import android.text.Html.ImageGetter10import android.util.Log11import android.view.View12import com.github.kittinunf.fuel.Fuel13import gitlin.kothub.R14import java.io.InputStream15class MarkdownImageGetter(val context: Context) : Html.ImageGetter {16 override fun getDrawable(source: String): Drawable {17 val response = Fuel.get(source).response()18 val data = response.third.get()19 Log.i("MarkdownImageGetter", source)20 Log.i("MarkdownImageGetter", data.contentToString())21 val bitmap = BitmapFactory.decodeStream(data.inputStream())22 if (bitmap == null) {23 return context.resources.getDrawable(R.drawable.abc_spinner_mtrl_am_alpha)24 }25 val drawable = BitmapDrawable(context.resources, bitmap)26 drawable.setBounds(0, 0, bitmap.width, bitmap.height)27 return drawable28 }29}30class UrlImageParser(internal var container: View, internal var c: Context) : ImageGetter {31 override fun getDrawable(source: String): Drawable {32 val urlDrawable = UrlDrawable()33 // get the actual source34 val asyncTask = ImageGetterAsyncTask(urlDrawable)35 asyncTask.execute(source)36 // return reference to URLDrawable where I will change with actual image from37 // the src tag38 return urlDrawable39 }40 inner class ImageGetterAsyncTask(internal var urlDrawable: UrlDrawable) : AsyncTask<String, Void, Drawable>() {41 override fun doInBackground(vararg params: String): Drawable? {42 val source = params[0]43 return fetchDrawable(source)44 }45 override fun onPostExecute(result: Drawable?) {46 if (result == null) {47 urlDrawable.drawable = null48 }49 else {50 // set the correct bound according to the result from HTTP call51 urlDrawable.setBounds(0, 0, 0 + result!!.intrinsicWidth, 0 + result!!.intrinsicHeight)52 // change the reference of the current drawable to the result53 // from the HTTP call54 urlDrawable.drawable = result55 // redraw the image by invalidating the container56 this@UrlImageParser.container.invalidate()57 }58 }59 /***60 * Get the Drawable from URL61 * @param urlString62 * *63 * @return64 */65 fun fetchDrawable(urlString: String): Drawable? {66 try {67 val `is` = fetch(urlString)68 val drawable = Drawable.createFromStream(`is`, "src")69 drawable.setBounds(0, 0, 0 + drawable.intrinsicWidth, 0 + drawable.intrinsicHeight)70 return drawable71 } catch (e: Exception) {72 return null73 }74 }75 private fun fetch(urlString: String): InputStream {76 return Fuel.get(urlString).response().third.get().inputStream()77 }78 }79 inner class UrlDrawable : BitmapDrawable() {80 // the drawable that you need to set, you could set the initial drawing81 // with the loading image if you need to82 var drawable: Drawable? = null83 override fun draw(canvas: Canvas) {84 // override the draw to facilitate refresh function later85 if (drawable != null) {86 drawable?.draw(canvas)87 }88 }89 }90}...

Full Screen

Full Screen

Image.kt

Source:Image.kt Github

copy

Full Screen

1package fr.niels.epicture.model2import android.content.res.Resources3import android.graphics.Bitmap4import android.graphics.BitmapFactory5import android.graphics.drawable.BitmapDrawable6import android.graphics.drawable.Drawable7import android.graphics.drawable.GradientDrawable8import com.github.kittinunf.fuel.core.ResponseDeserializable9import com.google.gson.Gson10import com.google.gson.annotations.SerializedName11import org.json.JSONArray12import org.json.JSONObject13import java.io.IOException14import java.net.HttpURLConnection15import java.net.URL16import java.util.*17class Image : Observable() {18 var id: String = ""19 var title: String = ""20 set(value) {21 field = value22 setChangedAndNotify("title")23 }24 var type: String = ""25 set(value) {26 field = value27 setChangedAndNotify("type")28 }29 var link: String = ""30 set(value) {31 field = value32 content = drawableFromUrl(value)33 }34 var content: Drawable = GradientDrawable()35 set(value) {36 field = value37 setChangedAndNotify("content")38 }39 var favorite: Boolean = false40 set(value) {41 field = value42 setChangedAndNotify("favorite")43 }44 @SerializedName("account_url")45 var owner: String = ""46 set(value) {47 field = value48 setChangedAndNotify("owner")49 }50 fun merge(other: Image?) {51 if (other == null)52 return53 this.apply {54 title = other.title55 type = other.type56 link = other.link57 favorite = other.favorite58 owner = other.owner59 }60 }61 private fun setChangedAndNotify(field: Any) {62 setChanged()63 notifyObservers(field)64 }65 @Throws(IOException::class)66 private fun drawableFromUrl(url: String): Drawable {67 val connection = URL(url).openConnection() as HttpURLConnection68 connection.connect()69 val input = connection.inputStream70 var x: Bitmap = BitmapFactory.decodeStream(input)71 return BitmapDrawable(Resources.getSystem(), x)72 }73 class Deserializer : ResponseDeserializable<Image> {74 override fun deserialize(content: String): Image? {75 val imageLink: String = getImageLink(content)76 if (imageLink.isEmpty())77 return null78 val image: Image = Gson().fromJson(content, Image::class.java)79 image.link = imageLink80 image.content = image.drawableFromUrl(image.link)81 return image82 }83 private fun getImageLink(content: String): String {84 if (!JSONObject(content).has("images")) {85 if (!isValidType(JSONObject(content)))86 return ""87 return JSONObject(content).getString("link")88 }89 val images: JSONArray = JSONObject(content).getJSONArray("images")90 if (images.length() != 1)91 return ""92 val firstImage = images.getJSONObject(0)93 if (!isValidType(firstImage))94 return ""95 return firstImage.getString("link")96 }97 private fun isValidType(image: JSONObject): Boolean {98 val type: String = image.getString("type")99 return type.startsWith("image/") &&100 type != "image/gif" &&101 !image.getBoolean("animated") &&102 !image.getBoolean("has_sound")103 }104 }105}...

Full Screen

Full Screen

CardView.kt

Source:CardView.kt Github

copy

Full Screen

1package com.csuf.scryfallclient2import android.graphics.Bitmap3import android.graphics.BitmapFactory4import android.os.AsyncTask5import android.os.Bundle6import android.widget.ImageView7import android.widget.TextView8import androidx.appcompat.app.AppCompatActivity9import com.beust.klaxon.Klaxon10import com.github.kittinunf.fuel.Fuel11import com.github.kittinunf.result.Result12import java.io.InputStream13import java.net.URL14import java.util.concurrent.Executor15class CardView : AppCompatActivity() {16 override fun onCreate(savedInstanceState: Bundle?) {17 super.onCreate(savedInstanceState)18 setContentView(R.layout.activity_card_view)19 val query = intent.getStringExtra(SEARCH_QUERY)20 if (query != null) {21 val r = Fuel.get("https://api.scryfall.com/cards/named?exact=$query")22 .responseString { request, response, result ->23 when (result) {24 is Result.Failure -> {25 println("Couldn't search! ${result.getException()}")26 }27 is Result.Success -> {28 val json = result.value29 val parsed = Klaxon().parse<Card>(json)30 if (parsed != null) {31 setCard(parsed)32 }33 }34 }35 }36 r.join()37 }38 }39 private fun setCard(card: Card) {40 findViewById<TextView>(R.id.card_name_text).text = card.name41 findViewById<TextView>(R.id.card_mana_text).text = card.mana_cost42 findViewById<TextView>(R.id.card_type_text).text = card.type_line43 findViewById<TextView>(R.id.card_oracle_text).text = card.oracle_text44 val imageView = findViewById<ImageView>(R.id.imageView)45 var bitmap : Bitmap? = null46 try {47 val input = URL(card.image_uris.png).openStream()48 bitmap = BitmapFactory.decodeStream(input)49 } catch (e: Exception) {50 e.printStackTrace()51 }52 if (bitmap != null) imageView.setImageBitmap(bitmap)53 }54}...

Full Screen

Full Screen

DecodeStream

Using AI Code Generation

copy

Full Screen

1val image = result.component1()?.let { DecodeStream(it).toBitmap() }2image?.let { imageView.setImageBitmap(it) }3image?.let { imageView.setImageBitmap(it) }4image?.let { imageView.setImageBitmap(it) }5image?.let { imageView.setImageBitmap(it) }6image?.let { imageView.setImageBitmap(it) }7image?.let { imageView.setImageBitmap(it) }8image?.let { imageView.setImageBitmap(it) }9image?.let { imageView.setImageBitmap(it) }10image?.let { imageView.setImageBitmap(it) }11image?.let { imageView.setImageBitmap(it) }12image?.let { imageView.setImageBitmap(it) }

Full Screen

Full Screen

DecodeStream

Using AI Code Generation

copy

Full Screen

1val (bytes, error) = result2}3val (bytes, error) = result4}5val (bytes, error) = result6}7val (bytes, error) = result8}9val (bytes, error) = result10}11val (bytes, error) = result12}13val (bytes, error) = result14}15val (request

Full Screen

Full Screen

DecodeStream

Using AI Code Generation

copy

Full Screen

1val (request, response, result) = Fuel.download(fileUrl).destination { response, url -> File.createTempFile("temp", "file") }.response()2val file = result.fold({ d -> d }, { err -> throw err })3val inputStream = file.inputStream()4val decodeStream = DecodeStream(inputStream)5val bitmap = decodeStream.decodeSampledBitmapFromStream(100, 100)6val imageView = findViewById(R.id.image_view) as ImageView7imageView.setImageBitmap(bitmap)8val (request, response, result) = Fuel.download(fileUrl).destination { response, url -> File.createTempFile("temp", "file") }.response()9val file = result.fold({ d -> d }, { err -> throw err })10val inputStream = file.inputStream()11val decodeStream = DecodeStream(inputStream)12val bitmap = decodeStream.decodeSampledBitmapFromStream(100, 100)13val imageView = findViewById(R.id.image_view) as ImageView14imageView.setImageBitmap(bitmap)15val (request, response, result) = Fuel.download(fileUrl).destination { response, url -> File.createTempFile("temp", "file") }.response()16val file = result.fold({ d -> d }, { err -> throw err })17val inputStream = file.inputStream()18val decodeStream = DecodeStream(inputStream)19val bitmap = decodeStream.decodeSampledBitmapFromStream(100, 100)20val imageView = findViewById(R.id.image_view) as ImageView21imageView.setImageBitmap(bitmap)22val (request, response, result) = Fuel.download(fileUrl).destination { response, url -> File.createTempFile("temp", "file") }.response()23val file = result.fold({ d -> d }, { err -> throw err })24val inputStream = file.inputStream()25val decodeStream = DecodeStream(inputStream)26val bitmap = decodeStream.decodeSampledBitmapFromStream(100, 100)27val imageView = findViewById(R.id.image_view) as ImageView28imageView.setImageBitmap(bitmap)29val (request, response, result) = Fuel.download(fileUrl).destination { response, url -> File.createTempFile("temp", "file")

Full Screen

Full Screen

DecodeStream

Using AI Code Generation

copy

Full Screen

1fun main(args: Array<String>) {2val image = result.fold({ data -> DecodeStream.decodeStream(data.inputStream) }, { err -> null })3image?.let { println("Image is ${it.width} wide and ${it.height} high") }4}5fun main(args: Array<String>) {6val image = result.fold({ data -> DecodeStream.decodeStream(data.inputStream) }, { err -> null })7image?.let { println("Image is ${it.width} wide and ${it.height} high") }8}

Full Screen

Full Screen

DecodeStream

Using AI Code Generation

copy

Full Screen

1val dataStream = result.component1()2val image = ImageIO.read(dataStream)3JLabel(ImageIcon(image)).display()4val image = result.fold({ ImageIO.read(it) }, { null })5JLabel(ImageIcon(image)).display()6val image = result.fold({ it }, { null })7JLabel(ImageIcon(image)).display()8val image = result.fold({ ImageIO.read(ByteArrayInputStream(it.toByteArray())) }, { null })9JLabel(ImageIcon(image)).display()10val image = result.fold({ ImageIO.read(ByteArrayInputStream(it.data)) }, { null })11JLabel(ImageIcon(image)).display()12val image = result.fold({ ImageIO.read(ByteArrayInputStream(it.data)) }, { null })13JLabel(ImageIcon(image)).display()14val image = result.fold({ ImageIO.read(ByteArrayInputStream(it.data)) }, { null })15JLabel(ImageIcon(image)).display()16val image = result.fold({ ImageIO.read(ByteArrayInputStream(it.data)) }, { null })17JLabel(ImageIcon(image)).display()18val image = result.fold({ ImageIO.read(ByteArrayInputStream(it.data)) }, { null })19JLabel(ImageIcon(image)).display

Full Screen

Full Screen

DecodeStream

Using AI Code Generation

copy

Full Screen

1 result.fold({ inputStream ->2 val data = ByteArray (100)3 inputStream.read(data)4 }, { error ->5 })6}7 result.fold({ inputStream ->8 inputStream.reader().readText()9 }, { error ->10 })11}12 result.fold({ inputStream ->13 inputStream.bufferedReader().readText()14 }, { error ->15 })16}17 result.fold({ inputStream ->18 inputStream.bufferedReader().use { it.readText() }19 }, { error ->20 })21}22 result.fold({ inputStream ->23 inputStream.bufferedReader().useLines { it.toList() }24 }, { error ->25 })26}

Full Screen

Full Screen

DecodeStream

Using AI Code Generation

copy

Full Screen

1val image: ImageView = findViewById(R.id.image)2File(filesDir, "image.jpg")3}.response { request, response, result ->4result.fold({ d ->5image.setImageBitmap(DecodeStream().invoke(d))6}, { err ->7})8}9val image: ImageView = findViewById(R.id.image)10File(filesDir, "image.jpg")11}.response { request, response, result ->12result.fold({ d ->13image.setImageBitmap(BitmapDecoder().invoke(d))14}, { err ->15})16}17val image: ImageView = findViewById(R.id.image)18File(filesDir, "image.jpg")19}.response { request, response, result ->20result.fold({ d ->21image.setImageBitmap(BitmapDecoder().invoke(d))22}, { err ->23})24}25val image: ImageView = findViewById(R.id.image)26File(filesDir, "image.jpg")27}.response { request, response, result ->28result.fold({ d ->29image.setImageBitmap(BitmapDecoder().invoke(d))30}, { err ->31})32}33val image: ImageView = findViewById(R.id.image)34File(filesDir, "image.jpg")35}.response { request, response, result ->36result.fold({ d ->37image.setImageBitmap(BitmapDecoder().invoke(d))38}, { err ->

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Fuel automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used methods in DecodeStream

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful