class FirstActivity : AppCompatActivity() {
companion object{
val USER_KEY="FirstActivity"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_first)
button_firstActivity.setOnClickListener {
val string:String=textView_first.text.toString()
val intent=Intent(this,MainActivity::class.java)
intent.putExtra(USER_KEY,string)
startActivity(intent)
}
}
}
class MainActivity : AppCompatActivity() {
companion object{
val MAINUSERKEY="MainActivity"
var str:String=""
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
str=intent.getStringExtra(FirstActivity.USER_KEY)
textview_main.text=str
button_Run.setOnClickListener {
val edittextstring=editText1.text.toString()
val intent=Intent(this,MainActivity::class.java)
intent.putExtra(MAINUSERKEY,edittextstring)
startActivity(intent)
}
}
}
Hello every one! I am new to Android programming with Kotlin.
I have two activities, suppose A and B. I want to start activity B from A and when B starts, it will display the TextView string of A into TextView_Main.
It is working fine now. I want to start activity B again on clicking button_Run which is on Activity B and passing a string again which I entered in edittext of Activity B. And now it should be displayed on textview of Activity B, when it opens again.
Please help me do this.
The problem is that the edittext string is being stored as an intent extra with name MAINUSERKEY="MainActivityā€¯, which is different from the extra you are currently extracting on your MainActivity, the one with name USER_KEY="FirstActivityā€¯. So I would do something like this to ensure I get the correct string extra:
str = with(intent) {
getStringExtra(FirstActivity.USER_KEY) ?: getStringExtra(MainActivity.MAINUSERKEY) ?: "No string extra was found"
}
it is more clear to startActivity like code below, add this code in ActivityB
companion object{
private const val EXTRA_ MAIN_USERKEY = "EXTRA.MAIN_USERKEY"
fun getIntent(context:Context, userKey:String): Intent
{
val intent = Intent(context,ActivityB::class.java)
intent.putExtra(EXTRA_ MAIN_USERKEY, userKey)
return intent
}
}
and this code in ActivityA:
startActivity(ActivityB.getIntent(this,"some key"))
so every time you start activityB you should pass the string
Related
I'm newbie in coding, so I want to ask more experienced programmers how to do it right.
I have 2 functions, first from Facebook SDK and second from AppsFlyerLib.
Can you tell me if there is right option to wait results from this functions please.
Here example of code:
class MainActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
super.onCreate(savedInstanceState, persistentState)
var linkdataPlusApps = ""
//Getting Link Data
val linkdataHandler = object : AppLinkData.CompletionHandler {
override fun onDeferredAppLinkDataFetched(appLinkData: AppLinkData?) {
linkdataPlusApps += appLinkData.toString()
}
}
AppLinkData.fetchDeferredAppLinkData(this, linkdataHandler)
//Gettings Apps
val appsdataHandler = object : AppsFlyerConversionListener {
override fun onConversionDataSuccess(p0: MutableMap<String, Any>?) {
linkdataPlusApps += p0.toString()
}
override fun onConversionDataFail(p0: String?) {}
override fun onAppOpenAttribution(p0: MutableMap<String, String>?) {}
override fun onAttributionFailure(p0: String?) {}
}
AppsFlyerLib.getInstance().init("APPS_KEY", appsdataHandler, this).start(this)
//Here I wanna take this data and put in another activity
val intent = Intent(this, NextActivity::class.java)
intent.putExtra("FetchedData", linkdataPlusApps)
startActivity(intent)
}}
But this code doesn't work because Activity started before data was fetched so string is empty.
I solved this by chaining code, but I'm sure that is dirty-coding.
How I did
class MainActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
super.onCreate(savedInstanceState, persistentState)
var linkdataPlusApps = ""
//Getting Link Data
val linkdataHandler = object : AppLinkData.CompletionHandler {
override fun onDeferredAppLinkDataFetched(appLinkData: AppLinkData?) {
linkdataPlusApps += appLinkData.toString()
val appsdataHandler = object : AppsFlyerConversionListener {
override fun onConversionDataSuccess(p0: MutableMap<String, Any>?) {
linkdataPlusApps += p0.toString()
val intent = Intent(this#MainActivity, NextActivity::class.java)
intent.putExtra("FetchedData", linkdataPlusApps)
startActivity(intent)
}
override fun onConversionDataFail(p0: String?) {}
override fun onAppOpenAttribution(p0: MutableMap<String, String>?) {}
override fun onAttributionFailure(p0: String?) {}
}
AppsFlyerLib.getInstance().init("APPS_KEY", appsdataHandler, this#MainActivity).start(this#MainActivity)
}
}
AppLinkData.fetchDeferredAppLinkData(this, linkdataHandler)
}
}
So code starts from fetching AppLinkData, and when fetched, starting fetching apps, and only then starting second activity with right string.
Can I do it in another way?
In my Jetpack Compose project I have two activities: ActivityA and ActivityB. I can pass data from ActivityA to ActivityB easily, as follows:
private fun showContinueDialog(indexSent: Int, messageSent: String){
val intent = Intent(this, ActivityB::class.java)
intent.putExtra("indexSent", indexSent)
intent.putExtra("messageSent", messageSent)
startForResult.launch(intent)
}
and:
private val startForResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
if (result.resultCode == Activity.RESULT_OK) {
val intent = result.data
if (intent != null) {
//I expect to receive data here
}
}
}
In ActivityB I have:
lateinit var intent2: Intent
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
.......
intent2 = intent}
#Composable
fun ContinueClicked(indexReturn: Int) {
intent2.putExtra("indexSent", indexReturn)
setResult(Activity.RESULT_OK, intent2)
startActivity(intent2)
this.finish()
}
When ActivityB closes, I expect to receive the result (an Integer) to appear in the ActivityResult block of ActivityA, but it does not happen. How can I return data from ActivityB to the ActivityResult block of ActivityA? Thanks!
I figured it out:
In the second activity, add something like this where the activity terminates:
intent.putExtra("indexSent", 7788)
setResult(Activity.RESULT_OK, intent)
this.finish()
I have a issue in getting a list returned in observe event in my activity. i am developing a login screen in MVVM. viewmodel is as follows.
my problem is i can get returned data in observe call back into a UI control. but same data returned assign into a list variable is empty. in other words, list returned unable to pass into a a list variable in an activity.
class LoginViewModel #Inject internal constructor (private val loginRepository: LoginRepository,private val usersRepository: UsersRepository): ViewModel() {
private var _userEmail:MutableLiveData<String>
private var _userPassword:MutableLiveData<String>
private var _userLoginData:MutableLiveData<UserLoginData>
private var allUsers:MutableLiveData<List<Users>>
private var findUser:MutableLiveData<List<Users>>
init{
_userEmail= MutableLiveData()
_userPassword= MutableLiveData()
_userLoginData= MutableLiveData()
allUsers= MutableLiveData()
findUser= MutableLiveData()
}
fun getEmail():LiveData<String>{
return _userEmail
}
fun getPassword():MutableLiveData<String>{
return _userPassword
}
fun userLogin(userEmail:String,userPassword:String):MutableLiveData<UserLoginData>{
_userEmail.postValue(userEmail)
_userPassword.postValue(userPassword)
viewModelScope.launch(Dispatchers.IO) {
var userlogindata:UserLoginData=loginRepository.userLogin(userEmail,userPassword)
_userLoginData.postValue(userlogindata)
}
return _userLoginData
}
fun getAllUsers():MutableLiveData<List<Users>>{
//lateinit var _allUsers:List<Users>
viewModelScope.launch(Dispatchers.IO) {
val _allUsers:List<Users> =usersRepository.getUsers()
allUsers.postValue(_allUsers)
}
return allUsers
}
fun findUser(userEmail:String):MutableLiveData<List<Users>>{
//lateinit var finduser:List<Users>
viewModelScope.launch(Dispatchers.IO) {
val _findUser:List<Users> =usersRepository.findUser(userEmail)
findUser.postValue(_findUser)
}
return findUser
}
}
in an activity i am observing the users list and getting the list into a list variable in the activity. code in the activity:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var loginViewModel: LoginViewModel
lateinit var loginData:UserLoginData
var users:List<Users> = emptyList()
var findUser:List<Users> = emptyList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
loginViewModel = ViewModelProvider(this).get(LoginViewModel::class.java)
/*observe users list*/
loginViewModel.getAllUsers().observe(this, {It->
users=It
binding.textView.text=It[0].email.toString()
})
loginViewModel.findUser(binding.loginEditTextTextEmailAddressTxt.toString().trim()).observe(this,{it->
findUser=it
})
This program failed if i use data in the users or findUser lists.
Kindly help me to find the best practice in getting the changed data from viewmodel into an activity
ViewModel:
data class User(
var name: String
)
private val _allUsers = MutableLiveData<List<User>>()
private val allUsers: LiveData<List<User>> get() = _allUsers
fun fetchAllUsers(): LiveData<List<User>> {
viewModelScope.launch {
//delay is simulating network request delay
delay(1000)
//listOf is simulating usersRepository.getUsers()
_allUsers.value = listOf(User("name1"), User("name2"), User("name3"))
}
return allUsers
}
Fragment:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.fetchAllUsers().observe(viewLifecycleOwner) { userList ->
userList.forEach {
Log.d("user", it.name)
}
}
You can try this way but I do not prefer returning liveData with function because you have to observe liveData once. You need to be careful observe once.
I have Firebase Realtime Database images displayed in a reyclerview. When users click that image, I want it to send the image to another activity's IMAGEVIEW and open that activity at the same time.
These are pictures of an example I saw on Youtube
As you can see in the second picture. It sent the data from the recyclerview to the imageview in the activity and opened that activity.
My adapter class
class AbstractAdapter(private val mContext: Context, private val abstractList: ArrayList<Abstract>) :
RecyclerView.Adapter<AbstractAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.abstract_image_view, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.imageView.setOnClickListener {
val intent = Intent(mContext, PreviewActivity::class.java)
intent.putExtra("abstract", abstractList[position].abstract.toString())
mContext.startActivity(intent)
}
holder.download_btn.setOnClickListener { }
Glide.with(mContext)
.load(abstractList[position].abstract)
.into(holder.imageView)
}
override fun getItemCount(): Int {
return abstractList.size
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val imageView: ImageView = itemView.findViewById(R.id.abstractImageView)
val download_btn: Button = itemView.findViewById(R.id.abstractDownloadBtn)
}
companion object {
private const val Tag = "RecyclerView"
}
Activity to receive image
class PreviewActivity : AppCompatActivity() {
private lateinit var previewImage: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_preview)
previewImage = findViewById(R.id.preview_image)
val previewImage: ImageView = findViewById(R.id.preview_image)
val bundle :Bundle? = intent.extras
val preview = bundle!!.getString("abstract")
}
Data model
class Abstract(var abstract: String? = null) {
}
I've tried running this code, but it doesn't show my image in the next activity. The Logcat doesn't give me any error, because according to it my code is running perfectly except that it's not showing the image in the next activity. I must be missing something, but I don't know what it is.
You have to set the image url to ImageView using Glide in second activity like this:
class PreviewActivity : AppCompatActivity() {
private lateinit var previewImage: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_preview)
previewImage = findViewById(R.id.preview_image)
val previewImage: ImageView = findViewById(R.id.preview_image)
val bundle :Bundle? = intent.extras
val preview = bundle!!.getString("abstract")
Glide.with(this)
.load(preview)
.into(previewImage)
}
I want to get input from the user using EditText and pass it to server and show the response to the user. I do this simply without any architecture but I would like to implement it in MVVM.
this is my repository code:
class Repository {
fun getData(context: Context, word: String): LiveData<String> {
val result = MutableLiveData<String>()
val request = object : StringRequest(
Method.POST,
"https://jsonplaceholder.typicode.com/posts",
Response.Listener {
result.value = it.toString()
},
Response.ErrorListener {
result.value = it.toString()
})
{
#Throws(AuthFailureError::class)
override fun getParams(): MutableMap<String, String> {
val params = HashMap<String, String>()
params["word"] = word
return params
}
}
val queue = Volley.newRequestQueue(context)
queue.add(request)
return result
}
}
and these are my View Model codes:
class ViewModel(application: Application) : AndroidViewModel(application) {
fun getData(word: String): LiveData<String> {
val repository = Repository()
return repository.getData(getApplication(), word)
}
}
and my mainActivity would be like this:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val model = ViewModelProviders.of(this).get(ViewModel::class.java)
model.getData("test").observe(this, Observer {
Log.i("Log", "activity $it")
})
}
}
My layout has an EditText which I want to get user input and pass it to the server, how should i do that?
Here how i did it in my projet.
You can probably use android annotations.
It's gonna requiere you to put some dependencies and maybe change the class a bit, but then you gonna link your Viewmodel with your repository and then you gonna have to program the setter of the variable to do a notifyChange() by making the class herited from BaseObservable. Then in the xml, if you did the correctly, you should be able to do a thing like text:"#={model.variable}" and it should be updating at the same time.
A bit hard and explain or to show for me sorry, but i would look into Android Annotations with #DataBinding, #DataBound :BaseObservable
https://github.com/androidannotations/androidannotations/wiki/Data-binding-support
Hope that can help a bit!