How can I make intent inside onAdDismissedFullScreenContent() kotlin - android-studio

I want when the player clicks on the imageView the ads should show first if its ready and then go to the next activity
here is my code
FalgQuizImageView.setOnClickListener {
if (mInterstitialAd != null) {
mInterstitialAd?.show(this)
}
mInterstitialAd?.fullScreenContentCallback = object: FullScreenContentCallback() {
override fun onAdDismissedFullScreenContent() {
val intent = Intent(this, QuizQuestionsCar::class.java)
startActivity(intent)
}
override fun onAdFailedToShowFullScreenContent(adError: AdError?) {
val intent = Intent(this, QuizQuestionsCar::class.java)
startActivity(intent)
}
}
}
Here is the error

First parameter on Intent constructor is of type Context, you are passing this which in your case refers to the FullScreenContentCallback object and its not of type Context. To fix this do the following
val intent = Intent(this#YourActivityName, QuizQuestionsCar::class.java)
this#YourActivityName refers to your Activity object, which is a Context

Related

can't use a toast message in the recyclerview

I am making recyclerview in kotlin in android studio. I'm trying to set up an event listener that puts a button in the recyclerview and outputs a toast message. Even if this#[activity name] is entered instead of this in context, a toast message is not displayed. What went wrong?
The error code is as follows.
Unresolved reference: #UpdateActivity
class UpdateActivity : AppCompatActivity() {
private val vBinding by lazy {ActivityUpdateBinding.inflate(layoutInflater)}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(vBinding.root)
var recyclerViewAdapter = CustomAdapter()
recyclerViewAdapter.listData = arrayListOf<String>("a", "b", "c")
vBinding.uploadedRecyclerView.adapter = recyclerViewAdapter
vBinding.uploadedRecyclerView.layoutManager = LinearLayoutManager(this)
} // onCreate End
class CustomAdapter:RecyclerView.Adapter<CustomAdapter.Holder>(){
var listData = arrayListOf<String>()
class Holder(val vBinding:UploadedRecyclerBinding):RecyclerView.ViewHolder(vBinding.root){
fun setData(name:String){
vBinding.name.text = name
vBinding.getBtn.setOnClickListener {
**Toast.makeText(this#UpdateActivity, "test", Toast.LENGTH_SHORT).show()**
// ↑A compilation error occurs here.**
}
}
} // Holder end
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
val vBinding = UploadedRecyclerBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return Holder(vBinding)
}
override fun onBindViewHolder(holder: Holder, position: Int) {
val name = listData[position]
holder.setData(name)
}
override fun getItemCount(): Int {
return listData.size
}
} // CustomAdapter end
} // UpdateActivity end
you could try put context into constructor of adapter when you create it, and use this context to show a toast. something like this:
class CustomAdapter(
private val mContext: Context
):RecyclerView.Adapter<CustomAdapter.Holder>(){
and in holder class:
Toast.makeText(mContext, "test", Toast.LENGTH_SHORT).show()
finally, when you create adapter in activity:
var recyclerViewAdapter = CustomAdapter(this)
Normally, we'll create adapter class in another file, so use this#UpdateActivity in adapter is bad idea
Instead of using the local context in Toast, always use applicationContext when showing it. So, you should replace that creation of Toast message as,
Toast.makeText(applicationContext, "test", Toast.LENGTH_SHORT).show()

Add marker in MapBox Android Studio

I have two Activity. I want pass LatLng pass to another Activity.
This code in first Activity:
public void testclick (View v){
Intent intent = new Intent(TestActivity.this, MainMenu.class);
intent.putExtra("lat", "58.37");
intent.putExtra("lan", "37.95");
startActivity(intent);
}
What I must write in another Activity to get LaTLng?
Intent intent = new Intent(getApplicationContext(), MainMenu.class);
intent.putExtra("lat", "`58.37`");
intent.putExtra("lan", "37.95")
startActivity(intent)
And MainMenu Activity onCreate() method receive
if(getIntent().getExtras() != null) {
String lat = getIntent().getExtras().getString("lat");
String lan = getIntent().getExtras().getString("lan");
}

How to Pagination using retrofit to fetch next items from API on Scrolling in kotlin?

I want to make my recyclerview paginationscrolling using retrofit.
I already complete get Json data using retrofit. It means interface API is correct from API Document.
However, if I loaded more 20items. can not scroll more items in Client.
when I checked Server data. per one page can get maximum 20items.
For example, if I loaded 25items in my recyclerview.
page 0: 20, page 1: 5.
if I want scrolling all items, How can I make paginationscrolling for retrofit??
check some my code and help me..
Response
Interface API
#GET("/store/cart/mine")
fun getCart(#Header("Authorization") token: String?, #Query("page") page:Int): Call<CartResponse>
CartViewActivity
class CartViewActivity : AppCompatActivity(), SwipeRefreshLayout.OnRefreshListener {
private val lastVisibleItemPosition: Int
get()= LinearLayoutManager.HORIZONTAL
private lateinit var scrollListener: RecyclerView.OnScrollListener
lateinit var mAdapter: CartItemRecyclerAdapter
#RequiresApi(Build.VERSION_CODES.N)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_cart_view)
val page = 0
val token = SharedPreference.getTokenInfo(this)
Client.retrofitService.getCart(token,page).enqueue(object :Callback<CartResponse> {
override fun onResponse(call: Call<CartResponse>, response: Response<CartResponse>) {
if (response?.isSuccessful == true) {
swipeRefreshLo.setOnRefreshListener(this#CartViewActivity)
showdata(response.body()?.docs!!)
}else if(response?.isSuccessful==false) {
val er = Gson().fromJson(response.errorBody()?.charStream(), ErrorResponse::class.java)
if (er.code==60202) {
}
}
}
override fun onFailure(call: Call<CartResponse>, t: Throwable) {
}
})
}
private fun showdata(results: MutableList<cartDocs>) {
recycler_view.apply {
mAdapter=CartItemRecyclerAdapter(context,context as Activity, results)
recycler_view.adapter=mAdapter
recycler_view.layoutManager=LinearLayoutManager(context)
setRecyclerViewScrollListener()
}
}
private fun setRecyclerViewScrollListener() {
scrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
val totalItemCount = recyclerView.layoutManager!!.itemCount
if(totalItemCount == lastVisibleItemPosition + 1) {
Log.d("MyTAG", "Load new list")
recyclerView.removeOnScrollListener(scrollListener)
}
}
}
}
override fun onRefresh() {
swipeRefreshLo.isRefreshing = false
}
}
Firstly, you need to modify your adapter to be able to update existing data, instead of creating new adapter every time you fetch new data.
Adapter should be initialised before getting the data, to be able to call methods on it.
You should create a method inside the adapter, something like
fun updateData(results: MutableList<cartDocs>) {
dataSet.addAll(results)
notifyItemRangeInserted(start, newItemsSize)
}
Then, we you get response from server in onSuccess() you should call method above, and increment page, so the next time you load data, you get new items.
Data should be fetched first time when screen loads (page will be 0), and then when user scrolls to bottom of RV ().

captured and displayed image on imageView, now i want to pass the imageView to another activity

This is my code on android studio using kotlin to capture and show image on main activity, I want that captured image to be displayed on my other activity. After image has been captured, the image will be displayed on the imageView on main Activity, now i want to pass that image to another activity using buttonClassify
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initializeTensorClassifier()
buttonRecognize.setOnClickListener {
setVisibilityOnCaptured(false)
cameraView.captureImage {
onImageCaptured(it)
}
buttonClassify.setOnClickListener{
val intent = Intent(this, classify::class.java)
startActivity(intent)
}
}
}
private fun onImageCaptured(it: CameraKitImage) {
val bitmap = Bitmap.createScaledBitmap(it.bitmap, INPUT_WIDTH, INPUT_HEIGHT, false)
showCapturedImage(bitmap)
classifier?.let {
try {
showRecognizedResult(it.recognizeImage(bitmap))
} catch (e: java.lang.RuntimeException) {
Log.e(TAG, "Crashing due to classification.closed() before the recognizer finishes!")
}
}
}
private fun showCapturedImage(bitmap: Bitmap?) {
runOnUiThread {
imageCaptured.visibility = View.VISIBLE
imageCaptured.setImageBitmap(bitmap)
}
}
If you store the image in a file, you can just pass the path to the file. If not, you can pass the Bitmap as a Parcelable in the Intent Extras.
private fun showCapturedImage(bitmap: Bitmap?) {
runOnUiThread {
imageCaptured.visibility = View.VISIBLE
imageCaptured.setImageBitmap(bitmap)
val nextActivityIntent = Intent(this, NextActivity::class.java).apply {
putExtra("captured_image", bitmap)
}
startActivity(nextActivityIntent)
}
}
Then in the next Activity you could retreive it like this:
override fun onCreate(savedInstance: Bundle?) {
...
val capturedImage = intent.extras.getParcelable("captured_image") as Bitmap?
/* Use bitmap as you wish */
}
Beware, large bitmaps can throw Exceptions when trying to be passed as Intent Extras, so consider saving the image and passing around the path.

