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?
Related
I am making this basic Notes App named Scribble
I wrote ViewModel class and all of its methods that is insert and delete are working fine but for some reason update method is not working, Its just not updating the passed note object
Please find code below :
First of all this is my Note i.e. Entity Class :
#Entity(tableName = "NotesTable")
data class Note constructor(
#ColumnInfo(name = "title") var noteTitle: String,
#ColumnInfo(name = "description") var noteDescription: String,
#ColumnInfo(name = "timeStamp") var timeStamp: String
):java.io.Serializable {
#PrimaryKey(autoGenerate = true)
#ColumnInfo(name = "id") var id : Int = 0
}
NoteViewModel Class :
class NoteViewModel (application: Application) : AndroidViewModel (application){
val allNotes: LiveData<List<Note>>
val repository: NoteRepository
init {
val dao = NoteDatabase.getDatabase(application).getNotesDao()
repository = NoteRepository(dao)
allNotes = repository.allNotes
}
fun insertNote(note: Note) {
viewModelScope.launch(Dispatchers.IO){
repository.insertNote(note)
}
}
fun deleteNote(note: Note) = viewModelScope.launch(Dispatchers.IO){repository.deleteNote(note)}
fun updateNote(note: Note) = viewModelScope.launch(Dispatchers.IO){repository.updateNote(note)}
Repository class :
class NoteRepository (private val noteDao: NoteDao) {
val allNotes : LiveData<List<Note>> = noteDao.getAllNotes()
suspend fun insertNote(note : Note){
noteDao.insert(note)
}
suspend fun deleteNote(note : Note){
noteDao.delete(note)
}
suspend fun updateNote(note : Note){
noteDao.update(note)
}
DAO class :
#Dao
public interface NoteDao {
#Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(note: Note)
#Update
fun update(note: Note)
#Delete
fun delete(note: Note)
#Query("Select * from NotesTable order by id ASC")
fun getAllNotes() : LiveData<List<Note>>
Now this is my EditNote Activity on which I come after clicking on a note card in my recycler view I am saving note when user presses back button after editing the note thus called updateNote method inside onDestroy :
class EditNoteActivity : AppCompatActivity() {
lateinit var titleOfNote : EditText
lateinit var bodyOfNote : EditText
lateinit var noteToUpdate: Note
lateinit var noteViewModel: NoteViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_edit_note)
noteViewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(application))[NoteViewModel::class.java]
titleOfNote = findViewById(R.id.titleEt)
bodyOfNote = findViewById(R.id.bodyEt)
noteToUpdate = intent.getSerializableExtra("noteObject") as Note
titleOfNote.setText(noteToUpdate.noteTitle)
bodyOfNote.setText(noteToUpdate.noteDescription)
}
fun updateNote(){
Log.d("AppLogs", "updateNote: called")
noteToUpdate.noteTitle = titleOfNote.text.toString()
noteToUpdate.noteDescription = bodyOfNote.text.toString()
val current = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy \nHH:mm")
noteToUpdate.timeStamp = current.format(formatter)
noteViewModel.updateNote(noteToUpdate)
}
override fun onDestroy() {
super.onDestroy()
Log.d("AppLogs", "onDestroy(updateNote): called")
updateNote()
}
I've used literally the same logic in AddNoteActivity and it works, it saves my note when i press back button and recycler view shows it perfectly
AddNoteActivity class :
class AddNoteActivity : AppCompatActivity() {
lateinit var noteTitle : EditText
lateinit var noteBody : EditText
lateinit var noteViewModel: NoteViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_note)
noteTitle = findViewById(R.id.noteTitleEt)
noteBody = findViewById(R.id.noteBodyEt)
noteViewModel = ViewModelProvider(this,ViewModelProvider.AndroidViewModelFactory.getInstance(application))[NoteViewModel::class.java]
}
fun saveNote(){
Log.d("AppLogs", "saveNote: called")
var titleOfNote : String = noteTitle.text.toString()
var bodyOfNote : String = noteBody.text.toString()
val current = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy \nHH:mm")
val timeStamp = current.format(formatter)
var note = Note(titleOfNote,bodyOfNote,timeStamp)
noteViewModel.insertNote(note)
}
override fun onStop() {
super.onStop()
Log.d("AppLogs", "onStop: called !")
saveNote()
}
}
means insertNote method from NoteViewModel works fine, similarly deleteNote also works fine, it deletes the note when I press delete button its just something wrong with updateNote method that I am not able to figure out
OTHER CLASSES ::::
NoteViewAdapter Class :
class NoteViewAdapter( allNotes : List<Note>, context: Context, clickListeners: ClickListeners)
: RecyclerView.Adapter<NoteViewAdapter.NoteViewHolder>() {
private val clickListeners : ClickListeners
private val context : Context
private var allNotes : List<Note>
init {
this.clickListeners = clickListeners
this.context = context
this.allNotes = allNotes
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int)
: NoteViewAdapter.NoteViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.note_row,parent,false)
return NoteViewHolder(itemView)
}
override fun onBindViewHolder(holder: NoteViewHolder, position: Int) {
holder.noteTitleTV.text = allNotes[position].noteTitle
holder.noteBodyTV.text = allNotes[position].noteDescription
holder.timeStampTV.text = allNotes[position].timeStamp
holder.deleteButton.visibility = View.INVISIBLE
holder.deleteButton.setOnClickListener {
clickListeners.onDeleteButtonClick(allNotes[position])
}
holder.itemView.setOnClickListener{
clickListeners.onNoteClick(allNotes[position])
}
holder.itemView.setOnLongClickListener{
holder.deleteButton.visibility = View.VISIBLE
val timer = Timer("schedule", true);
timer.schedule(2000) {
holder.deleteButton.visibility = View.INVISIBLE
}
return#setOnLongClickListener true
}
}
override fun getItemCount(): Int {
return allNotes.size
}
inner class NoteViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
val noteTitleTV: TextView = itemView.findViewById(R.id.titleTV)
val noteBodyTV: TextView = itemView.findViewById(R.id.bodyTV)
val deleteButton: FloatingActionButton = itemView.findViewById(R.id.deleteButton)
val timeStampTV : TextView = itemView.findViewById(R.id.timeStamp)
}
}
interface ClickListeners {
fun onNoteClick(note: Note)
fun onDeleteButtonClick(note: Note)
}
MainActivity class :
class MainActivity : AppCompatActivity(), ClickListeners {
lateinit var recyclerView : RecyclerView
lateinit var addButton : FloatingActionButton
lateinit var viewModel : NoteViewModel
lateinit var adapter : NoteViewAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView = findViewById(R.id.NotesRV)
addButton = findViewById(R.id.addButton)
viewModel = ViewModelProvider(this,ViewModelProvider.AndroidViewModelFactory.getInstance(application))[NoteViewModel::class.java]
viewModel.allNotes.observe(this, Observer {list ->
adapter = NoteViewAdapter(list ,this, this)
recyclerView.adapter = adapter
})
recyclerView.layoutManager = GridLayoutManager(this,2,GridLayoutManager.VERTICAL,false)
addButton.setOnClickListener{
val intent : Intent = Intent(this,AddNoteActivity::class.java)
startActivity(intent)
}
}
override fun onNoteClick(note: Note) {
val intent : Intent = Intent(this,EditNoteActivity::class.java)
intent.putExtra("noteObject",note)
startActivity(intent)
}
override fun onDeleteButtonClick(note: Note) {
viewModel.deleteNote(note)
}
Here I am passing note object with intent Extras because I implemented java.io.Serializable in Note class
When I click on note it opens edit note activity then I change the previous text set there, but when i press back button it doesnt update note
I used debug logs and found that both onDestroy and updateNote are getting called but still it is note updating my note
Also these lines from EditNoteActivity.kt are setting previous entered text in note after clicking on note card
titleOfNote.setText(noteToUpdate.noteTitle)
bodyOfNote.setText(noteToUpdate.noteDescription)
but for some reason this line isn't working
noteViewModel.updateNote(noteToUpdate)
Could somebody tell me what's wrong with my code? When I press the SignInButton, the Google sign in popup appears, but after selecting the account, the result is always RESULT_CANCELED.
class LoginActivity : AppCompatActivity() {
private lateinit var binding: ActivityLoginBinding
private lateinit var signInButton: SignInButton
private lateinit var textView: TextView
private lateinit var signInClient: GoogleSignInClient
private val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
// never comes here
textView.text = "Login result " + result.resultCode.toString()
}
else
textView.text = "Login result " + result.resultCode.toString()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityLoginBinding.inflate(layoutInflater)
setContentView(binding.root)
var gso: GoogleSignInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build()
signInClient = GoogleSignIn.getClient(this, gso)
textView = binding.textView
signInButton = binding.signInButton
signInButton.setOnClickListener {
launcher.launch(signInClient.signInIntent)
}
}
}
Did you try add Web Client OAuth2 in Credential ? And use Web Client ID like a param for signIn, like this:
var gso: GoogleSignInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken("YOUR_WEB_APPLICATION_CLIENT_ID")
.requestEmail()
.build()
or make sure you declare right dependency in gradle file
When I try to view the list of data coming from realtime firebase no information is displayed
My adapter:
class MarcacaoAdapter: RecyclerView.Adapter<MarcacaViewHolder>() {
private var items = listOf<Marcacao>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MarcacaViewHolder {
val view = LayoutInflater
.from(parent.context)
.inflate(R.layout.item_lista, parent, false)
return MarcacaViewHolder(view)
}
override fun onBindViewHolder(holder: MarcacaViewHolder, position: Int) {
holder.bind(items[position])
}
override fun getItemCount(): Int {
return items.size
}
}
My view holder:
class MarcacaViewHolder(view: View): RecyclerView.ViewHolder(view) {
private val textviewData = itemView.findViewById<TextView>(R.id.tvDataM)
private val textviewHora = itemView.findViewById<TextView>(R.id.tvHoraM)
fun bind (item: Marcacao){
textviewData.text = item.dia
textviewHora.text = item.hora
}
}
My activity list:
class ListaActivity : AppCompatActivity() {
private val adapterMarcacao = MarcacaoAdapter()
private var tvDataM: TextView? = null
private var tvHoraM: TextView? = null
private lateinit var mDatabaseReference: DatabaseReference
private lateinit var mRecycler : RecyclerView
private lateinit var mArrayList : ArrayList<Marcacao>
override fun onCreate(savedInstanceState : Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_lista)
mRecycler = findViewById(R.id.recyclerView)
mArrayList = arrayListOf<Marcacao>()
mDatabaseReference = FirebaseDatabase.getInstance().getReference("data")
}
}
I would like some help to identify why my recycler view is not loading information from firebase.
Why does navigation composable call twice? If I set a breakpoint on the Text I will get two stops when the app runs. Thank you for your answers.
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val navController = rememberNavController()
var i: Int = 0
NavHost(navController = navController, startDestination = "s1") {
composable("s1") {
i++
Text("$i")
}
}
}
}
}
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.