How to connect two activities in Android Studio? - android-studio

I am trying to create a lonin page where you enter your email address and password. If they are correct you will be taken to another page (activity) but my app keeps crashing and I have tried everything but still stuck here.
My code is below, thank you in advance.
class MainActivity : AppCompatActivity() {
#SuppressLint("MissingInflatedId", "WrongViewCast")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btn = findViewById<Button>(R.id.btn1)
val email = findViewById<TextView>(R.id.email)
val password = findViewById<TextView>(R.id.password)
fun onClick(view: View) {
if (email.toString() == "safin" || password.toString() == "hallo") {
btn.setOnClickListener {
startActivity(Intent(this, MainActivity2::class.java))
}
} else {
email.error = "Your Email and your Password did not match!"
password.error = "Your Password and your Email did not match!"
}
}
}

Related

MainActivity is not showing log statements

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)
}
}

how to solve this startActivityForResult

how to solve this kind of problem starActivityForResult please any budy guide me to solve this
startActivityForResult is deprecated following is new the way. Here is a full source code example
MainActivity
class MainActivity : AppCompatActivity() {
private lateinit var tvResult:TextView
private lateinit var btnNext:Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
tvResult = findViewById(R.id.tv_result)
btnNext = findViewById(R.id.btn_next)
btnNext.setOnClickListener {
openActivityForResult(Intent(this,SampleActivity::class.java))
}
}
private var resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val mIntent: Intent? = result.data
val mDataString = mIntent?.getStringExtra("result_data")
tvResult.text = mDataString
}
}
private fun openActivityForResult(mIntent: Intent) {
resultLauncher.launch(mIntent)
}
}
SampleActivity
class SampleActivity : AppCompatActivity() {
private lateinit var btnDone: Button
private val sampleData = "Sample Activity Result Data"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sample)
btnDone = findViewById(R.id.btn_done)
btnDone.setOnClickListener{
returnForResult()
}
}
private fun returnForResult(){
val replyIntent = Intent()
replyIntent.putExtra(
"result_data",
sampleData
)
setResult(Activity.RESULT_OK, replyIntent)
finish()
}
}
startActivityForResult is deprecated, meaning that it will no longer be supported going forward. That is why Android Studio is showing you the lines through the code. Instead, review this Stackoverflow post on alternative options:
OnActivityResult method is deprecated, what is the alternative?

How To Show Interstitial Ads in The getView Function in Kotlin?

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

Rotating screen does not save text colour kotlin

I have a simple increment app. When you press on the button the number goes up. However i also made the number change to red once it's higher then 5.
I was able to get the number to save on rotation however the colour resets back to normal.
I'm not sure how i can also save the colour. Any ideas on how i can do this?
// number starts at 0
var num = 0
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val textView = findViewById<TextView>(R.id.textView)
val add = findViewById<Button>(R.id.button)
add.setOnClickListener {
++num
if(num > 5) {
textView.setTextColor(Color.parseColor("#FF0000"))
}
textView.setText(num.toString())
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt("int", num)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
if(savedInstanceState != null) {
num = savedInstanceState.getInt("int")
textView.setText(num.toString())
}
}
}
update this method onRestoreInstanceState
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
if(savedInstanceState != null) {
num = savedInstanceState.getInt("int")
if(num > 5){
textView.setTextColor(Color.parseColor("#FF0000"))
}
textView.setText(num.toString())
}
}

Activity not passing intent to onActivityResult()

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?

Resources