kotlin.TypeCastException: null cannot be cast to non-null type error

I'm trying to get a info box working with Google Maps API. When trying to run the application, and adding a marker with custom info box it crashes.
Here is my code:
class MainMapsActivity : AppCompatActivity(), OnMapReadyCallback {
private lateinit var mMap: GoogleMap
private val test: ArrayList<String> = arrayListOf()
private var mLocationPermissionGranted: Boolean = false
private val PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: Int = 1234
// ^Number isnt definitive, as long as its unique inside the application
private val DEFAULT_ZOOM: Float = 15.0F
private var mLastKnownLocation: Location? = null
private val mDefaultLocation = LatLng(60.312491, 24.484248)
private lateinit var mFusedLocationProviderClient: FusedLocationProviderClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_maps)
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
}
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
getDeviceLocation()
//PRESSING WILL ADD MARKER
mMap.setOnMapClickListener(GoogleMap.OnMapClickListener { point ->
val builder: AlertDialog.Builder
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert)
} else {
builder = AlertDialog.Builder(this)
}
val marker = MarkerOptions().position(point)
builder.setTitle("Are you sure you want to add a map location here?")
.setMessage("Are you sure you want to add a map location here?")
.setPositiveButton(android.R.string.yes, DialogInterface.OnClickListener { dialog, which ->
mMap.addMarker(marker)
//CUSTOM MARKER
.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.pinetree_foreground))
})
.setNegativeButton(android.R.string.no, DialogInterface.OnClickListener { dialog, which ->
// do nothing
})
.show()
true
val mapInfoWindowFragment = supportFragmentManager.findFragmentById(R.id.infoWindowMap) as MapInfoWindowFragment
//Set Custom InfoWindow
val infoWindow = InfoWindow(point, InfoWindow.MarkerSpecification(0, 0), mapInfoWindowFragment)
// Shows the InfoWindow or hides it if it is already opened.
mapInfoWindowFragment.infoWindowManager()?.toggle(infoWindow, true);
})
And here is the error Logcat gives me:
kotlin.TypeCastException: null cannot be cast to non-null type com.example.sampo.luontoalueet.MapInfoWindowFragment
at com.example.sampo.luontoalueet.MainMapsActivity$onMapReady$1.onMapClick(MainMapsActivity.kt:123)
My question is how to change change this statement into non-null type?
val mapInfoWindowFragment = supportFragmentManager.findFragmentById(R.id.infoWindowMap) as MapInfoWindowFragment
Your findfragmentById is returning null (which indicates that your fragment does not exist).
If you're absolutely sure that fragment cannot be null at this point, you need to review your code. Maybe your fragment is not attached to supportFragmentManager?
If you want to handle a case where this fragment might not exist, You can use nullable cast as?:
val mapInfoWindowFragment = supportFragmentManager.findFragmentById(R.id.infoWindowMap) as? MapInfoWindowFragment
Then you can check conditionally if(mapInfoWindowFragment == null) and handle the null case.

Resources