簡體   English   中英

在活動之間失去意圖額外

[英]Losing intent extras between activities

我遇到了一個問題,即我在活動之間丟失了額外內容。

我正在將一個 ChatObject 從 MainActivity Recyclerview 發送到一個 ChatActivity,它工作正常。

然后我將相同的 ChatObject 從 ChatActivity 發送到 GroupSettingsActivity,它也可以正常工作。

我的問題是當我嘗試從我的 topAppBar 主頁按鈕從 GroupSettingsActivity 返回到 ChatActivity 時,我得到一個 nullPointerException 試圖從 ChatObject 中獲取聊天 ID。

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.shotgunnot/com.example.shotgunnot.ChatActivity}: 
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.shotgunnot.Chat.ChatObject.getChatId()' on a null object reference

我嘗試過使用 onResume 和 Navutils,但我一直收到同樣的錯誤,我認為這是我在生命周期中沒有得到的東西。 Androids 內置的后退導航按鈕按預期工作。

這是我的 MainActivity recyclerview 適配器

    @Override
    public void onBindViewHolder(@NonNull final ChatListViewHolder holder, final int position) {
        ChatObject data = chatList.get(position);

        holder.mTitle.setText(data.getChatId());
        holder.mGroup.setText(data.getGroupId());

        System.out.println("GroupPic" + data.getGroupPic());
        Glide.with(context)
                .load(data.getGroupPic())
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .placeholder(R.drawable.ic_group_24dp)
                .apply(RequestOptions.circleCropTransform().circleCrop())
                .into(holder.mGroupPic);

        holder.mLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(v.getContext(), ChatActivity.class);
                intent.putExtra("chatObject", chatList.get(holder.getBindingAdapterPosition()));
                v.getContext().startActivity(intent);
            }
        });
    }

這是聊天活動

public class ChatActivity extends AppCompatActivity  {

    ChatObject mChatObject;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        Intent intent = getIntent(); >> 
        mChatObject = (ChatObject) intent.getSerializableExtra("chatObject");

        BottomAppBar bottomAppBar = findViewById(R.id.bottomAppBar);
        bottomAppBar.replaceMenu(R.menu.group_menu);
        bottomAppBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.settings:
                        Intent intent = new Intent(ChatActivity.this, GroupSettingsActivity.class);
                        intent.putExtra("chatObject", mChatObject);
                        startActivity(intent);
                        return true;
                    case android.R.id.home:
                        Intent home = new Intent(getApplicationContext(), MainPageActivity.class);
                        startActivity(home);
                }
                return false;
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();

        Intent intent = getIntent();
        mChatObject = (ChatObject) intent.getSerializableExtra("chatObject");

    }

}


最后是 GroupSetting 活動

public class GroupSettingsActivity extends AppCompatActivity {
    ChatObject mChatObject;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_settings);

        Intent intent = getIntent(); 

        mChatObject = (ChatObject) intent.getSerializableExtra("chatObject");
        chatId = mChatObject.getChatId();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case android.R.id.home:
                Intent intent = new Intent(this, ChatActivity.class);
                intent.putExtra("chatObject", mChatObject);
                startActivity(intent);
                //NavUtils.navigateUpFromSameTask(this);
                finish();
            default:
                return super.onOptionsItemSelected(item);
        }
    }

任何幫助將非常感激。

在使用它之前,您應該檢查第二個活動中到達的值是否與 null 不同。 嘗試做這樣的事情並放置一個斷點來調試你的第二個活動中即將發生的事情:

第一項活動:

Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("user_id", "1234");
i.putExtra("user_name", "John Doe");

startActivity(i);

第二個活動:

Bundle extras = getIntent().getExtras();

if (extras != null) {
    Integer id= extras.getInt("user_id");
    String username= extras.getString("user_name");
}

嘗試在啟動ChatActivity之前添加這些標志,以清除堆棧並確保您正在創建新的ChatActivity而不是重新創建舊的:

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

我根據這個答案找到了使用 sharedPrefs 的解決方法How do you save/store objects in SharedPreferences on Android?

保存首選項

    @Override
    protected void onPause() {
        super.onPause();
        SharedPreferences.Editor prefsEditor = mPrefs.edit();
        Gson gson = new Gson();
        String json = gson.toJson(mChatObject);
        prefsEditor.putString("mChatObject", json);
        prefsEditor.commit();
    }

並在 onCreate 中檢索它們

        mChatObject = (ChatObject) intent.getSerializableExtra("chatObject");
        if(mChatObject != null){
            chatId = mChatObject.getChatId();
            groupId = mChatObject.getGroupId();
            groupPic = mChatObject.getGroupPic();
        }else{
            Gson gson = new Gson();
            String json = mPrefs.getString("mChatObject", "");
            mChatObject = (ChatObject) gson.fromJson(json, ChatObject.class);
            chatId = mChatObject.getChatId();
            groupId = mChatObject.getGroupId();
            groupPic = mChatObject.getGroupPic();
        }

雖然感覺有點像黑客,所以如果有人有更好的解決方案,那就太好了。

謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM