I want to make an app where you have to guess two numbers that eaquals a random number. But my app crash at the start because of java.lang.NumberFormatException: For input string: ""
val intNumber1 = etNumber1.text.toString().toInt() is the line that causes the crash. But I dont know what to do.
Here is my main activity:
//Buttons und Text initialisieren
private lateinit var btnCheck: Button
private lateinit var tvRndNumber: TextView
private lateinit var etNumber1: EditText
private lateinit var etNumber2: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Buttons und Text verknüpfen
btnCheck = findViewById(R.id.checkButton)
tvRndNumber = findViewById(R.id.randomNumber)
etNumber1 = findViewById(R.id.inputNumber1)
etNumber2 = findViewById(R.id.inputNumber2)
val intNumber1 = etNumber1.text.toString().toInt()
val intNumber2 = etNumber2.text.toString().toInt()
fun getRandomNumber(): Int {
return Random.nextInt(0,100)
}
var intRdnNumber = getRandomNumber()
tvRndNumber.text = intRdnNumber.toString()
fun checkNumbers(num1: Int, num2: Int){
if (num1 + num2 == intRdnNumber) {
tvRndNumber.text = "Richtig"
}
else {
Toast.makeText(this,"Probier es nochmal", Toast.LENGTH_LONG).show()
}
}
btnCheck.setOnClickListener {
checkNumbers(intNumber1, intNumber2)
}
Try like the following
//....
val intNumber1 = etNumber1.text.toString()
val intNumber2 = etNumber2.text.toString()
//.....
btnCheck.setOnClickListener {
if(intNumber1.isNotEmpty && intNumber2.isNotEmpty{
checkNumbers(intNumber1.toInt(), intNumber2.toInt())
}else{
// input filed is empty
// show message or do nothing
}
}
val intNumber1 = if(etNumber1.text.isNotEmpty()) {
etNumber1.text.toString().toInt()
} else {
0
}
val intNumber2 = if(etNumber2.text.isNotEmpty()) {
etNumber2.text.toString().toInt()
} else {
0
}
Related
It loads fine at startup but when I navigate to other fragments and go back to Home Fragment, the recycler view doesn't load anymore. It loads fine with other fragments when I navigate back to it, only the recycler view of Home Fragment doesn't show. There is no error showing in the logcat. Only this W/RecyclerView: No adapter attached; skipping layout. Anyone can help me? I don't know what's really wrong here. Thank you in advance guys.
Here is my code of HOME FRAGMENT
class HomeFragment : Fragment() {
private lateinit var homeViewModel: HomeViewModel
var recyclerView:RecyclerView?=null
lateinit var swipeUpToRefresh:SwipeRefreshLayout
private var viewPager:LoopingViewPager?=null
private var layoutAnimationController:LayoutAnimationController?=null
private var _binding: FragmentHomeBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
homeViewModel =
ViewModelProvider(this).get(HomeViewModel::class.java)
_binding = FragmentHomeBinding.inflate(inflater, container, false)
val root: View = binding.root
val key = requireArguments().getString("restaurant")
initView(root)
refreshPage()
//bind data
homeViewModel.getPopularList(key!!).observe(viewLifecycleOwner, {
val listData = it
val adapter = MyPopularCategoriesAdapter(requireContext(), listData)
recyclerView!!.adapter = adapter
recyclerView!!.layoutAnimation = layoutAnimationController
})
homeViewModel.getBestDealList(key).observe(viewLifecycleOwner, {
val adapter = MyBestDealsAdapter(requireContext(), it, false)
viewPager!!.adapter = adapter
})
return root
}
private fun refreshPage() {
val key = requireArguments().getString("restaurant")
swipeUpToRefresh.setOnRefreshListener {
//bind data
homeViewModel.getPopularList(key!!).observe(viewLifecycleOwner, {
val listData = it
val adapter = MyPopularCategoriesAdapter(requireContext(), listData)
recyclerView!!.adapter = adapter
recyclerView!!.layoutAnimation = layoutAnimationController
})
homeViewModel.getBestDealList(key).observe(viewLifecycleOwner, {
val adapter = MyBestDealsAdapter(requireContext(), it, false)
viewPager!!.adapter = adapter
})
swipeUpToRefresh.isRefreshing = false
}
}
private fun initView(root:View) {
swipeUpToRefresh = root.findViewById(R.id.refresh) as SwipeRefreshLayout
layoutAnimationController = AnimationUtils.loadLayoutAnimation(context, R.anim.layout_item_from_left)
viewPager = root.findViewById(R.id.viewpager) as LoopingViewPager
recyclerView = root.findViewById(R.id.recycler_popular) as RecyclerView
recyclerView!!.setHasFixedSize(true)
recyclerView!!.layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
}
override fun onResume() {
super.onResume()
viewPager!!.resumeAutoScroll()
}
override fun onPause() {
viewPager!!.pauseAutoScroll()
super.onPause()
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}}
I added this line of code to my HomeActivity in R.id.nav_home
val bundle = Bundle()
bundle.putString("restaurant",Common.currentRestaurant!!.uid)
navController.navigate(R.id.nav_home,bundle)
here Is my navView
navView!!.setNavigationItemSelectedListener { p0 ->
p0.isChecked = true
drawer!!.closeDrawers()
if (p0.itemId == R.id.nav_sign_out) {
signOut()
} else if (p0.itemId == R.id.nav_restaurant) {
if (menuItemClick != p0.itemId)
navController.popBackStack()
navController.navigate(R.id.nav_restaurant)
} else if (p0.itemId == R.id.nav_home) {
if (menuItemClick != p0.itemId) {
EventBus.getDefault().postSticky(MenuInflateEvent(true))
navController.popBackStack()
val bundle = Bundle()
bundle.putString("restaurant",Common.currentRestaurant!!.uid)
navController.navigate(R.id.nav_home,bundle)
}
} else if (p0.itemId == R.id.nav_cart) {
if (menuItemClick != p0.itemId) {
EventBus.getDefault().postSticky(MenuInflateEvent(true))
navController.popBackStack()
navController.navigate(R.id.nav_cart)
}
} else if (p0.itemId == R.id.nav_menu) {
if (menuItemClick != p0.itemId) {
EventBus.getDefault().postSticky(MenuInflateEvent(true))
navController.popBackStack()
navController.navigate(R.id.nav_menu)
}
} else if (p0.itemId == R.id.nav_view_order) {
if (menuItemClick != p0.itemId) {
EventBus.getDefault().postSticky(MenuInflateEvent(true))
navController.popBackStack()
navController.navigate(R.id.nav_view_order)
}
} else if (p0.itemId == R.id.nav_update_info) {
showUpdateDialog()
}
menuItemClick = p0.itemId
true
}
Try doing this
private fun initView(root:View) {
swipeUpToRefresh = root.findViewById(R.id.refresh) as SwipeRefreshLayout
layoutAnimationController = AnimationUtils.loadLayoutAnimation(context, R.anim.layout_item_from_left)
viewPager = root.findViewById(R.id.viewpager) as LoopingViewPager
recyclerView = root.findViewById(R.id.recycler_popular) as RecyclerView
//Here is where you need to initialize an adapter to the recyclerView
recylerView!!.adapter = MyPopularCategoriesAdapter(requireContext(), listData) //I'm not sure what is the second argument of your adapter. Feel free to change it as you like.
recyclerView!!.setHasFixedSize(true)
recyclerView!!.layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
}
So I am using CameraSource to preview camera scan in my application, but the problem is that the camera preview is always horizontal. TO be more clear look at this picture:
Preview
I mean the preview is just always tilted. How do I make the camera scan preview upwards (normal) ?
This is my current code:
private fun setupCameraSource() {
cameraSource = CameraSource.Builder(activity, cameraSourceCustomDetector)
.setAutoFocusEnabled(true).setRequestedFps(10F)
.setFacing(CameraSource.CAMERA_FACING_BACK).build()
}
Or if the whole code helps, I don't know if I'm doing it wrong.
class colorDetector(activity: Activity, cameraPreview: ImageView?, editCameraPreview: ImageView?) {
private val TAG = "colorDetector"
private var bitmap:Bitmap? = null
private val FPS: Number = 20
private var cameraSource: CameraSource? = null
private var cameraSourceCustomDetector: CustomDetector? = null
private var editCameraPreview: ImageView? = null
//private var visionUtilities: VisionUtilities? = null
private var activity: Activity? = null
private var cameraPreview: ImageView? = null
init {
this.activity = activity
this.cameraPreview = cameraPreview
this.editCameraPreview = editCameraPreview
cameraSourceCustomDetector = CustomDetector()
setupCameraSource()
}
private fun setupCameraSource() {
cameraSource = CameraSource.Builder(activity, cameraSourceCustomDetector)
.setAutoFocusEnabled(true).setRequestedFps(10F)
.setFacing(CameraSource.CAMERA_FACING_BACK).build()
}
fun start(context: Context) {
try {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
cameraSource?.start()
}
} catch (e: IOException) {
Log.d(TAG, "Couldn't start camera")
}
}
fun stop() {
cameraSource!!.stop()
}
fun saveImageToStorage() {
saveImgInStorage(bitmap!!,activity!!)
}
fun uploadImageToFirebase(type: uploadType) {
uploadPictureToFirebaseStorage(activity!!,bitmap,null,type)
}
inner class CustomDetector : Detector<Point>() {
#RequiresApi(Build.VERSION_CODES.O)
override fun detect(frame: Frame?): SparseArray<Point>? {
val byteBuffer: ByteBuffer = frame!!.grayscaleImageData
val bytes: ByteArray = byteBuffer.array()
val w = frame.metadata.width
val h = frame.metadata.height
val yuvimage = YuvImage(bytes, ImageFormat.NV21, w, h, null)
val baos = ByteArrayOutputStream()
yuvimage.compressToJpeg(
Rect(0, 0, w, h),
100,
baos
) // Where 100 is the quality of the generated jpeg
val jpegArray = baos.toByteArray()
bitmap = BitmapFactory.decodeByteArray(jpegArray, 0, jpegArray.size)
activity?.runOnUiThread(Runnable{ getEditedImg(bitmap!!,w,h, cameraPreview!!, editCameraPreview!!,
activity!!
) })
return null
}
}
}
Well, in the end after a really long search, I've decided to do it like that, I'm not sure if it's the ideal way, but if someone wants, here is the solution I did:
I created a function called rotate:
// rotates a 'bitmap' clockwise direction by 'degree'
fun rotate(bitmap: Bitmap, degree: Float): Bitmap? {
val matrix = Matrix()
matrix.postRotate(degree)
val resizedBitmap = Bitmap.createScaledBitmap(bitmap, bitmap.width, bitmap.width, false)
return Bitmap.createBitmap(resizedBitmap, 0, 0, resizedBitmap.width, resizedBitmap.height, matrix, true)
}
And replaced the 3 places where bitmap with rotate(bitmap, 90F).
TYPE_STEP_COUNTER is not working with this code. Could anyone please tell me what is wrong.
My min sdk is 19 and target sdk is 30. I have also tried using TYPE_STEP_COUNTER instead number of 19 but it still does not work. Please help!!
I have been trying to debug this for hours now. I am using pixel 3 to test this and I see that the required sensor is here but for some reason this is not working.
class MainActivity : AppCompatActivity(), SensorEventListener, View.OnClickListener {
var running = false
private var sensorManager: SensorManager? = null
lateinit var sharebutton: Button
lateinit var goalnum: Button
lateinit var et: EditText
lateinit var tv: EditText
lateinit var progress: ProgressBar
lateinit var step2: EditText
var steps=0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.mainlayout)
sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
sharebutton = findViewById(R.id.share) as Button
tv = findViewById(R.id.tv) as EditText
sharebutton.setOnClickListener(this)
goalnum = findViewById(R.id.goalnum) as Button
goalnum.setOnClickListener(this)
val circularProgressBar = findViewById<CircularProgressBar>(R.id.progressBar)
val toolbar = findViewById(R.id.tbar) as Toolbar?
setSupportActionBar(toolbar)
getSupportActionBar()?.setTitle("");
//manualInc()
}
override fun onResume() {
//manualInc()
Toast.makeText(this, "I am in", Toast.LENGTH_SHORT).show()
super.onResume()
running = true;
var StepSensor = sensorManager?.getDefaultSensor(19)
if (StepSensor == null) {
Toast.makeText(this, "No Step Counter Sensor !", Toast.LENGTH_SHORT).show()
} else {
sensorManager?.registerListener(this, StepSensor, SensorManager.SENSOR_DELAY_UI)
}
}
fun manualInc(){
steps =100
var step2 = tv.getText().toString().toInt()
var steps3 = (step2 - steps)
tv_steps.setText("" + steps.toInt())
if (steps3 > 0) {
tv_steps2.setText("" + (steps3).toInt());
} else {
tv_steps2.setText("Goal Reached!");
}
val currentsteps = step2 - steps.toInt()
progressBar.apply{
setProgressWithAnimation(currentsteps.toFloat())
}
if(steps> step2) {
Toast.makeText(this, "GOAL REACHED!!! Amazing job!", Toast.LENGTH_LONG).show()
}
}
override fun onPause() {
super.onPause()
running = true;
var StepSensor = sensorManager?.getDefaultSensor(19)
if (StepSensor == null) {
Toast.makeText(this, "No Step Counter Sensor !", Toast.LENGTH_SHORT).show()
} else {
sensorManager?.registerListener(this, StepSensor, SensorManager.SENSOR_DELAY_UI)
}
}
override fun onClick(view: View?) {
when (view?.id) {
R.id.goalnum -> {
var goalcount = tv.getText().toString().toDouble()
userinput.setText("" + goalcount.toInt())
Toast.makeText(this, "Great goal!", Toast.LENGTH_LONG).show()
}
R.id.share -> {
val sendIntent: Intent = Intent().apply {
var goalcount = tv.getText().toString().toInt()
action = Intent.ACTION_SEND
putExtra(
Intent.EXTRA_TEXT,
"I am on my way to reaching my goal of " + goalcount + " daily steps! Join me on Step Counter and Tracker"
)
type = "text/plain"
}
startActivity(Intent.createChooser(sendIntent, null))
}
}
}
override fun onAccuracyChanged(p0: Sensor?, p1: Int) {
}
override fun onSensorChanged(event: SensorEvent) {
Toast.makeText(this, "I am i", Toast.LENGTH_LONG).show()
if (running) {
val steps = (event.values[0])
var step2 = tv.getText().toString().toInt()
var steps3 = (step2 - steps)
tv_steps.setText("" + steps.toInt())
if (steps3 > 0) {
tv_steps2.setText("" + (steps3).toInt());
} else {
tv_steps2.setText("Goal Reached!");
}
val currentsteps = step2 - steps.toInt()
progressBar.apply{
setProgressWithAnimation(currentsteps.toFloat())
}
if(steps> step2) {
Toast.makeText(this, "GOAL REACHED!!! Amazing job!", Toast.LENGTH_LONG).show()
}}}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater: MenuInflater = menuInflater
inflater.inflate(R.menu.menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle presses on the action bar menu items
when (item.itemId) {
R.id.action_one -> {
val intent = Intent(this, MainActivity::class.java)
finishAffinity();
startActivity(intent)
}
R.id.action_two -> {
val intent = Intent(this, ExerciseHistory::class.java)
startActivity(intent)
}
R.id.action_three -> {
val intent = Intent(this, ViewListContents::class.java)
startActivity(intent)
}
R.id.action_four -> {
val intent = Intent(this, StepHistory::class.java)
startActivity(intent)
}
R.id.action_five -> {
val intent = Intent(this, Help::class.java)
startActivity(intent)
Toast.makeText(
this,
"Please leave feedback!",
Toast.LENGTH_SHORT
).show()
}
}
return super.onOptionsItemSelected(item)
}
}
Hello everyone please help me i am try to modify link but it's not working. it's working on java but recently i convert java to kotlin and getting this error.
am trying to change my link http://www.offertoro.com/click_track/api?offer_id=419393&pub_id=14&pub_app_id=5&USER_ID=[USER_ID]&GAID=[your_GAID] in [USER_ID] with current login user email but getting error.
Check Screenshot
Screenshot
Error
None of the following functions can be called with the arguments supplied.
CharSequence.replace(Regex, String) defined in kotlin.text
String.replace(String, String, Boolean = ...) defined in kotlin.text
My code
fun modifyOfferLink() {
val id = mAuth!!.currentUser!!.email
// Modifying Offer Link Acording to Offer Partner
when (partner) {
"ogads" -> Finallink = link + "&aff_sub5=" + mAuth!!.currentUser!!.email
"offertoro" -> Finallink = link.replace("[USER_ID]", mAuth!!.currentUser!!.email)
"none" -> {
Finallink = link!!.replace("[USER_ID]", mAuth!!.currentUser!!.email)
}
else -> Finallink = link.replace("[USER_ID]", mAuth!!.currentUser!!.email)
}
}
OfferActivity.kt
package com.sgamer.creditsk.Activity
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.google.firebase.auth.FirebaseAuth
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.loopj.android.http.AsyncHttpClient
import com.loopj.android.http.AsyncHttpResponseHandler
import com.loopj.android.http.RequestParams
import com.sgamer.creditsk.Activity.AndyConstants.ServiceType
import com.sgamer.creditsk.Activity.OfferDetailsActivity
import com.sgamer.creditsk.R
import com.sgamer.creditsk.Utils.*
import cz.msebera.android.httpclient.Header
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
class OfferDetailsActivity constructor() : AppCompatActivity() {
var Finallink: String? = null
var package_id: String? = null
var uniq_id: String? = null
var offerid: String? = null
var app_name: String? = null
var description: String? = null
var icon_url: String? = null
var bg_image_url: String? = null
var amount: String? = null
var OriginalAmount: String? = null
var link: String? = null
var partner: String? = null
var insTitle: String? = null
var first_text: String? = null
var second_text: String? = null
var third_text: String? = null
var fourth_text: String? = null
var webview: Boolean? = null
var ClickId: String? = null
var ctx: OfferDetailsActivity? = null
var later: TextView? = null
var status_image: ImageView? = null
var mAuth: FirebaseAuth? = null
private val bannerAdManager: BannerAdManager_SK? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_offer_details)
val toolbar: Toolbar = findViewById<View>(R.id.toolbar) as Toolbar
val adContainer: LinearLayout = findViewById<View>(R.id.adView) as LinearLayout
setSupportActionBar(toolbar)
val bannerAdManager_SK: BannerAdManager_SK = BannerAdManager_SK(this#OfferDetailsActivity, adContainer)
bannerAdManager_SK.BannerAds()
ctx = this
mAuth = FirebaseAuth.getInstance()
getSupportActionBar()!!.setTitle(R.string.offer_details)
getSupportActionBar()!!.setDisplayHomeAsUpEnabled(true)
getSupportActionBar()!!.setBackgroundDrawable(ColorDrawable(getResources().getColor(android.R.color.transparent)))
getSupportActionBar()!!.setElevation(0f)
if (Build.VERSION.SDK_INT >= 21) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
}
changeStatusBarColor()
initViews()
modifyOfferLink()
}
private fun changeStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val window: Window = getWindow()
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.setStatusBarColor(Color.TRANSPARENT)
}
}
fun initViews() {
val title: TextView = findViewById(R.id.title)
val desc: TextView = findViewById(R.id.description)
val instructionsTitle: TextView = findViewById(R.id.instructions)
val first: TextView = findViewById(R.id.first)
val second: TextView = findViewById(R.id.second)
val third: TextView = findViewById(R.id.third)
val fourth: TextView = findViewById(R.id.fourth)
val des: TextView = findViewById(R.id.des)
val complete_button: TextView = findViewById(R.id.complete_button)
val button: TextView = findViewById(R.id.button)
later = findViewById(R.id.later)
val comSpace: LinearLayout = findViewById(R.id.comSpace)
val offer_icon: ImageView = findViewById(R.id.offer_icon)
val bg_image: ImageView = findViewById(R.id.bg_image)
status_image = findViewById(R.id.status_image)
uniq_id = getIntent().getStringExtra("uniq_id")
offerid = getIntent().getStringExtra("offerid")
app_name = getIntent().getStringExtra("app_name")
package_id = getIntent().getStringExtra("package_id")
description = getIntent().getStringExtra("description")
icon_url = getIntent().getStringExtra("icon_url")
bg_image_url = getIntent().getStringExtra("bg_image_url")
amount = getIntent().getStringExtra("amount")
OriginalAmount = getIntent().getStringExtra("OriginalAmount")
link = getIntent().getStringExtra("link")
partner = getIntent().getStringExtra("partner")
first_text = getIntent().getStringExtra("first_text")
insTitle = getIntent().getStringExtra("instructionsTitle")
second_text = getIntent().getStringExtra("second_text")
third_text = getIntent().getStringExtra("third_text")
fourth_text = getIntent().getStringExtra("fourth_text")
webview = getIntent().getBooleanExtra("webview", false)
if (getIntent().hasExtra("description")) {
des.setText(getIntent().getStringExtra("description"))
} else {
des.setText(getIntent().getStringExtra("description"))
}
title.setText(app_name)
desc.setText(getString(R.string.earn) + " " + amount + " " + getString(R.string.app_currency) + " " + getString(R.string.on_this_offer))
Glide.with(this).load(icon_url)
.apply(RequestOptions().placeholder(R.drawable.placeholder_image).error(R.drawable.placeholder_image))
.into(offer_icon)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
comSpace.setElevation(20f)
}
instructionsTitle.setText(insTitle)
first.setText(first_text)
second.setText(second_text)
third.setText(third_text)
fourth.setText(fourth_text)
complete_button.setText(getResources().getString(R.string.complete_offer))
if (!bg_image_url!!.isEmpty()) {
Glide.with(this).load(bg_image_url).into(bg_image)
} else {
}
// On click Listners
later!!.setOnClickListener(object : View.OnClickListener {
public override fun onClick(view: View) {
finish()
}
})
complete_button.setOnClickListener(object : View.OnClickListener {
public override fun onClick(view: View) {
if (!App.isVPNConnected()) {
addoffer(amount, app_name + " Offer Credit", offerid)
}
AppUtils.parse(this#OfferDetailsActivity, Finallink)
}
})
button.setOnClickListener(object : View.OnClickListener {
public override fun onClick(view: View) {
val launchIntent: Intent? = getPackageManager().getLaunchIntentForPackage((package_id)!!)
startActivity(launchIntent)
}
})
isAppExist
if (isAppExist) {
complete_button.setVisibility(View.GONE)
button.setVisibility(View.VISIBLE)
} else {
button.setVisibility(View.GONE)
complete_button.setVisibility(View.VISIBLE)
}
}
fun addoffer(points: String?, Activity: String?, offerid: String?) {
val client: AsyncHttpClient = AsyncHttpClient()
val params: RequestParams = RequestParams()
val jsObj: JsonObject = Gson().toJsonTree(API()) as JsonObject
jsObj.addProperty("method_name", "user_offeradd")
jsObj.addProperty("offer_id", offerid)
jsObj.addProperty("email", mAuth!!.getCurrentUser()!!.getEmail())
jsObj.addProperty("points", points)
jsObj.addProperty("firebase_id", mAuth!!.getCurrentUser()!!.getUid())
jsObj.addProperty("Activity", Activity)
params.put("data", API.toBase64(jsObj.toString()))
client.post(Javaaescipher.decrypt(), params, object : AsyncHttpResponseHandler() {
public override fun onSuccess(statusCode: Int, headers: Array<Header>, responseBody: ByteArray) {
Log.d("Response", String(responseBody))
val res: String = String(responseBody)
try {
val jsonObject: JSONObject = JSONObject(res)
val jsonArray: JSONArray = jsonObject.getJSONArray("ANDROID_REWARDS_APP")
for (i in 0 until jsonArray.length()) {
val `object`: JSONObject = jsonArray.getJSONObject(i)
val success: String = `object`.getString("success")
val msg: String = `object`.getString("msg")
if ((success == "1")) {
// Toast.makeText(OfferDetailsActivity.this, msg, Toast.LENGTH_LONG).show();
} else {
// Toast.makeText(OfferDetailsActivity.this, msg, Toast.LENGTH_LONG).show();
}
}
} catch (e: JSONException) {
e.printStackTrace()
}
}
public override fun onFailure(statusCode: Int, headers: Array<Header>, responseBody: ByteArray, error: Throwable) {
Log.d("error", error.toString())
}
})
}
private val isAppExist: Boolean
private get() {
val pm: PackageManager = getPackageManager()
try {
val info: PackageInfo = pm.getPackageInfo((package_id)!!, PackageManager.GET_META_DATA)
} catch (e: PackageManager.NameNotFoundException) {
return false
}
return true
}
fun modifyOfferLink() {
val id = mAuth!!.currentUser!!.email
// Modifying Offer Link Acording to Offer Partner
when (partner) {
"ogads" -> Finallink = link + "&aff_sub5=" + mAuth!!.currentUser!!.email
"offertoro" -> Finallink = link!!.replace("[USER_ID]", mAuth!!.currentUser!!.email)
"none" -> {
Finallink = link!!.replace("[USER_ID]", mAuth!!.currentUser!!.email)
}
else -> Finallink = link!!.replace("[USER_ID]", mAuth!!.currentUser!!.email)
}
}
}
It is likely there is no sub-string that is exactly [USER_ID]. Are you sure is it not ["USER_ID"] ?
Can you print the value of link before you call the replace. This may let us and you see the problem.
I am a student, new to kotlin, so I am converting java codes to kotlin to learn and see how it works, but I didnt understand what the error says.
private val _songs = ArrayList<SongInfo>()
internal lateinit var recyclerView: RecyclerView
internal lateinit var seekBar: SeekBar
internal lateinit var songAdapter: SongAdapter
internal var mediaPlayer: MediaPlayer? = null
private val myHandler = Handler()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView = findViewById(R.id.recyclerView) as RecyclerView
seekBar = findViewById(R.id.seekBar) as SeekBar
songAdapter = SongAdapter(this, _songs)
recyclerView.adapter = songAdapter
val linearLayoutManager = LinearLayoutManager(this)
val dividerItemDecoration = DividerItemDecoration(recyclerView.context,
linearLayoutManager.orientation)
recyclerView.layoutManager = linearLayoutManager
recyclerView.addItemDecoration(dividerItemDecoration)
songAdapter.setOnItemClickListener { b, view, obj, position ->
if (b.text == "Stop") {
mediaPlayer!!.stop()
mediaPlayer!!.reset()
mediaPlayer!!.release()
mediaPlayer = null
b.text = "Play"
} else {
val runnable = Runnable {
try {
mediaPlayer = MediaPlayer()
mediaPlayer!!.setDataSource(obj.songUrl)
mediaPlayer!!.prepareAsync()
mediaPlayer!!.setOnPreparedListener { mp ->
mp.start()
seekBar.progress = 0
seekBar.max = mediaPlayer!!.duration
Log.d("Prog", "run: " + mediaPlayer!!.duration)
}
b.text = "Stop"
} catch (e: Exception) {
}
}
myHandler.postDelayed(runnable, 100)
}
}
checkUserPermission()
val t = runThread()
t.start()
}
inner class runThread : Thread() {
override fun run() {
while (true) {
try {
Thread.sleep(1000)
} catch (e: InterruptedException) {
e.printStackTrace()
}
Log.d("Runwa", "run: " + 1)
if (mediaPlayer != null) {
seekBar.post { seekBar.progress = mediaPlayer!!.currentPosition }
Log.d("Runwa", "run: " + mediaPlayer!!.currentPosition)
}
}
}
}
private fun checkUserPermission() {
if (Build.VERSION.SDK_INT >= 23) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 123)
return
}
}
loadSongs()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
123 -> if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
loadSongs()
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show()
checkUserPermission()
}
else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
private fun loadSongs() {
val uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
val selection = MediaStore.Audio.Media.IS_MUSIC + "!=0"
val cursor = contentResolver.query(uri, null, selection, null, null)
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
val name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME))
val artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST))
val url = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA))
val s = SongInfo(name, artist, url)
_songs.add(s)
} while (cursor.moveToNext())
}
cursor.close()
songAdapter = SongAdapter(this#MainActivity, _songs)
}
}
}
This is the error:
"Error:(46, 44) Type mismatch: inferred type is (???, ???, ???, ???)
-> Any but SongAdapter.OnItemClickListener was expected Error:(46, 46) Cannot infer a type for this parameter. Please specify it explicitly."
Batch conversion to Kotlin is not the best way to learn the language. I suggest you to re-implement your Android component in Kotlin manually, to get the feeling of language.
The error you see says: "I can not understand how this lambda with 4 parameters can be an instance of SongAdapter.OnItemClickListener, please help". You can try anonymous class in this place.