How to use InputStream.decode method of com.github.kittinunf.fuel.util.DecodeStream class

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

ChatInfoActivity.kt

Source:ChatInfoActivity.kt Github

copy

Full Screen

1package com.example.pangchat2import android.app.Activity3import android.content.Intent4import android.graphics.Bitmap5import android.graphics.BitmapFactory6import android.os.Bundle7import android.provider.MediaStore8import android.util.Log9import android.view.View10import android.widget.ImageView11import android.widget.LinearLayout12import android.widget.TextView13import androidx.appcompat.app.AppCompatActivity14import androidx.lifecycle.MutableLiveData15import androidx.lifecycle.lifecycleScope16import androidx.recyclerview.widget.GridLayoutManager17import androidx.recyclerview.widget.RecyclerView18import com.example.pangchat.chat.Chat19import com.example.pangchat.chat.ChatMemberAdapter20import com.example.pangchat.chat.data.ChatInfo21import com.example.pangchat.chat.data.ChatRequest22import com.example.pangchat.chat.data.ChatResult23import com.example.pangchat.chat.data.ChatUserInfo24import com.example.pangchat.fragment.data.FileDataSource25import com.example.pangchat.fragment.data.Result26import com.example.pangchat.fragment.data.UploadResult27import com.example.pangchat.user.User28import com.example.pangchat.user.data.CommonResp29import com.example.pangchat.user.data.UserRequest30import com.example.pangchat.user.data.UserResult31import com.example.pangchat.utils.CookiedFuel32import com.example.pangchat.websocketClient.webSocketClient33import com.github.kittinunf.fuel.core.BlobDataPart34import com.github.kittinunf.fuel.core.DataPart35import com.github.kittinunf.fuel.coroutines.awaitByteArray36import kotlinx.coroutines.Dispatchers37import kotlinx.coroutines.MainScope38import kotlinx.coroutines.launch39import kotlinx.coroutines.withContext40import java.io.InputStream41import java.util.*42import kotlin.collections.ArrayList43class ChatInfoActivity : AppCompatActivity() {44 var chat: Chat? = null45 var chatId: String? = null46 var members = LinkedList<User?>()47 var chatName: TextView? = null48 var chatAvatar: ImageView ?= null49 var chatAvatarUrl: String ?= null50 var hasChange: Boolean = false51 var chatNameLayout: LinearLayout? = null52 var chatAvatarLayout: LinearLayout? = null53 var chatLeaveLayout: LinearLayout? = null54 var recyclerView : RecyclerView? = null55 var _uploadInfo = MutableLiveData<UploadResult>()56 // 拍照回传码57 val CAMERA_REQUEST_CODE = 0;58 // 相册选择回传码59 val GALLERY_REQUEST_CODE = 160 override fun onCreate(savedInstanceState: Bundle?) {61 super.onCreate(savedInstanceState)62 setContentView(R.layout.activity_chat_info)63 chatId = intent.getStringExtra("chatId")64 chatName = findViewById<TextView>(R.id.chatName)65 chatAvatar = findViewById(R.id.chatInfoChatAvatar)66 recyclerView = findViewById<RecyclerView>(R.id.chatInfoMembersView)67 recyclerView?.adapter = ChatMemberAdapter(this, members, webSocketClient.urlToBitmap)68 val gridLayoutManager = GridLayoutManager(this, 5)69 recyclerView?.layoutManager = gridLayoutManager70 chatNameLayout = findViewById(R.id.chatNameLayout)71 chatAvatarLayout = findViewById(R.id.chatAvatarLayout)72 chatLeaveLayout = findViewById(R.id.chatLeaveLayout)73 }74 fun updateChatInfo(){75 if (chatId != null) {76 lifecycleScope.launch {77 members.clear()78 getChatMember(chatId!!)79 runOnUiThread {80 recyclerView?.adapter?.notifyDataSetChanged()81 }82 if(members != null){83 for(member in members){84 if(!webSocketClient.urlToBitmap.keys.contains(member?.getAvatar())){85 downloadImage(member!!.getAvatar(), recyclerView!!)86 }87 }88 }89 recyclerView?.adapter?.notifyDataSetChanged()90 if(!hasChange){91 if(!webSocketClient.urlToBitmap.containsKey(chat!!.getChatAvatar())){92 // 发起下载图片请求93 val bit: Bitmap;94 withContext(Dispatchers.IO) {95 val result = CookiedFuel.get(chat!!.getChatAvatar()).awaitByteArray();96 bit = BitmapFactory.decodeByteArray(result, 0, result.size)97 webSocketClient.urlToBitmap[chat!!.getChatAvatar()!!] = bit98 }99 }100 chatAvatar!!.setImageBitmap(webSocketClient.urlToBitmap[chat!!.getChatAvatar()])101 }102 hasChange = false103 runOnUiThread{104 if(chat != null){105 chatName?.text = chat!!.getChatName()106 members.add(User("-1", "-1", "-1", "-1"))107 recyclerView?.adapter?.notifyDataSetChanged()108 if(!chat!!.getIsGroup()){109 chatNameLayout?.visibility = View.GONE110 chatAvatarLayout?.visibility = View.GONE111 chatLeaveLayout?.visibility = View.GONE112 }113 }114 }115 }116 }117 val back = findViewById<ImageView>(R.id.chatInfoBackward)118 back.setOnClickListener {119 finish()120 }121 chatLeaveLayout?.setOnClickListener {122 lifecycleScope.launch {123 if(chatId != null && leaveChat(chatId!!)){124 activityFinish()125 }126 }127 }128 chatNameLayout?.setOnClickListener {129 if(chatId != null){130 val intent = Intent(this, ChatnameModifyActivity::class.java)131 intent.putExtra("chatId", chatId)132 intent.putExtra("chatName", chat?.getChatName())133 try {134 this.startActivity(intent)135 } catch (ActivityNotFoundException: Exception) {136 Log.d("ImplicitIntents", "Can't handle this!")137 }138 }139 }140 chatAvatarLayout?.setOnClickListener {141 val pickIntent : Intent = Intent(Intent.ACTION_PICK,142 MediaStore.Images.Media.EXTERNAL_CONTENT_URI);143 pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");144 startActivityForResult(pickIntent, GALLERY_REQUEST_CODE);145 }146 }147 override fun onResume() {148 super.onResume()149 webSocketClient.context = this150 updateChatInfo()151 }152 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {153 super.onActivityResult(requestCode, resultCode, data)154 if (resultCode == Activity.RESULT_OK) {155 if (requestCode == CAMERA_REQUEST_CODE) {156 print("qwq")157 }158 else if (requestCode == GALLERY_REQUEST_CODE){159 try {160 //该uri是上一个Activity返回的161 val imageUri = data?.getData();162 if(imageUri!=null) {163 var inputImage: InputStream164 hasChange = true165 chatAvatar?.setImageBitmap(BitmapFactory.decodeStream(contentResolver?.openInputStream(imageUri)))166 // 向服务器发送请求167 MainScope().launch {168 val splited = imageUri.lastPathSegment!!.split("/");169 withContext(Dispatchers.IO) {170 inputImage =171 contentResolver?.openInputStream(imageUri)!!172 }173 uploadImage(174 BlobDataPart(175 inputImage,176 "file",177 splited[splited.size - 1]178 )179 )180 modifyChatAvatar(chatId!!, _uploadInfo.value!!.url)181 }182 }183 } catch (e: Exception) {184 e.printStackTrace();185 }186 }else if(requestCode == 100){187 val reply = data?.getStringExtra("chatName")188 chatName?.text = reply189 }190 }191 }192 suspend fun uploadImage(file: DataPart) {193 val fileDataSource = FileDataSource()194 val result: Result<UploadResult>195 withContext(Dispatchers.IO) {196 result = fileDataSource.uploadFile(file)197 }198 if (result is Result.Success) {199 _uploadInfo.value = result.data200 } else {201 // TODO:抛出并解析异常202 }203 }204 private suspend fun modifyChatAvatar(chatId: String, value: String): Boolean{205 val chatRequest = ChatRequest()206 val result: ChatResult<ChatInfo>207 withContext(Dispatchers.IO) {208 result = chatRequest.chatModify(chatId, "chatAvatar",value)209 }210 if (result is ChatResult.Success) {211 Log.d("chat", "success")212 } else {213 // TODO:抛出并解析异常214 }215 return result is ChatResult.Success216 }217 private suspend fun activityFinish(){218 this.finish()219 }220 private suspend fun getChatMember(chatId: String){221 val chatRequest = ChatRequest()222 val result: ChatResult<ChatUserInfo>223 withContext(Dispatchers.IO) {224 result = chatRequest.getChatAndMembers(chatId)225 }226 if (result is ChatResult.Success) {227 chat = result.data.chat228 for(user in result.data.members){229 members.add(user)230 }231 } else {232 // TODO:抛出并解析异常233 }234 }235 private suspend fun leaveChat(chatId: String): Boolean{236 val userRequest = UserRequest()237 val result: UserResult<CommonResp>238 withContext(Dispatchers.IO) {239 var userId = ArrayList<String>()240 userId.add(webSocketClient.userId!!)241 result = userRequest.userChat(userId, chatId, "leave")242 }243 if (result is UserResult.Success) {244 Log.d("chat", "success")245 } else {246 // TODO:抛出并解析异常247 }248 return result is UserResult.Success249 }250 fun toAddChatMember(){251 val intent = Intent(this, SelectFriendsActivity::class.java)252 intent.putExtra("chatId", chat?.getId())253 intent.putStringArrayListExtra("members", chat?.getMembers())254 try {255 this.startActivity(intent)256 this.finish()257 } catch (ActivityNotFoundException: Exception) {258 Log.d("ImplicitIntents", "Can't handle this!")259 }260 }261 public fun downloadImage(url: String, recyclerView: RecyclerView){262 lifecycleScope.launch {263 downloadBitmap(url)264 recyclerView.adapter?.notifyDataSetChanged()265 }266 }267 suspend fun downloadBitmap(url: String){268 withContext(Dispatchers.IO){269 val result = CookiedFuel.get(url).awaitByteArray();270 if(result != null){271 val bit: Bitmap = BitmapFactory.decodeByteArray(result, 0, result.size)272 webSocketClient.urlToBitmap!!.put(url, bit)273 }274 }275 }276}...

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

EvaluatedPearRepository.kt

Source:EvaluatedPearRepository.kt Github

copy

Full Screen

1package com.example.pearappearanceevaluatesystemandroid.repository2import android.graphics.Bitmap3import android.graphics.BitmapFactory4import com.example.pearappearanceevaluatesystemandroid.config.GlobalConst5import com.example.pearappearanceevaluatesystemandroid.originenum.EvaluateCode6import com.example.pearappearanceevaluatesystemandroid.model.EvaluatedPearModel7import com.github.kittinunf.fuel.httpGet8import com.github.kittinunf.fuel.json.responseJson9import com.github.kittinunf.result.Result10import org.json.JSONArray11import org.json.JSONObject12import java.io.IOException13import java.io.InputStream14import java.net.HttpURLConnection15import java.net.URL16import java.util.ArrayList17class EvaluatedPearRepository {18 /**19 * @args pearId 洋ナシのID20 * @return evaluatedPearModel21 */22 fun getEvaluatedPear(pearId: Int): EvaluatedPearModel {23 val requestURL = GlobalConst().defaultRequestUrl + "/pear/evaluates/$pearId"24 val (_, _, result) = requestURL.httpGet().responseJson()25 when (result) {26 is Result.Success -> {27 // レスポンスボディを取得28 val responseBody = result.get().obj()29 var evaluateCode = EvaluateCode.Not_Yet30 when (responseBody["evaluate_code"] as String) {31 "Not_Yet" -> {32 evaluateCode = EvaluateCode.Not_Yet33 }34 "No" -> {35 evaluateCode = EvaluateCode.No36 }37 "Good" -> {38 evaluateCode = EvaluateCode.Good39 }40 "Blue" -> {41 evaluateCode = EvaluateCode.Blue42 }43 "Red" -> {44 evaluateCode = EvaluateCode.Red45 }46 }47 if (evaluateCode == EvaluateCode.Not_Yet) {48 return EvaluatedPearModel(49 id = pearId,50 evaluateCode = EvaluateCode.Not_Yet,51 pearImages = ArrayList(),52 evaluatedPearImages = ArrayList(),53 deteriorations = ArrayList()54 )55 }56 val evaluatedImageUrls: JSONArray = responseBody["evaluated_images"] as JSONArray57 val pearImageUrls: JSONArray = responseBody["pear_images"] as JSONArray58 val deteriorations: JSONArray = responseBody["deteriorations"] as JSONArray59 val evaluatedImageUrlList: ArrayList<String> = ArrayList()60 val pearImageUrlList: ArrayList<String> = ArrayList()61 val deteriorationList: ArrayList<JSONObject> = ArrayList()62 for (i in 0 until evaluatedImageUrls.length()) {63 val evaluatedImageUrl = evaluatedImageUrls[i]64 evaluatedImageUrlList.add(evaluatedImageUrl as String)65 }66 for (i in 0 until pearImageUrls.length()) {67 val pearImageUrl = pearImageUrls[i]68 pearImageUrlList.add(pearImageUrl as String)69 }70 for (i in 0 until deteriorations.length()) {71 val deterioration = deteriorations.getJSONObject(i)72 deteriorationList.add(deterioration)73 }74 val pearImages: ArrayList<Bitmap> = ArrayList()75 pearImageUrlList.forEach { pearImageUrl ->76 val pearImage = getBitmapFromURL(pearImageUrl)77 if (pearImage != null) {78 pearImages.add(pearImage)79 }80 }81 val evaluatedPearImages: ArrayList<Bitmap> = ArrayList()82 evaluatedImageUrlList.forEach { evaluatedImageUrl ->83 val evaluatedPearImage = getBitmapFromURL(evaluatedImageUrl)84 if (evaluatedPearImage != null) {85 evaluatedPearImages.add(evaluatedPearImage)86 }87 }88 return EvaluatedPearModel(89 id = pearId,90 evaluateCode = evaluateCode,91 pearImages = pearImages,92 evaluatedPearImages = evaluatedPearImages,93 deteriorations = deteriorationList94 )95 }96 is Result.Failure -> {97 println("connection failed: " + result.error)98 }99 }100 return EvaluatedPearModel(101 id = pearId,102 evaluateCode = EvaluateCode.Not_Yet,103 pearImages = ArrayList(),104 evaluatedPearImages = ArrayList(),105 deteriorations = ArrayList()106 )107 }108 /**109 * 画像のURLからBitmapを生成する110 */111 private fun getBitmapFromURL(src: String?): Bitmap? {112 return try {113 val url = URL(src)114 val connection: HttpURLConnection = url.openConnection() as HttpURLConnection115 connection.doInput = true116 connection.connect()117 val input: InputStream = connection.inputStream118 BitmapFactory.decodeStream(input)119 } catch (e: IOException) {120 e.printStackTrace()121 null122 }123 }124}...

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

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

InputStream.decode

Using AI Code Generation

copy

Full Screen

1result.fold({ d ->2println(d)3}, { err ->4println(err)5})6}7result.fold({ d ->8println(d)9}, { err ->10println(err)11})12}13result.fold({ d ->14println(d)15}, { err ->16println(err)17})18}19result.fold({ d ->20println(d)21}, { err ->22println(err)23})24}25result.fold({ d ->26println(d)27}, { err ->28println(err)29})30}31result.fold({ d ->32println(d)33}, { err ->34println(err)35})36}37result.fold({ d ->38println(d)39}, { err ->40println(err)41})42}43result.fold({ d ->44println(d)45}, { err ->46println(err)47})48}49result.fold({ d ->50println(d)51}, { err ->52println(err)53})54}55result.fold({ d

Full Screen

Full Screen

InputStream.decode

Using AI Code Generation

copy

Full Screen

1InputStream decodedStream = DecodeStream(inputStream, "UTF-8");2InputStream decodedStream = DecodeStream(inputStream, "UTF-8");3InputStream decodedStream = DecodeStream(inputStream, "UTF-8");4InputStream decodedStream = DecodeStream(inputStream, "UTF-8");5InputStream decodedStream = DecodeStream(inputStream, "UTF-8");6InputStream decodedStream = DecodeStream(inputStream, "UTF-8");7InputStream decodedStream = DecodeStream(inputStream, "UTF-8");8InputStream decodedStream = DecodeStream(inputStream, "UTF-8");9InputStream decodedStream = DecodeStream(inputStream, "UTF-8");10InputStream decodedStream = DecodeStream(inputStream, "UTF-8");

Full Screen

Full Screen

InputStream.decode

Using AI Code Generation

copy

Full Screen

1val (request, response, result) = Fuel.get(url).responseString()2val (data, error) = result3val inputStream = ByteArrayInputStream(data?.toByteArray())4val decodedStream = DecodeStream(inputStream).decode()5val bitmap = BitmapFactory.decodeStream(decodedStream)6val (request, response, result) = Fuel.get(url).responseString()7val (data, error) = result8val inputStream = ByteArrayInputStream(data?.toByteArray())9val decodedStream = DecodeStream(inputStream).decode()10val bitmap = BitmapFactory.decodeStream(decodedStream)11val (request, response, result) = Fuel.get(url).responseString()12val (data, error) = result13val inputStream = ByteArrayInputStream(data?.toByteArray())14val decodedStream = DecodeStream(inputStream).decode()15val bitmap = BitmapFactory.decodeStream(decodedStream)16val (request, response, result) = Fuel.get(url).responseString()17val (data, error) = result18val inputStream = ByteArrayInputStream(data?.toByteArray())19val decodedStream = DecodeStream(inputStream).decode()20val bitmap = BitmapFactory.decodeStream(decodedStream)21val (request, response, result) = Fuel.get(url).responseString()22val (data, error) = result23val inputStream = ByteArrayInputStream(data?.toByteArray())24val decodedStream = DecodeStream(inputStream).decode()25val bitmap = BitmapFactory.decodeStream(decodedStream)26val (request, response, result) = Fuel.get(url).responseString()27val (data, error) = result28val inputStream = ByteArrayInputStream(data?.toByteArray())29val decodedStream = DecodeStream(inputStream).decode()30val bitmap = BitmapFactory.decodeStream(decodedStream)31val (request, response, result) = Fuel.get(url).responseString()32val (data, error) = result33val inputStream = ByteArrayInputStream(data?.toByteArray())34val decodedStream = DecodeStream(inputStream).decode()35val bitmap = BitmapFactory.decodeStream(decodedStream)36val (request, response, result) = Fuel.get(url).responseString()37val (data, error) = result38val inputStream = ByteArrayInputStream(data?.toByteArray())39val decodedStream = DecodeStream(inputStream).decode()40val bitmap = BitmapFactory.decodeStream(decodedStream)41val (request, response, result) = Fuel.get(url).responseString()42val (data, error) = result43val inputStream = ByteArrayInputStream(data?.toByteArray())44val decodedStream = DecodeStream(inputStream).decode()45val bitmap = BitmapFactory.decodeStream(decodedStream

Full Screen

Full Screen

InputStream.decode

Using AI Code Generation

copy

Full Screen

1val stream = ByteArrayInputStream ( "test" . toByteArray ( Charset . forName ( "UTF-8" )))2 val string = stream . decode ( "UTF-8" )3val stream = ByteArrayInputStream ( "test" . toByteArray ( Charset . forName ( "UTF-8" )))4 val string = stream . decode ( "UTF-8" )5val stream = ByteArrayInputStream ( "test" . toByteArray ( Charset . forName ( "UTF-8" )))6 val string = stream . decode ( "UTF-8" )7val stream = ByteArrayInputStream ( "test" . toByteArray ( Charset . forName ( "UTF-8" )))8 val string = stream . decode ( "UTF-8" )9val stream = ByteArrayInputStream ( "test" . toByteArray ( Charset . forName ( "UTF-8" )))10 val string = stream . decode ( "UTF-8" )11val stream = ByteArrayInputStream ( "test" . toByteArray ( Charset . forName ( "UTF-8" )))12 val string = stream . decode ( "UTF-8" )13val stream = ByteArrayInputStream ( "test" . toByteArray ( Charset . forName ( "UTF-8" )))14 val string = stream . decode ( "UTF-8" )

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 method 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