gpt4 book ai didi

java - 当我尝试将包从我的 Activity 传递到我的 fragment 时,为什么我总是得到空值?

转载 作者:行者123 更新时间:2023-12-01 23:43:08 25 4
gpt4 key购买 nike

我试图将一个值从我的 Activity 传递到我的 fragment ,但我不断收到此错误“尝试调用虚拟方法 'java.lang.String android.os.Bundle.getString(java.lang.String)'空对象引用”。我不知道为什么,我们将不胜感激。

fragment 类

public class MessageFragment extends Fragment {
private RecyclerView displayMessagesRecycleView;
private View displayChatListView;
private RecyclerView.LayoutManager layoutManager;
private ChatListAdapter chatListAdapter;
private ArrayList<String> messageList;
private Message message;


@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
displayChatListView = inflater.inflate(R.layout.display_messages_layout, container, false);
createObjects();
initRecycleView();
populateRecycleView();
return displayChatListView;


}


//set up RecycleVIew/listener to detect taps
public void initRecycleView() {
displayMessagesRecycleView = displayChatListView.findViewById(R.id.chatListRecycleView);
layoutManager = new LinearLayoutManager(getContext());
((LinearLayoutManager) layoutManager).setStackFromEnd(true);
((LinearLayoutManager) layoutManager).setReverseLayout(true);
displayMessagesRecycleView.setLayoutManager(layoutManager);
chatListAdapter = new ChatListAdapter(getActivity(), messageList);
displayMessagesRecycleView.setAdapter(chatListAdapter);
displayMessagesRecycleView.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, final int position) {
TextView textView = view.findViewById(R.id.textViewOptions);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("position", "item clicked");
}
});
}
})
);
}

@Override
public void onStart() {
super.onStart();
retreiveBundle();

}

//Instantiate objects
public void createObjects() {
messageList = new ArrayList<>();
}

public void populateRecycleView() {
messageList.add("HEy");
chatListAdapter.notifyDataSetChanged();

}
//retrieves selected user's name and profile pic from message activity and updates profile image and name
public void retreiveBundle() {
String data = getArguments().getString("data");// data whi


}




}

消息 Activity

public class MessageActivity extends AppCompatActivity {
private RecyclerView messagesRecycleView;
private String userProfileName;
private String userProfilePic;
private String timeStamp;
private String messageTimeStamp;
private HashMap<String, Object> messageDictionary;
private FirebaseUser currentFirebaseUser;
private TextView userNameTextView;
private CircleImageView userProfilePicture;
private EditText messageInputEditText;
private DatabaseReference firebaseDatabase;
private DatabaseReference messesagesRef;
private DatabaseReference RootRef;

private String id;
private String messageSender, messageReceiver;


private Message messages;
private ArrayList<Message> messageList;
private MessageAdapter messageAdapter;

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

messageList = new ArrayList<>();
initRecycleView();
linkUpViews();
createObjects();
setUpFirebase();
retreiveBundle();
messageSender = currentFirebaseUser.getUid();
messageReceiver = id;


}


@Override
protected void onStart() {
super.onStart();
messageList.clear();
RootRef.child("Messages").child(messageSender).child(messageReceiver).addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Message messages = dataSnapshot.getValue(Message.class);
messageList.add(messages);
messageAdapter.notifyDataSetChanged();


}

@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {

}

@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {

}

@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {

}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});

}

//find views by id
public void linkUpViews() {
userNameTextView = findViewById(R.id.userNameTv);
userProfilePicture = findViewById(R.id.chatProfilePic);
messageInputEditText = findViewById(R.id.chatboxEditText);
}

//set up RecycleView
public void initRecycleView() {
messagesRecycleView = findViewById(R.id.messagesRecycleView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(true);
linearLayoutManager.setReverseLayout(true);
messagesRecycleView.setLayoutManager(linearLayoutManager);
messageAdapter = new MessageAdapter(MessageActivity.this, messageList);
messagesRecycleView.setAdapter(messageAdapter);
}

//create objects
public void createObjects() {
messageDictionary = new HashMap<>();
//messageList = new ArrayList<>();

}

public void sendMessageButton(View view) {
sendMessages();
//saveMessages();


}


//retrieves selected user's name and profile pic from NewsFeedFragment and updates profile image and name
public void retreiveBundle() {
Bundle bundle = getIntent().getExtras();
userProfileName = bundle.getString("profileName");
userProfilePic = bundle.getString("profilePic");
timeStamp = bundle.getString("timestamp");
id = bundle.getString("id");
Log.i("timestamp", timeStamp);
userNameTextView.setText(userProfileName);
Picasso.get().load(userProfilePic).into(userProfilePicture);
}


//goes back to previous activity
public void backToShop(View view) {
Intent intent = new Intent(MessageActivity.this, MainActivity.class);
startActivity(intent);
}

//Set up Firebase connection
public void setUpFirebase() {
messesagesRef = FirebaseDatabase.getInstance().getReference();
RootRef = FirebaseDatabase.getInstance().getReference();
firebaseDatabase = FirebaseDatabase.getInstance().getReference();
currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();


}


//Store messages to Firebase
public void sendMessages() {
if (TextUtils.isEmpty(messageInputEditText.getText().toString())) {
Toast.makeText(this, "Please enter a message", Toast.LENGTH_SHORT).show();
} else {
String messageSenderRef = "Messages/" + messageSender + "/" + messageReceiver;
String messageReceiverRef = "Messages/" + messageReceiver + "/" + messageSender;

DatabaseReference userMessageKeyRef = RootRef.child("Messages")
.child(messageSender).child(messageReceiver).push();
String messagePushKey = userMessageKeyRef.getKey();

messageDictionary.put("message", messageInputEditText.getText().toString());
messageDictionary.put("sender", messageSender);
messageDictionary.put("receiver", messageReceiver);

HashMap<String, Object> messageBodyDetails = new HashMap<>();
messageBodyDetails.put(messageSenderRef + "/" + messagePushKey, messageDictionary);
messageBodyDetails.put(messageReceiverRef + "/" + messagePushKey, messageDictionary);

RootRef.updateChildren(messageBodyDetails).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
messageInputEditText.setText("");
Toast.makeText(MessageActivity.this, "Sent message...", Toast.LENGTH_SHORT).show();
sendDataToFrag();
} else {
Log.e("Error", task.getException().getMessage().toString());
}

}
});


}
}

//sends data to message fragment...
public void sendDataToFrag(){
Bundle bundle = new Bundle();
bundle.putString("data", "From Activity");
// set Fragmentclass Arguments
MessageFragment fragobj = new MessageFragment();
fragobj.setArguments(bundle);

}



}

最佳答案

这段代码可以工作

public class MyFragment extends Fragment {
public static MyFragment newInstance(String data) {
Bundle args = new Bundle();
args.putString("data", data);

MyFragment fragment = new MyFragment();
fragment.setArguments(args);
return fragment;
}

public String getData() {

return getArguments().getString("data");
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String data = getData();
return inflater.inflate(R.layout.test, container, false);
}
}

而你的Activity一定是这样的

    public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uiView = findViewById(R.id.ui);
uiView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread(new Runnable() {
@Override
public void run() {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.replace(R.id.fragment, MyFragment.newInstance("My Test"));
transaction.commit();
}
}).start();
}
});
}

}

关于java - 当我尝试将包从我的 Activity 传递到我的 fragment 时,为什么我总是得到空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58250888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com