This is the Kotlin main activity, which is having problems receiving data from the second activity (posted after this)
class MainActivity : AppCompatActivity() {
private val LOG_TAG = MainActivity::class.java.simpleName
val EXTRA_MESSAGE = "com.example.android.twoactivities.extra.MESSAGE"
val TEXT_REQUEST = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun launchSecondActivity(view: View) {
Log.d(LOG_TAG, "Button clicked!")
val intent = Intent(this, SecondActivity::class.java)
val message = "${editText_main.text}"
intent.putExtra(EXTRA_MESSAGE, message)
Toast.makeText(applicationContext, intent.getStringExtra(EXTRA_MESSAGE), Toast.LENGTH_LONG).show()
startActivityForResult(intent, TEXT_REQUEST)
editText_main.text.clear()
}
public override fun onActivityResult(requestCode: Int, resultCode: Int,
data: Intent?
) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == TEXT_REQUEST) {
if (resultCode == RESULT_OK) {
val reply = intent.getStringExtra(SecondActivity().EXTRA_REPLY)
(findViewById<TextView>(R.id.text_header_reply) as TextView).setVisibility(View.VISIBLE)
(findViewById(R.id.text_message_reply) as TextView).setText(reply)
}
}
}
}
This is the second activity,
class SecondActivity : AppCompatActivity() {
val TEXT_REQUEST = 1
val EXTRA_REPLY = "com.example.android.twoactivities.extra.REPLY"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
var message = intent.getStringExtra(MainActivity().EXTRA_MESSAGE)
val textView2 = findViewById(R.id.text_message) as TextView
if (textView2 != null) {
textView2.setText(message)
}
}
fun returnReply(view: View) {
val intent = Intent(this, MainActivity::class.java)
val reply = "${editText_second.text}"
intent.putExtra(EXTRA_REPLY, reply)
setResult(RESULT_OK,intent)
Toast.makeText(applicationContext, intent.getStringExtra(EXTRA_REPLY), Toast.LENGTH_LONG).show()
startActivityForResult(intent, TEXT_REQUEST)
finish()
}
}
What's wrong with the code? The TEXT_REQUEST and RESULT CODE aren't passing
Remove this code from SecondActivity:
startActivityForResult(intent, TEXT_REQUEST)
and in MainActivity.onActivityResult() change this:
val reply = intent.getStringExtra(SecondActivity().EXTRA_REPLY)
to this:
val reply = data.getStringExtra(SecondActivity().EXTRA_REPLY)
You are trying to get the returned "reply" from the wrong Intent.
Remove startActivityForResult(intent, TEXT_REQUEST) from second activity and check what result are you getting?
Related
Hi I am new to android development and the problem is Whenever I am using MainActivity in logcat as a filter it is not showing me Log statements for this Log.i(TAG, "TAG on Fb")(my tag is also MainActivity) and Log.i(TAG, "onitemclick $position") for this it is shown by its function that is onItemClick but the same happen with this statement whenever I am trying to filter it on the basis of MainActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
userMaps = generateSampleData() as MutableList<user>
//set layout manager on the screen => RV
rvmaps.layoutManager = LinearLayoutManager(this)
//set adapter on RV
mapAdapter = mapadapter(this, userMaps, object: mapadapter.OnClickListener{
override fun onitemclick(position: Int) {
Log.i(TAG, "onitemclick $position")
val intent = Intent(this#MainActivity, googlemaps::class.java)
// here we will use putextra which help us to put extra data to another activity through data
intent.putExtra(user_data_map, userMaps[position])
startActivity(intent)
}
})
rvmaps.adapter = mapAdapter
fabcreatemap.setOnClickListener{
Log.i(TAG, "TAG on Fb")
val intent = Intent(this#MainActivity, createmap::class.java)
intent.putExtra(user_map_title, "new map name")
startActivityForResult(intent, requestcode)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if(requestcode == requestCode && resultCode == Activity.RESULT_OK)
{
val usermap = data?.getSerializableExtra(user_data_map) as user
// userMaps.add(usermap)
// mapAdapter.notifyItemChanged(userMaps.size-1)
}
super.onActivityResult(requestCode, resultCode, data)
}
}
class DetailActivity : AppCompatActivity() {
companion object {
const val EXTRA_USER = "extra_user"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detail)
val imgAvatar:CircleImageView = findViewById(R.id.img_dtlavtr)
val txtName:TextView = findViewById(R.id.txt_names)
val txtUname:TextView = findViewById(R.id.txt_uname)
val users = intent.getParcelableArrayListExtra<User>(EXTRA_USER) as ArrayList<User>
imgAvatar.setImageResource(users)
txtName.text
txtUname.text
}
}
It's my first time learning Android Studio and Kotlin,
Above is the second activity DetailActivity.kt, in the section I will display an image (imgAvatar.setImageresource(users)), an error appears
I use arraylist and parcelable to send data sets in the form of images and text
"Type missmatch
Required: Int
Found: kotlin.collection. ArrayList "
and here's the code for MainActivity.kt
class MainActivity : AppCompatActivity() {
private lateinit var adapter: UserAdapter
private lateinit var dataName: Array<String>
private lateinit var dataUname: Array<String>
private lateinit var dataAvatar: TypedArray
private var users = arrayListOf<User>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val listView: ListView = findViewById(R.id.lv_list)
adapter = UserAdapter(this)
listView.adapter = adapter
prepare()
addItem()
listView.onItemClickListener = AdapterView.OnItemClickListener {
_, _, position, _ ->
//Toast.makeText(this#MainActivity, users[position].name, Toast.LENGTH_SHORT).show()
val detailIntent = Intent(this#MainActivity, DetailActivity::class.java)
detailIntent.putParcelableArrayListExtra(EXTRA_USER, users)
startActivity(detailIntent)
}
}
private fun addItem() {
for (position in dataName.indices) {
val user = User(
dataAvatar.getResourceId(position, -1),
dataName[position],
dataUname[position]
)
users.add(user)
}
adapter.users = users
}
private fun prepare() {
dataName = resources.getStringArray(R.array.name)
dataUname = resources.getStringArray(R.array.username)
dataAvatar = resources.obtainTypedArray(R.array.avatar)
}
}
Firstly, please check the android documentations about imageview setImageResource
It only accepts a single resource integer. i.e. you can give image sources such as
setImageResource(R.drawable.yourImage)
R.drawable.yourImage actually is an int. That is why exception says you that it expects int however found list.
I'm a Beginner in Kotlin and I want a way to display Interstitial Ad every time I click on the button tvName, but on the contrary, the app crashes whenever I click on the button. I searched for the solution for a long time.
Here's MainActivity
import ...
#Suppress("UNREACHABLE_CODE")
class MainActivity : AppCompatActivity() {
lateinit var mAdView : AdView
var adapter:ChaptersAdapter?=null
var listOfChapters= ArrayList<Chapters>()
#SuppressLint("WrongViewCast")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
MobileAds.initialize(this) {}
mAdView = findViewById(R.id.adView)
val adRequest = AdRequest.Builder().build()
mAdView.loadAd(adRequest)
loadChapters()
adapter = ChaptersAdapter(listOfChapters, this)
lvchapters.adapter = adapter
MobileAds.initialize(this,
"ca-app-pub-3940256099942544~3347511713")
mInterstitialAd = InterstitialAd(this)
mInterstitialAd.adUnitId = "ca-app-pub-3940256099942544/1033173712"
mInterstitialAd.loadAd(AdRequest.Builder().build())
}
fun loadChapters(){
listOfChapters.add(Chapters(" Chapter 1 ", applicationContext.assets.open("Chapter0.txt").bufferedReader().use {
it.readText()
}
))
listOfChapters.add(Chapters(" Chapter 2 ", applicationContext.assets.open("Chapter1.txt").bufferedReader().use {
it.readText()
}
))
}
class ChaptersAdapter: BaseAdapter {
var context:Context?=null
var listOfChaptersLocal= ArrayList<Chapters>()
constructor(listOfChapters:ArrayList<Chapters>,context:Context){
listOfChaptersLocal=listOfChapters
this.context=context
}
override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View {
val chapters= listOfChaptersLocal[p0]
var inflator= context!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val chaptersView=inflator.inflate(R.layout.list_chapters,null)
chaptersView.tvName.text= chapters.name!!
chaptersView.**tvName.setOnClickListener** {
// **i want to show the Ads in this time frame** but like this example it didn't work
if (mInterstitialAd.isLoaded) {
mInterstitialAd.show()
} else {
Log.d("TAG", "The interstitial wasn't loaded yet.")
}
val intent =Intent(context,ChapterDetails::class.java)
intent.putExtra("name",chapters.name!!)
intent.putExtra("des",chapters.des!!)
context!!.startActivity(intent)
}
return chaptersView
}
override fun getItem(p0: Int): Any {
return listOfChaptersLocal[p0]
}
override fun getItemId(p0: Int): Long {
return p0.toLong()
}
override fun getCount(): Int {
return listOfChaptersLocal.size
}
}
}
I want to create a code to click on items of RecyclerView. I found one from Internet, however it keep getting this error:
None of the following functions can be called with the arguments supplied:
public open fun makeText(p0: Context!, p1: CharSequence!, p2: Int): Toast! defined in android.widget.Toast
public open fun makeText(p0: Context!, p1: Int, p2: Int): Toast! defined in android.widget.Toast
Here's my code:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
val users = ArrayList<User>()
val adapter = CustomAdapter(users)
recyclerView.adapter = adapter
recyclerView.addOnItemClickListener(object : OnItemClickListener {
override fun onItemClicked(position: Int, view: View) {
Toast.makeText(this, "Clicked on " + users.get(position).name, Toast.LENGTH_LONG).show()
}
})
}
interface OnItemClickListener {
fun onItemClicked(position: Int, view: View)
}
fun RecyclerView.addOnItemClickListener(onClickListener: OnItemClickListener) {
this.addOnChildAttachStateChangeListener(object : RecyclerView.OnChildAttachStateChangeListener {
override fun onChildViewDetachedFromWindow(view: View) {
view.setOnClickListener(null)
}
override fun onChildViewAttachedToWindow(view: View) {
view.setOnClickListener {
val holder = getChildViewHolder(view)
onClickListener.onItemClicked(holder.adapterPosition, view)
}
}
})
}
How can I fix that error message?
Toast.makeText(this#YOUR_ACTIVITY_NAME, "Clicked on " + users.get(position).name, Toast.LENGTH_LONG).show()
//In Activity use:
Toast.makeText(this#YOUR_ACTIVITY_NAME, "your message", Toast.LENGTH_LONG).show()
//In Fragments use:
Toast.makeText(requireActivity(), "your message", Toast.LENGTH_LONG).show()
Your problem will be solved...
does not set adapter and work it in Kotlin
I take data from retrofit and i test it ,it work.
but when pass array list to adapter,it cant set list
and have error:
kotlin.UninitializedPropertyAccessException: lateinit property adapters has not been initialized
myadapter:
class RecyclerSaleAdapter(var sale_list: ArrayList<sale_agahi>): RecyclerView.Adapter<RecyclerSaleAdapter.ViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.recycler_sale_item, parent, false)
return ViewHolder(v)
}
override fun getItemCount(): Int {
return sale_list.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.cost_view.text=sale_list[position].cost.toString()
holder.area.text=sale_list[position].area
holder.info_view.text=sale_list[position].info
holder.metr_view.text=sale_list[position].metr.toString()
}
class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
val ImageView=itemView.findViewById<ImageView>(R.id.image_sale_view)
val cost_view=itemView.findViewById<TextView>(R.id.cost_text_rec_view)
val area=itemView.findViewById<TextView>(R.id.area_text_rec_view)
val info_view=itemView.findViewById<TextView>(R.id.info_text_rec_view)
val metr_view=itemView.findViewById<TextView>(R.id.metr_text_rec_view)
val btn_rec_item=itemView.findViewById<Button>(R.id.btn_item_rec)
}
}
myactivity on create:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_profile)
val toolbar: Toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
val fab: FloatingActionButton = findViewById(R.id.fab)
fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
val navView: NavigationView = findViewById(R.id.nav_view)
val toggle = ActionBarDrawerToggle(
this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close
)
drawerLayout.addDrawerListener(toggle)
toggle.syncState()
//var intent=Intent(this,Profile::class.java)
var us= User_info()
us.name=intent.getStringExtra("username")
us.image_url=intent.getStringExtra("image")
user= User_info()
this.user =us
get_sales_list()
var rec=findViewById<RecyclerView>(R.id.rec_sale)
rec.layoutManager = LinearLayoutManager(this, LinearLayout.VERTICAL, false)
rec.adapter=adapters
navView.setNavigationItemSelectedListener(this)
}
and get data fun:
fun get_sales_list()
{
var retrofit = Retrofit.Builder()
.baseUrl("http://sobosha.ir/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val services=retrofit.create(Apiservices::class.java)
val call =services.sale_agahi(user.name.toString())
call.enqueue(object : Callback<sales_list> {
override fun onResponse(call: Call<sales_list>, response: retrofit2.Response<sales_list>) {
var temp:sales_list= response.body()!!
arr_sale= temp
Log.d("arr_sale",arr_sale.list[0].phone.toString())
adapters=RecyclerSaleAdapter(arr_sale.list)
}
override fun onFailure(call: Call<sales_list>, t: Throwable) {
Toast.makeText(applicationContext,t.message,Toast.LENGTH_LONG).show()
}
})
}
I have an error on rec.adapter=adapters
You only set adapters in the line
adapters=RecyclerSaleAdapter(arr_sale.list)
when Retrofit receives a response. The lines
var rec=findViewById<RecyclerView>(R.id.rec_sale)
rec.layoutManager = LinearLayoutManager(this, LinearLayout.VERTICAL, false)
rec.adapter=adapters
are executed after get_sales_list returns but the request is still likely enqueued or sent and the response is not received yet, so adapters isn't initialized.
One workaround would be to pass rec to get_sales_list and make it set rec.adapter instead of adapters. I'd prefer to e.g. make get_sales_list return Future<sales_list> or to make it suspend and return sales_list, but these would be more work.