Best Fuel code snippet using com.example.fuel.MainActivity.httpPost
ProductBidActivity.kt
Source:ProductBidActivity.kt
...21import com.example.kalepa.Preferences.SharedApp22import com.example.kalepa.models.User23import com.github.kittinunf.fuel.android.extension.responseJson24import com.github.kittinunf.fuel.httpGet25import com.github.kittinunf.fuel.httpPost26import com.github.kittinunf.fuel.httpPut27import com.github.kittinunf.result.Result28import kotlinx.android.synthetic.main.fragment_product_image.view.*29import org.jetbrains.anko.toast30import org.json.JSONObject31class ProductBidActivity : AppCompatActivity() {32 var product: Product = Product()33 var user: User = User()34 private var mSectionsPagerAdapter: SectionsPagerAdapter? = null35 private var num_images = 036 override fun onCreate(savedInstanceState: Bundle?) {37 super.onCreate(savedInstanceState)38 val product_id: String? = intent.extras.getString(PRODUCT_ARG)39 setContentView(R.layout.activity_product_bid)40 val builder = AlertDialog.Builder(this)41 val dialogView = layoutInflater.inflate(R.layout.progress_dialog,null)42 val message = dialogView.findViewById<TextView>(R.id.message)43 message.text = "Cargando producto..."44 builder.setView(dialogView)45 builder.setCancelable(false)46 val dialog = builder.create()47 dialog.show()48 val url = MainActivity().projectURL + "/product/" + product_id49 val req = url.httpGet().header(Pair("Cookie", SharedApp.prefs.cookie))50 req.responseJson { request, response, result ->51 when (result) {52 is Result.Failure -> {53 MainActivity.start(this)54 toast("Error cargando el producto")55 }56 is Result.Success -> {57 Initialize1(result.value)58 dialog.dismiss()59 }60 }61 }62 }63 private fun Initialize1(jsonObject: JSONObject) {64 product.fromJSON(jsonObject)65 val builder = AlertDialog.Builder(this)66 val dialogView = layoutInflater.inflate(R.layout.progress_dialog,null)67 val message = dialogView.findViewById<TextView>(R.id.message)68 message.text = "Cargando usuario..."69 builder.setView(dialogView)70 builder.setCancelable(false)71 val dialog = builder.create()72 dialog.show()73 val url = MainActivity().projectURL + "/user/" + product.user_id74 val req = url.httpGet().header(Pair("Cookie", SharedApp.prefs.cookie))75 req.responseJson { request, response, result ->76 when (result) {77 is Result.Failure -> {78 MainActivity.start(this)79 toast("Error cargando el producto")80 }81 is Result.Success -> {82 Initialize2(result.value)83 dialog.dismiss()84 }85 }86 }87 }88 private fun Initialize2(jsonObject: JSONObject) {89 user.fromJSON(jsonObject)90 val builder = AlertDialog.Builder(this)91 val dialogView = layoutInflater.inflate(R.layout.progress_dialog,null)92 val message = dialogView.findViewById<TextView>(R.id.message)93 message.text = "Cargando pujas..."94 builder.setView(dialogView)95 builder.setCancelable(false)96 val dialog = builder.create()97 dialog.show()98 val url = MainActivity().projectURL + "/bid/" + product.id99 val req = url.httpGet().header(Pair("Cookie", SharedApp.prefs.cookie))100 req.responseJson { request, response, result ->101 when (result) {102 is Result.Failure -> {103 MainActivity.start(this)104 toast("Error cargando el producto")105 }106 is Result.Success -> {107 Initialize3(result.value)108 dialog.dismiss()109 }110 }111 }112 }113 private fun Initialize3(jsonObject: JSONObject) {114 b_product_name.setText(product.title)115 b_product_price.setText(product.price.toString())116 b_product_bid.setText(jsonObject.get("max_bid").toString())117 b_product_bid_date.setText(product.bid_date.substring(0,10))118 b_product_description.setText(product.descript)119 b_product_place.setText(product.place)120 b_product_date.setText(product.publish_date)121 b_product_seller.setText(user.nick)122 b_product_rating.rating = user.points.toFloat()123 b_product_seller.setOnClickListener {124 ProfileActivity.start(this, product.user_id.toString())125 }126 b_product_bid_button.setOnClickListener {127 bidONbid()128 }129 m_product_share_facebook.setOnClickListener {130 val url = MainActivity().webURL + "/anuncio.html?idAnuncio=" + product.id.toString()131 val shareIntent = Intent()132 shareIntent.action = Intent.ACTION_SEND133 shareIntent.type="text/plain"134 shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Mira que producto mas chulo de KALEPA, mi pagina de compra y venta favorita:")135 shareIntent.putExtra(Intent.EXTRA_TEXT, url)136 startActivity(Intent.createChooser(shareIntent, "Compartir con:"))137 }138 num_images = product.photo_urls.size139 mSectionsPagerAdapter = SectionsPagerAdapter(supportFragmentManager)140 b_product_images_container.adapter = mSectionsPagerAdapter141 showImages(product.categories)142 }143 private fun showImages(items: ArrayList<String>) {144 b_categories_container_bid.layoutManager = GridLayoutManager(this, items.size)145 val imageItemAdapters = items.map(this::createCategoryItemAdapter)146 b_categories_container_bid.adapter = MainListAdapter(imageItemAdapters)147 }148 private fun createCategoryItemAdapter(category: String)149 = CategoryAdapter(category,150 { rtrue(category) })151 private fun rtrue (category: String): Boolean {152 return true153 }154 private fun bidONbid() {155 var userBid: Float = 0.0f156 if (!b_product_bid_offer.text.toString().isNullOrEmpty()){157 userBid = b_product_bid_offer.text.toString().toFloat()158 }159 val maxBid = b_product_bid.text.toString().toFloat()160 val regex = """[0-9]+(.[0-9][0-9])?""".toRegex()161 if (!regex.matches(b_product_bid_offer.text.toString()) || userBid <= maxBid) {162 b_product_bid_offer.error = "No es una cantidad válida o es insuficiente"163 } else {164 val builder = AlertDialog.Builder(this)165 val dialogView = layoutInflater.inflate(R.layout.progress_dialog,null)166 val message = dialogView.findViewById<TextView>(R.id.message)167 message.text = "Pujando..."168 builder.setView(dialogView)169 builder.setCancelable(false)170 val dialog = builder.create()171 dialog.show()172 val jsonObject = JSONObject()173 jsonObject.accumulate("bid", userBid)174 val url = MainActivity().projectURL + "/bid/" + product.id175 val req = url.httpPost().body(jsonObject.toString()).header(Pair("Cookie", SharedApp.prefs.cookie))176 req.httpHeaders["Content-Type"] = "application/json"177 req.responseJson { request, response, result ->178 when (result) {179 is Result.Failure -> {180 dialog.dismiss()181 toast("Su puja ya es la más alta")182 }183 is Result.Success -> {184 dialog.dismiss()185 toast("Su puja es ahora la más alta")186 }187 }188 }189 }190 }191 inner class SectionsPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {192 override fun getItem(position: Int): Fragment {193 // getItem is called to instantiate the fragment for the given page.194 // Return a PlaceholderFragment (defined as a static inner class below).195 return PlaceholderFragment.newInstance(position , product.photo_urls)196 }197 override fun getCount(): Int {198 // Show 5 total pages.(we will use 5 pages so change it to 5)199 return num_images200 }201 }202 class PlaceholderFragment : Fragment() {203 override fun onCreateView(204 inflater: LayoutInflater, container: ViewGroup?,205 savedInstanceState: Bundle?206 ): View? {207 val rootView = inflater.inflate(R.layout.fragment_product_image, container, false)208 val images = arguments!!.getStringArrayList(ARG_IMAGE_LIST)209 rootView.image_iv.loadImage(images[arguments!!.getInt(ARG_SECTION_NUMBER)])210 return rootView211 }212 companion object {213 /**214 * The fragment argument representing the section number for this215 * fragment.216 */217 private val ARG_SECTION_NUMBER = "section_number"218 private val ARG_IMAGE_LIST = "image_list"219 /**220 * Returns a new instance of this fragment for the given section221 * number.222 */223 fun newInstance(sectionNumber: Int, images: ArrayList<String?>): PlaceholderFragment {224 val fragment = PlaceholderFragment()225 val args = Bundle()226 args.putInt(ARG_SECTION_NUMBER, sectionNumber)227 args.putStringArrayList(ARG_IMAGE_LIST, images)228 fragment.arguments = args229 return fragment230 }231 }232 }233 companion object {234 private const val bullet = '\u2022'235 private const val PRODUCT_ARG = "com.example.kalepa.BidProductActivity.ProductArgKey"236 fun getIntent(context: Context, product_id: String) = context237 .getIntent<ProductBidActivity>()238 .apply { putExtra(PRODUCT_ARG, product_id) }239 fun start(context: Context, product_id: String) {240 val intent = getIntent(context, product_id)241 context.startActivity(intent)242 }243 }244 override fun onCreateOptionsMenu(menu: Menu): Boolean {245 val inflater = menuInflater246 if (SharedApp.prefs.isMod) {247 inflater.inflate(R.menu.mod_product_menu, menu)248 } else {249 inflater.inflate(R.menu.user_product_menu, menu)250 }251 return true252 }253 override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {254 R.id.n_upm_follow -> {255 val builder = AlertDialog.Builder(this)256 val dialogView = layoutInflater.inflate(R.layout.progress_dialog,null)257 val message = dialogView.findViewById<TextView>(R.id.message)258 message.text = "Siguiendo producto..."259 builder.setView(dialogView)260 builder.setCancelable(false)261 val dialog = builder.create()262 dialog.show()263 val url = MainActivity().projectURL + "/product/" + product.id.toString() + "/follow"264 val req = url.httpPost().header(Pair("Cookie", SharedApp.prefs.cookie))265 req.response { request, response, result ->266 when (result) {267 is Result.Failure -> {268 dialog.dismiss()269 toast("Ya sigues este producto")270 }271 is Result.Success -> {272 dialog.dismiss()273 toast("Añadido a tu lista de deseos")274 }275 }276 }277 true278 }279 R.id.n_upm_unfollow -> {280 val builder = AlertDialog.Builder(this)281 val dialogView = layoutInflater.inflate(R.layout.progress_dialog,null)282 val message = dialogView.findViewById<TextView>(R.id.message)283 message.text = "Siguiendo producto..."284 builder.setView(dialogView)285 builder.setCancelable(false)286 val dialog = builder.create()287 dialog.show()288 val url = MainActivity().projectURL + "/product/" + product.id.toString() + "/unfollow"289 val req = url.httpPost().header(Pair("Cookie", SharedApp.prefs.cookie))290 req.response { request, response, result ->291 when (result) {292 is Result.Failure -> {293 dialog.dismiss()294 toast("No sigues este producto")295 }296 is Result.Success -> {297 dialog.dismiss()298 toast("Eliminado de tu lista de deseos")299 }300 }301 }302 true303 }304 R.id.n_upm_report -> {305 reportProduct()306 true307 }308 R.id.n_mpm_ban -> {309 banProduct()310 true311 }312 else -> {313 super.onOptionsItemSelected(item)314 }315 }316 private fun reportProduct() {317 val view = layoutInflater.inflate(R.layout.dialog_report_product, null)318 val window = PopupWindow(319 view, // Custom view to show in popup window320 LinearLayout.LayoutParams.WRAP_CONTENT, // Width of popup window321 LinearLayout.LayoutParams.WRAP_CONTENT // Window height322 )323 window.isFocusable = true324 //Blur the background325 val fcolorNone = ColorDrawable(resources.getColor(R.color.transparent))326 val fcolorBlur = ColorDrawable(resources.getColor(R.color.transparentDark))327 n_productBid_container.foreground = fcolorBlur328 window.showAtLocation(329 n_productBid_header, // Location to display popup window330 Gravity.CENTER, // Exact position of layout to display popup331 0, // X offset332 0 // Y offset333 )334 val cancel = view.findViewById<Button>(R.id.n_drp_cancelar)335 val report = view.findViewById<Button>(R.id.n_drp_reportar)336 val reason = view.findViewById<EditText>(R.id.n_drp_reason)337 report.setOnClickListener {338 if (!reason.text.toString().equals("")) {339 val builder = AlertDialog.Builder(this)340 val dialogView = layoutInflater.inflate(R.layout.progress_dialog,null)341 val message = dialogView.findViewById<TextView>(R.id.message)342 message.text = "Enviando report..."343 builder.setView(dialogView)344 builder.setCancelable(false)345 val dialog = builder.create()346 dialog.show()347 val jsonObject = JSONObject()348 jsonObject.accumulate("user_id", user.id)349 jsonObject.accumulate("product_id", product.id)350 jsonObject.accumulate("reason", reason.text.toString())351 val url = MainActivity().projectURL + "/report"352 val req = url.httpPost().body(jsonObject.toString()).header(Pair("Cookie", SharedApp.prefs.cookie))353 req.httpHeaders["Content-Type"] = "application/json"354 req.response { request, response, result ->355 when (result) {356 is Result.Failure -> {357 dialog.dismiss()358 toast("Error enviando report")359 }360 is Result.Success -> {361 dialog.dismiss()362 toast("Report enviado")363 }364 }365 }366 window.dismiss()...
ProductBuyActivity.kt
Source:ProductBuyActivity.kt
...22import com.example.kalepa.Preferences.SharedApp23import com.example.kalepa.models.User24import com.github.kittinunf.fuel.android.extension.responseJson25import com.github.kittinunf.fuel.httpGet26import com.github.kittinunf.fuel.httpPost27import com.github.kittinunf.fuel.httpPut28import com.github.kittinunf.result.Result29import kotlinx.android.synthetic.main.fragment_product_image.view.*30import org.jetbrains.anko.toast31import org.json.JSONObject32class ProductBuyActivity : AppCompatActivity() {33 var product: Product = Product()34 var user: User = User()35 private var mSectionsPagerAdapter: SectionsPagerAdapter? = null36 private var num_images = 037 override fun onCreate(savedInstanceState: Bundle?) {38 super.onCreate(savedInstanceState)39 val product_id: String? = intent.extras.getString(PRODUCT_ARG)40 setContentView(R.layout.activity_product_buy)41 val builder = AlertDialog.Builder(this)42 val dialogView = layoutInflater.inflate(R.layout.progress_dialog,null)43 val message = dialogView.findViewById<TextView>(R.id.message)44 message.text = "Cargando producto..."45 builder.setView(dialogView)46 builder.setCancelable(false)47 val dialog = builder.create()48 dialog.show()49 val url = MainActivity().projectURL + "/product/" + product_id50 val req = url.httpGet().header(Pair("Cookie", SharedApp.prefs.cookie))51 req.responseJson { request, response, result ->52 when (result) {53 is Result.Failure -> {54 MainActivity.start(this)55 toast("Error cargando el producto")56 }57 is Result.Success -> {58 Initialize1(result.value)59 dialog.dismiss()60 }61 }62 }63 }64 private fun Initialize1(jsonObject: JSONObject) {65 product.fromJSON(jsonObject)66 val builder = AlertDialog.Builder(this)67 val dialogView = layoutInflater.inflate(R.layout.progress_dialog,null)68 val message = dialogView.findViewById<TextView>(R.id.message)69 message.text = "Cargando usuario..."70 builder.setView(dialogView)71 builder.setCancelable(false)72 val dialog = builder.create()73 dialog.show()74 val url = MainActivity().projectURL + "/user/" + product.user_id75 val req = url.httpGet().header(Pair("Cookie", SharedApp.prefs.cookie))76 req.responseJson { request, response, result ->77 when (result) {78 is Result.Failure -> {79 MainActivity.start(this)80 toast("Error cargando el producto")81 }82 is Result.Success -> {83 Initialize2(result.value)84 dialog.dismiss()85 }86 }87 }88 }89 private fun Initialize2(jsonObject: JSONObject) {90 user.fromJSON(jsonObject)91 b_product_name.setText(product.title)92 b_product_price.setText(product.price.toString())93 b_product_description.setText(product.descript)94 b_product_date.setText(product.publish_date)95 b_product_place.setText(product.place)96 b_product_seller.setText(user.nick)97 b_product_rating.rating = user.points.toFloat()98 b_product_seller.setOnClickListener {99 ProfileActivity.start(this, product.user_id.toString())100 }101 b_product_trade.setOnClickListener {102 TradeActivity.start(this, product.id.toString(), user.id.toString())103 }104 m_product_share_facebook.setOnClickListener {105 val url = MainActivity().webURL + "/anuncio.html?idAnuncio=" + product.id.toString()106 val shareIntent = Intent()107 shareIntent.action = Intent.ACTION_SEND108 shareIntent.type="text/plain"109 shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Mira que producto mas chulo de KALEPA, mi pagina de compra y venta favorita:")110 shareIntent.putExtra(Intent.EXTRA_TEXT, url)111 startActivity(Intent.createChooser(shareIntent, "Compartir con:"))112 }113 num_images = product.photo_urls.size114 mSectionsPagerAdapter = SectionsPagerAdapter(supportFragmentManager)115 b_product_images_container.adapter = mSectionsPagerAdapter116 showImages(product.categories)117 }118 private fun showImages(items: ArrayList<String>) {119 b_categories_container_buy.layoutManager = GridLayoutManager(this, items.size)120 val imageItemAdapters = items.map(this::createCategoryItemAdapter)121 b_categories_container_buy.adapter = MainListAdapter(imageItemAdapters)122 }123 private fun createCategoryItemAdapter(category: String)124 = CategoryAdapter(category,125 { rtrue(category) })126 private fun rtrue (category: String): Boolean {127 return true128 }129 inner class SectionsPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {130 override fun getItem(position: Int): Fragment {131 // getItem is called to instantiate the fragment for the given page.132 // Return a PlaceholderFragment (defined as a static inner class below).133 return PlaceholderFragment.newInstance(position , product.photo_urls)134 }135 override fun getCount(): Int {136 // Show 5 total pages.(we will use 5 pages so change it to 5)137 return num_images138 }139 }140 class PlaceholderFragment : Fragment() {141 override fun onCreateView(142 inflater: LayoutInflater, container: ViewGroup?,143 savedInstanceState: Bundle?144 ): View? {145 val rootView = inflater.inflate(R.layout.fragment_product_image, container, false)146 val images = arguments!!.getStringArrayList(ARG_IMAGE_LIST)147 rootView.image_iv.loadImage(images[arguments!!.getInt(ARG_SECTION_NUMBER)])148 return rootView149 }150 companion object {151 /**152 * The fragment argument representing the section number for this153 * fragment.154 */155 private val ARG_SECTION_NUMBER = "section_number"156 private val ARG_IMAGE_LIST = "image_list"157 /**158 * Returns a new instance of this fragment for the given section159 * number.160 */161 fun newInstance(sectionNumber: Int, images: ArrayList<String?>): PlaceholderFragment {162 val fragment = PlaceholderFragment()163 val args = Bundle()164 args.putInt(ARG_SECTION_NUMBER, sectionNumber)165 args.putStringArrayList(ARG_IMAGE_LIST, images)166 fragment.arguments = args167 return fragment168 }169 }170 }171 companion object {172 private const val bullet = '\u2022'173 private const val PRODUCT_ARG = "com.example.kalepa.BuyProductActivity.ProductArgKey"174 fun getIntent(context: Context, product_id: String) = context175 .getIntent<ProductBuyActivity>()176 .apply { putExtra(PRODUCT_ARG, product_id) }177 fun start(context: Context, product_id: String) {178 val intent = getIntent(context, product_id)179 context.startActivity(intent)180 }181 }182 override fun onCreateOptionsMenu(menu: Menu): Boolean {183 val inflater = menuInflater184 if (SharedApp.prefs.isMod) {185 inflater.inflate(R.menu.mod_product_menu, menu)186 } else {187 inflater.inflate(R.menu.user_product_menu, menu)188 }189 return true190 }191 override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {192 R.id.n_upm_follow -> {193 val builder = AlertDialog.Builder(this)194 val dialogView = layoutInflater.inflate(R.layout.progress_dialog,null)195 val message = dialogView.findViewById<TextView>(R.id.message)196 message.text = "Siguiendo producto..."197 builder.setView(dialogView)198 builder.setCancelable(false)199 val dialog = builder.create()200 dialog.show()201 val url = MainActivity().projectURL + "/product/" + product.id.toString() + "/follow"202 val req = url.httpPost().header(Pair("Cookie", SharedApp.prefs.cookie))203 req.response { request, response, result ->204 when (result) {205 is Result.Failure -> {206 dialog.dismiss()207 toast("Ya sigues este producto")208 }209 is Result.Success -> {210 dialog.dismiss()211 toast("Añadido a tu lista de deseos")212 }213 }214 }215 true216 }217 R.id.n_upm_unfollow -> {218 val builder = AlertDialog.Builder(this)219 val dialogView = layoutInflater.inflate(R.layout.progress_dialog,null)220 val message = dialogView.findViewById<TextView>(R.id.message)221 message.text = "Siguiendo producto..."222 builder.setView(dialogView)223 builder.setCancelable(false)224 val dialog = builder.create()225 dialog.show()226 val url = MainActivity().projectURL + "/product/" + product.id.toString() + "/unfollow"227 val req = url.httpPost().header(Pair("Cookie", SharedApp.prefs.cookie))228 req.response { request, response, result ->229 when (result) {230 is Result.Failure -> {231 dialog.dismiss()232 toast("No sigues este producto")233 }234 is Result.Success -> {235 dialog.dismiss()236 toast("Eliminado de tu lista de deseos")237 }238 }239 }240 true241 }242 R.id.n_upm_report -> {243 reportProduct()244 true245 }246 R.id.n_mpm_ban -> {247 banProduct()248 true249 }250 else -> {251 super.onOptionsItemSelected(item)252 }253 }254 private fun reportProduct() {255 val view = layoutInflater.inflate(R.layout.dialog_report_product, null)256 val window = PopupWindow(257 view, // Custom view to show in popup window258 LinearLayout.LayoutParams.WRAP_CONTENT, // Width of popup window259 LinearLayout.LayoutParams.WRAP_CONTENT // Window height260 )261 window.isFocusable = true262 //Blur the background263 val fcolorNone = ColorDrawable(resources.getColor(R.color.transparent))264 val fcolorBlur = ColorDrawable(resources.getColor(R.color.transparentDark))265 n_productBuy_container.foreground = fcolorBlur266 window.showAtLocation(267 n_productBuy_header, // Location to display popup window268 Gravity.CENTER, // Exact position of layout to display popup269 0, // X offset270 0 // Y offset271 )272 val cancel = view.findViewById<Button>(R.id.n_drp_cancelar)273 val report = view.findViewById<Button>(R.id.n_drp_reportar)274 val reason = view.findViewById<EditText>(R.id.n_drp_reason)275 report.setOnClickListener {276 if (!reason.text.toString().equals("")) {277 val builder = AlertDialog.Builder(this)278 val dialogView = layoutInflater.inflate(R.layout.progress_dialog,null)279 val message = dialogView.findViewById<TextView>(R.id.message)280 message.text = "Enviando report..."281 builder.setView(dialogView)282 builder.setCancelable(false)283 val dialog = builder.create()284 dialog.show()285 val jsonObject = JSONObject()286 jsonObject.accumulate("user_id", user.id)287 jsonObject.accumulate("product_id", product.id)288 jsonObject.accumulate("reason", reason.text.toString())289 val url = MainActivity().projectURL + "/report"290 val req = url.httpPost().body(jsonObject.toString()).header(Pair("Cookie", SharedApp.prefs.cookie))291 req.httpHeaders["Content-Type"] = "application/json"292 req.response { request, response, result ->293 when (result) {294 is Result.Failure -> {295 dialog.dismiss()296 toast("Error enviando report")297 }298 is Result.Success -> {299 dialog.dismiss()300 toast("Report enviado")301 }302 }303 }304 window.dismiss()...
SearchFragment.kt
Source:SearchFragment.kt
...11import com.example.kalepa.R12import com.example.kalepa.models.RawProduct13import com.github.kittinunf.fuel.android.extension.responseJson14import com.github.kittinunf.fuel.httpGet15import com.github.kittinunf.fuel.httpPost16import com.github.kittinunf.result.Result17import kotlinx.android.synthetic.main.fragment_search.*18import org.jetbrains.anko.support.v4.toast19import org.jetbrains.anko.toast20import org.json.JSONArray21import org.json.JSONObject22class SearchFragment: Fragment() {23 private var category: String = ""24 private var serverCategories = ArrayList<String>()25 companion object {26 fun newInstance(): SearchFragment {27 return SearchFragment()28 }29 }30 override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =31 inflater.inflate(R.layout.fragment_search, container, false)32 override fun onActivityCreated(savedInstanceState: Bundle?) {33 super.onActivityCreated(savedInstanceState)34 val builder = AlertDialog.Builder(context!!)35 val dialogView = layoutInflater.inflate(R.layout.progress_dialog,null)36 val message = dialogView.findViewById<TextView>(R.id.message)37 message.text = "Cargando..."38 builder.setView(dialogView)39 builder.setCancelable(false)40 val dialog = builder.create()41 dialog.show()42 val url = MainActivity().projectURL + "/categories"43 val req = url.httpGet().header(Pair("Cookie", SharedApp.prefs.cookie))44 req.responseJson { request, response, result ->45 when (result) {46 is Result.Failure -> {47 toast("Error cargando categorÃas")48 dialog.dismiss()49 MainActivity.start(context!!)50 }51 is Result.Success -> {52 val jsonObject = result.value53 val aux = jsonObject.get("list").toString()54 val separate = aux.split("""(\",\")|(\[\")|(\"\])""".toRegex())55 serverCategories = ArrayList(separate.slice(IntRange(1,separate.size-2)))56 dialog.dismiss()57 }58 }59 }60 m_search_category_button.setOnClickListener{61 showCategoryDialog()62 }63 m_button_search.setOnClickListener {64 searchProducts()65 }66 }67 private fun searchProducts() {68 val builder = AlertDialog.Builder(context!!)69 val dialogView = layoutInflater.inflate(R.layout.progress_dialog,null)70 val message = dialogView.findViewById<TextView>(R.id.message)71 message.text = "Buscando productos..."72 builder.setView(dialogView)73 builder.setCancelable(false)74 val dialog = builder.create()75 dialog.show()76 val title = m_search_title.text.toString()77 var min = 078 var max = 079 val descript = m_search_descript.text.toString()80 val category = m_search_category.text.toString()81 val place = m_search_place.text.toString()82 if(!m_search_priece_min.text.toString().equals("")) {83 min = m_search_priece_min.text.toString().toInt()84 }85 if(!m_search_priece_max.text.toString().equals("")) {86 max = m_search_priece_max.text.toString().toInt()87 }88 val jsonObject = JSONObject()89 jsonObject.accumulate("price_min", min)90 if (max != 0 && max > min) {91 jsonObject.accumulate("price_max", max)92 }93 if(!descript.equals("")){94 jsonObject.accumulate("descript", descript)95 }96 if(!category.equals("")){97 jsonObject.accumulate("category", category)98 }99 if(!place.equals("")){100 jsonObject.accumulate("place", place)101 }102 val url = MainActivity().projectURL + "/search/products/adv"103 val req = url.httpPost().body(jsonObject.toString()).header(Pair("Cookie", SharedApp.prefs.cookie))104 req.httpHeaders["Content-Type"] = "application/json"105 req.responseJson { request, response, result ->106 when (result) {107 is Result.Failure -> {108 dialog.dismiss()109 toast("Error en la búsqueda")110 }111 is Result.Success -> {112 dialog.dismiss()113 loadProducts(result.value)114 }115 }116 }117 }...
SettingsFragment.kt
Source:SettingsFragment.kt
...14import com.example.kalepa.R15import com.github.kittinunf.fuel.android.extension.responseJson16import com.github.kittinunf.fuel.httpDelete17import com.github.kittinunf.fuel.httpGet18import com.github.kittinunf.fuel.httpPost19import com.github.kittinunf.fuel.httpPut20import com.github.kittinunf.result.Result21import kotlinx.android.synthetic.main.fragment_settings.*22import org.jetbrains.anko.support.v4.toast23import org.json.JSONObject24class SettingsFragment: Fragment() {25 companion object {26 fun newInstance(): SettingsFragment {27 return SettingsFragment()28 }29 }30 override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =31 inflater.inflate(R.layout.fragment_settings, container, false)32 override fun onActivityCreated(savedInstanceState: Bundle?) {33 super.onActivityCreated(savedInstanceState)34 n_settings_delete_user.setOnClickListener {35 checkPassword()36 }37 }38 private fun checkPassword() {39 val view = layoutInflater.inflate(R.layout.dialog_password, null)40 val window = PopupWindow(41 view, // Custom view to show in popup window42 LinearLayout.LayoutParams.WRAP_CONTENT, // Width of popup window43 LinearLayout.LayoutParams.WRAP_CONTENT // Window height44 )45 window.isFocusable = true46 //Blur the background47 val fcolorNone = ColorDrawable(resources.getColor(R.color.transparent))48 val fcolorBlur = ColorDrawable(resources.getColor(R.color.transparentDark))49 n_settings_container.foreground = fcolorBlur50 window.showAtLocation(51 n_settings_header, // Location to display popup window52 Gravity.CENTER, // Exact position of layout to display popup53 0, // X offset54 0 // Y offset55 )56 val cancel = view.findViewById<Button>(R.id.n_dp_cancel)57 val delete = view.findViewById<Button>(R.id.n_dp_delete)58 val password = view.findViewById<EditText>(R.id.n_dp_password)59 delete.setOnClickListener {60 if (password.text.toString().equals("")) {61 toast("Introduzca la contraseña")62 } else {63 val builder = AlertDialog.Builder(context!!)64 val dialogView = layoutInflater.inflate(R.layout.progress_dialog,null)65 val message = dialogView.findViewById<TextView>(R.id.message)66 message.text = "Comprobando contraseña..."67 builder.setView(dialogView)68 builder.setCancelable(false)69 val dialog = builder.create()70 dialog.show()71 val url = MainActivity().projectURL + "/login"72 val jsonObject = JSONObject()73 jsonObject.accumulate("nick", SharedApp.prefs.username)74 jsonObject.accumulate("pass", password.text.toString())75 jsonObject.accumulate("remember", false)76 val req = url.httpPost().body(jsonObject.toString())77 req.httpHeaders["Content-Type"] = "application/json"78 req.response { request, response, result ->79 when (result) {80 is Result.Failure -> {81 dialog.dismiss()82 toast("La contraseña no es correcta")83 }84 is Result.Success -> {85 dialog.dismiss()86 deleteUser()87 }88 }89 }90 window.dismiss()...
LoginActivity.kt
Source:LoginActivity.kt
...7import android.os.Bundle8import android.widget.TextView9import com.github.kittinunf.fuel.Fuel10import com.github.kittinunf.fuel.httpGet11import com.github.kittinunf.fuel.httpPost12import com.github.kittinunf.result.Result13import kotlinx.android.synthetic.main.activity_login.*14import org.jetbrains.anko.toast15import org.json.JSONObject16class LoginActivity : AppCompatActivity() {17 override fun onCreate(savedInstanceState: Bundle?) {18 super.onCreate(savedInstanceState)19 setContentView(R.layout.activity_login)20 m_login_button_login.setOnClickListener {21 if(logUser()) {22 MainActivity.start(this)23 }24 }25 m_login_button_register.setOnClickListener {26 RegisterActivity.start(this)27 }28 }29 private fun logUser () : Boolean {30 val builder = AlertDialog.Builder(this)31 val dialogView = layoutInflater.inflate(R.layout.progress_dialog,null)32 val message = dialogView.findViewById<TextView>(R.id.message)33 message.text = "Comprobando usuario..."34 builder.setView(dialogView)35 builder.setCancelable(false)36 val dialog = builder.create()37 dialog.show()38 val url = MainActivity().projectURL + "/login"39 val jsonObject = JSONObject()40 jsonObject.accumulate("nick", m_userEditText.text.toString())41 jsonObject.accumulate("pass", m_passwordEditText.text.toString())42 jsonObject.accumulate("remember", m_CheckBox.isChecked)43 val req = url.httpPost().body(jsonObject.toString())44 req.httpHeaders["Content-Type"] = "application/json"45 var exito = false46 req.response { request, response, result ->47 when (result) {48 is Result.Failure -> {49 dialog.dismiss()50 toast("Usuario o contraseña no validos")51 }52 is Result.Success -> {53 MySqlHelper(this).addCookie(response.httpResponseHeaders["Set-Cookie"]!![0])54 dialog.dismiss()55 MainActivity.start(this)56 exito = true57 }...
RegistrarUsuarioActivity.kt
Source:RegistrarUsuarioActivity.kt
...5import android.widget.Toast6import androidx.appcompat.app.AppCompatActivity7import com.beust.klaxon.Klaxon8import com.github.kittinunf.fuel.httpGet9import com.github.kittinunf.fuel.httpPost10import com.github.kittinunf.result.Result11import kotlinx.android.synthetic.main.activity_main.*12import kotlinx.android.synthetic.main.activity_registrar_usuario.*13class RegistrarUsuarioActivity : AppCompatActivity() {14 override fun onCreate(savedInstanceState: Bundle?) {15 super.onCreate(savedInstanceState)16 setContentView(R.layout.activity_registrar_usuario)17 val urlCrearUsuario = "http://172.31.104.142:1337/usuario"18 btn_create_account.setOnClickListener {19 val parametrosCrearUsuario = listOf(20 "nombre_completo" to txt_fullname.text.toString(),21 "correo_electronico" to txt_email.text.toString(),22 "contrasena" to txt_password.text.toString()23 )24 urlCrearUsuario25 .httpPost(parametrosCrearUsuario)26 .responseString { request, response, result ->27 when(result){28 is Result.Failure -> {29 val error = result.getException()30 Log.i("http","Error: ${error}")31 }32 is Result.Success ->{33 val usuarioString = result.get()34 Log.i("http","${usuarioString}")35 val intentExplicito = Intent(36 this,37 MainActivity::class.java38 )39 startActivity(intentExplicito)...
MainActivity.kt
Source:MainActivity.kt
...3import android.os.Bundle4import android.util.Log5import com.example.loginapi.databinding.ActivityMainBinding6import com.github.kittinunf.fuel.httpGet7import com.github.kittinunf.fuel.httpPost8class MainActivity : AppCompatActivity() {9 private val binding: ActivityMainBinding by lazy {10 ActivityMainBinding.inflate(layoutInflater)11 }12 override fun onCreate(savedInstanceState: Bundle?) {13 super.onCreate(savedInstanceState)14 setContentView(binding.root)15 "https://jsonplaceholder.typicode.com/posts".httpGet()16 .responseString{request, response, result ->17 result.fold({18 binding.textid.text =it19 },{20 })21 }22 val body =23 """24 {25 "user":"10",26 "id":"96",27 "title":"api",28 }29 """30 "https://jsonplaceholder.typicode.com/posts".httpPost()31 .body(body)32 .responseString { _, _, result ->33 result.fold({34 Log.d("MainActivity","successful")35 },{36 })37 }38 }39}...
EndActivity.kt
Source:EndActivity.kt
1package com.example.pathhunt.pathhuntkotlin2import android.content.Intent3import android.support.v7.app.AppCompatActivity4import android.os.Bundle5import com.github.kittinunf.fuel.httpPost6import com.google.gson.Gson7import kotlinx.android.synthetic.main.activity_end.*8class EndActivity : AppCompatActivity() {9 override fun onCreate(savedInstanceState: Bundle?) {10 super.onCreate(savedInstanceState)11 setContentView(R.layout.activity_end)12 txtEndScore.text = "Your score is: ${prefs.teamScore.toString()}!"13 val team = Team(null, prefs.teamName, prefs.teamScore)14 CreateTeam(Api().urlTeams, team)15 /*Api().urlTeams.httpPost()16 .jsonBody(Gson().toJson(team))17 .response {_,_, result ->18 println("result: " + result.toString())19 }*/20 btnEnd.setOnClickListener {21 val intent = Intent(this, MainActivity::class.java)22 startActivity(intent)23 }24 }25 private fun CreateTeam(URL: String ,team: Team) {26 URL.httpPost()27 .jsonBody(Gson().toJson(team))28 .response {_,_, result ->29 println("result: " + result.toString())30 }31 }32}...
httpPost
Using AI Code Generation
1 public void httpPost(String url, String data) {2 try {3 HttpClient httpclient = new DefaultHttpClient();4 HttpPost httppost = new HttpPost(url);5 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);6 nameValuePairs.add(new BasicNameValuePair("data", data));7 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));8 HttpResponse response = httpclient.execute(httppost);9 } catch (ClientProtocolException e) {10 } catch (IOException e) {11 }12 }13 }14 public void sendData(View view) {15 String data = "data";16 new HttpPostTask().execute(data);17 }18 public void sendData(View view) {19 String data = "data";20 new HttpPostTask().execute(data);
httpPost
Using AI Code Generation
1 public void sendData(View view){2 EditText editText = (EditText) findViewById(R.id.editText);3 String message = editText.getText().toString();4 Toast.makeText(this, message, Toast.LENGTH_SHORT).show();5 httpPost(message);6 }7}
httpPost
Using AI Code Generation
1 private void httpPost(String url, String data) {2 try {3 HttpClient client = new DefaultHttpClient();4 HttpPost post = new HttpPost(url);5 post.setEntity(new StringEntity(data));6 post.setHeader("Content-type", "application/json");7 HttpResponse response = client.execute(post);8 String result = EntityUtils.toString(response.getEntity());9 tv.setText(result);10 } catch (Exception e) {11 e.printStackTrace();12 }13 }14 private void httpGet(String url) {15 try {16 HttpClient client = new DefaultHttpClient();17 HttpGet get = new HttpGet(url);18 HttpResponse response = client.execute(get);19 String result = EntityUtils.toString(response.getEntity());20 tv.setText(result);21 } catch (Exception e) {22 e.printStackTrace();23 }24 }25}
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!