问题:在使用界面从 activity2 向 activity1 发送数据时,未分配 activity1 中的发送数据,即使它已被分配。因此, activity1 成员变量将自动设置为null。
设置详细信息:在 activity1 中单击按钮时,启动 activity2 。现在,用户可以在 activity2 中执行任何工作。但是,只要用户在 activity2 中执行工作,我的自定义界面就会将数据发送到 activity1 。 Activity1应该将发送的值分配给它的成员变量,并且当用户导航回到 activity1 时,activity1的 onRestart() 方法被绑定用新值更新用户界面。
设置要点:
1-用户单击 ACTIVITY1
上的按钮2-按钮打开 ACTIVITY2
3-用户执行触发我的界面发送数据的操作
4-界面在后台将数据发送到 ACTIVITY1 (ACTIVITY2仍然可见)
5-已通过接口将发送的数据分配给 ACTIVITY1 成员变量(布尔值)
6-用户向后按下 ACTIVITY2 ,然后导航回 ACTIVITY1
触发 ACTIVITY1 的7- ONRESTART()
8- ONRESTART()检查布尔值是否正确,然后更新UI
但是,我的困惑开始了。 为什么,即使分配了布尔值,也仍然为空? 为什么为什么ACTIVITY1的成员变量丢失分配的值?
代码:
界面
override fun onReturnedToActivity(actionID: Int) {
when(actionID)
{
3 ->
{
newNoteCreated = true
}
}
}
ONRESTART()
override fun onRestart() {
super.onRestart()
if(newNoteCreated) //variable is null not true.
{
Toast.makeText(this,"TRUE",Toast.LENGTH_SHORT).show()
mDrawer!!.updateBadge(3, StringHolder(dbHandler.totalNotes().toString() ))
newNoteCreated = false
}
请教我这个问题。我一直试图在SO上找到它的解决方案,但还没有任何答案。我知道还有其他方法可以在活动之间发送数据,但是我正在尝试特别使用接口。
引用
https://developer.android.com/reference/android/app/Activity#ActivityLifecycle
“ 如果一个活动完全被另一个活动遮盖,则将其停止。该活动仍保留所有状态和成员信息,但是,对于用户而言,它不再可见是隐藏的,当其他地方需要内存时,它通常会被系统杀死。“
那为什么我的活动会丢失其可变数据?
编辑
主要活动(ACTIVITY1)
class MainActivity : AppCompatActivity(), ContextBarVisibilityListener, OnActionPerformedBadgeUpdater, ActivityReturningStateNotify {
private val dbHandler: PediaDatabase = PediaDatabase(this)
private var mDrawer: Drawer? = null
private var filePath: String? = null
private var backupFileName: String? = null
private var listBt: MenuItem? = null
private var gridBt: MenuItem? = null
private var frontAppName: TextView? = null
private var buttonStatePref: SharedPreferences? = null
private var speedDialView: SpeedDialView? = null
private var trashNotesCount: String? = null
private var archiveNotesCount: String? = null
private var onLayoutChange: LayoutChangeListener? = null
private var newNoteCreated: Boolean = false //THIS IS THE BOOL
private lateinit var mAdView: AdView
companion object
{
private const val LAYOUT_USER_PREF = "layout_preference"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
onLayoutChange = NotesFrag()
if(savedInstanceState == null) //prevents reloading fragment
{
val transaction = supportFragmentManager.beginTransaction()
transaction.add(R.id.innerFrameLayout,NotesFrag()).commit()
}
trashNotesCount = dbHandler.trashedNotesCount().toString()
archiveNotesCount = dbHandler.archivedNoteCount().toString()
val drawerTrashBt: PrimaryDrawerItem = PrimaryDrawerItem().withIdentifier(1).withName("Trash Bin")
.withIcon(R.drawable.delete_note_image)
.withBadge(trashNotesCount)
.withSelectedIcon(R.drawable.delete_drawer_selected)
val drawerArchiveBt: PrimaryDrawerItem = PrimaryDrawerItem().withIdentifier(2).withName("Archive")
.withIcon(R.drawable.archive_note_img)
.withBadge(archiveNotesCount)
.withSelectedIcon(R.drawable.archive_drawer_selected)
val drawerNotesBt: PrimaryDrawerItem = PrimaryDrawerItem().withIdentifier(3).withName("Notes")
.withIcon(R.drawable.notes_img)
.withBadge(dbHandler.totalNotes().toString())
.withSelectedIcon(R.drawable.notes_drawer_selected)
val drawerLockedNotesBt: PrimaryDrawerItem = PrimaryDrawerItem().withIdentifier(4).withName("Locked Notes")
.withIcon(R.drawable.lock_button)
.withBadge("1")
.withSelectedIcon(R.drawable.locked_drawer_selected)
val drawerReminderNotesBt: PrimaryDrawerItem = PrimaryDrawerItem().withIdentifier(5).withName("Reminder Notes")
.withIcon(R.drawable.reminder_notes)
.withBadge("1")
.withSelectedIcon(R.drawable.reminder_drawer_selected)
val drawerFavouriteNotesBt: PrimaryDrawerItem = PrimaryDrawerItem().withIdentifier(6).withName("Favourite Notes")
.withIcon(R.drawable.rate_app_star_img)
.withBadge("1")
.withSelectedIcon(R.drawable.favourite_drawer_selected)
val drawerSettingsBt: PrimaryDrawerItem = PrimaryDrawerItem().withIdentifier(7).withName("Settings")
.withIcon(R.drawable.settings_drawer)
mDrawer = DrawerBuilder().withActivity(this)
.withHeader(R.layout.navbar_header)
.addDrawerItems(drawerNotesBt,drawerArchiveBt,drawerTrashBt,
drawerLockedNotesBt,drawerReminderNotesBt,
drawerFavouriteNotesBt,DividerDrawerItem(), drawerSettingsBt)
.withOnDrawerItemClickListener(object: Drawer.OnDrawerItemClickListener{
override fun onItemClick(view: View?, position: Int, drawerItem: IDrawerItem<*, *>?): Boolean {
when(position)
{
1 ->
{
frontAppName!!.text = "Wonder Notes"
speedDialView!!.show() //show again because traversing to other fragments hides it
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.innerFrameLayout, NotesFrag())
transaction.addToBackStack(null)
transaction.commit()
}
2 ->
{
speedDialView!!.hide()
supportFragmentManager.beginTransaction().replace(R.id.innerFrameLayout,ArchiveFragment()).commit()
}
3 ->
{
frontAppName!!.text = "Trash"
speedDialView!!.hide()
fabLayoutBehaviourSetter(false)
supportFragmentManager.beginTransaction().replace(R.id.innerFrameLayout, TrashFragment()).commit()
}
4 -> Log.d("locked notes","1")
5 -> Log.d("reminder","1")
6 -> Log.d("favourite","1")
}
return false // false closes drawer on click
}
}).build()
/*Below code handles swipe tabs adapter setting and displaying
* and implements fragments to viewpager programitically */
// mainActivityViewPagerID.adapter = ViewPagerAdapter(supportFragmentManager)
// attachNotesFrag()
//mainTabsID.setupWithViewPager(mainActivityViewPagerID)
//mainTabsID.setTabTextColors(Color.DKGRAY, Color.parseColor("white"))
val drawerOpener = findViewById<ImageButton>(R.id.drawerOpenImgBt)
val noteCounterAsBt = findViewById<TextView>(R.id.showNotesCountID)
drawerOpener.setOnClickListener { mDrawer!!.openDrawer() }
noteCounterAsBt.setOnClickListener { mDrawer!!.openDrawer() }
//navigationView.setNavigationItemSelectedListener(this)
val customToolbar: Toolbar = findViewById(R.id.toolbarID)
setSupportActionBar(customToolbar)
supportActionBar!!.setDisplayShowTitleEnabled(false) //set main title off
val toolbarTxtView = findViewById<TextView>(R.id.toolbar_title)
toolbarTxtView.visibility = View.GONE
checkForStoragePermission()
}//on create
override fun onContextBarVisibilityChange(isVisible: Boolean) { //custom interface
if(isVisible)
{
speedDialView!!.hide()
fabLayoutBehaviourSetter(false) //remove scrolling behaviour
}
else
{
speedDialView!!.show()
fabLayoutBehaviourSetter(true) //set scrolling behaviour
}
}
override fun onReturnedToActivity(actionID: Int) { ///it just recieves value from ACTIVITY2 and assign its value to ACTIVTY1`s "newNoteCreated" varaible
when(actionID)
{
3 ->
{
Log.d("INTERFACE","CALLED $actionID")
newNoteCreated = true
Log.d("INTERFACE","CALLED $newNoteCreated")
}
}
}
参考活动(ACTIVITY2) 我只包括接口将数据发送回活动1的部分,因为活动2的代码很长,很可能会使读者感到困惑。
onActivityReturningStateNotify = MainActivity()
dbHandler!!.createNote(note)
//onActionPerformedBadgeUpdater!!.onActionPerformed(3)
onActivityReturningStateNotify!!.onReturnedToActivity(3)
界面
interface ActivityReturningStateNotify {
fun onReturnedToActivity(actionID: Int)
}
答案 0 :(得分:0)
您的问题是您要在MainActivity的新实例上调用onReturnedToActivity(),而不是您从其启动的实例或将要返回的实例。
有几种在活动之间共享数据的方法,一种是使用startActivityForResult()。
但是,我认为您的问题是Activity1将停止,因此您无法真正从Activity2发送数据。但是,您可以从startActivityForResult
开始Activity2并返回结果。
这是documentation中的示例。
开始活动。
const val PICK_CONTACT_REQUEST = 1 // The request code
...
private fun pickContact() {
Intent(Intent.ACTION_PICK, Uri.parse("content://contacts")).also { pickContactIntent ->
pickContactIntent.type = Phone.CONTENT_TYPE // Show user only contacts w/ phone numbers
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST)
}
}
获取返回的数据。
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
// Check which request we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == Activity.RESULT_OK) {
// The user picked a contact.
// The Intent's data Uri identifies which contact was selected.
// Do something with the contact here (bigger example below)
}
}
}
其他方案包括Global Singleton,使用Intents启动活动或使用SharedPreferences在一个活动中写入数据,然后在另一个活动中读取数据。
如果您在android share data between activities
上进行搜索,您会发现实现此目标的最佳方法有多种选择。
答案 1 :(得分:0)
通过接口将Activity1分配给Activity2是一个坏主意,尝试在activity1中使用:startActivityForResult(intent, requestCode)
在activity2中进行所需的操作,然后调用:onActivityResult(requestCode, resultCode, intent);
,在activity1中覆盖该功能:{{ 1}},然后从意图中获取布尔数据。