개발자

안드로이드 Activity의 EditText 값을 fragment의 커스텀 리스트뷰의 값으로 받아오는 과정에서 오류가 뭘까요?

2023년 11월 25일조회 122

Fragment로 커뮤니티 게시판을 만들고 있습니다 사진처럼 Activity에 작성한 글을 Fragment 안에 있는 커스텀 리스트뷰에 넣으려고합니다 구글링으로 방법을 찾아서 하고 있는데 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference at com.example.project.ChatFragment.onCreateView(String Title=bundle.getString("mainTitle",null);) 이렇게 오류 메세지가 뜨네요 어떻게 해결해야할지 모르겠습니다 엑티비티와 프래그먼트 코드 올립니다 혹시 몰라서 BaseAdater 코드도 올립니다

1//Fragment
2package com.example.project;
3
4import android.content.Intent;
5import android.os.Bundle;
6
7import androidx.fragment.app.Fragment;
8
9import android.view.LayoutInflater;
10import android.view.View;
11import android.view.ViewGroup;
12import android.widget.ListView;
13import android.widget.TextView;
14
15import com.google.android.material.floatingactionbutton.FloatingActionButton;
16
17public class ChatFragment extends Fragment {
18    private View view;
19    private ListView chatList;
20    @Override
21    public View onCreateView(LayoutInflater inflater, ViewGroup container,
22                             Bundle savedInstanceState) {
23        view=inflater.inflate(R.layout.fragment_chat,container,false);
24        chatList=view.findViewById(R.id.chatList1);
25        ChatListItem clAdapter=new ChatListItem();
26        FloatingActionButton fab2=view.findViewById(R.id.fab2);
27        TextView chatcustom1=view.findViewById(R.id.chatcustom1);
28        TextView chatcustom2=view.findViewById(R.id.chatcustom2);
29        Bundle bundle=getArguments();
30        chatList.setAdapter(clAdapter);
31        clAdapter.addChatList("맨시티 첼시 4:4 난타전","qoad123");
32        clAdapter.addChatList("나이키 축구화 대박 세일","mzkxn753");
33        clAdapter.addChatList("매칭 비매너 개쩌네","okc654");
34        String Title=bundle.getString("mainTitle",null);
35        String Text=bundle.getString("mainText1",null);
36        chatcustom1.setText(Title);
37        chatcustom2.setText(Text);
38        fab2.setOnClickListener(new View.OnClickListener() {
39            @Override
40            public void onClick(View v) {
41                startActivity(new Intent(getActivity(), Comunity.class));
42            }
43        });
44        clAdapter.addChatList(Title,Text);
45        clAdapter.notifyDataSetChanged();
46        return view;
47    }
48}
49
50//Activity
51package com.example.project;
52
53import android.app.Activity;
54import android.app.Fragment;
55import android.content.Intent;
56import android.os.Bundle;
57import android.view.View;
58import android.widget.Button;
59import android.widget.EditText;
60
61import androidx.annotation.Nullable;
62import androidx.appcompat.app.AppCompatActivity;
63import androidx.fragment.app.FragmentManager;
64import androidx.fragment.app.FragmentTransaction;
65
66public class Comunity extends AppCompatActivity {
67    @Override
68    protected void onCreate(@Nullable Bundle savedInstanceState) {
69        super.onCreate(savedInstanceState);
70        setContentView(R.layout.comunity);
71        EditText cet1=(EditText)findViewById(R.id.cet1);
72        EditText cet2=(EditText)findViewById(R.id.cet2);
73        Button cbtn1=(Button)findViewById(R.id.cbtn1);
74        Button cbtn2=(Button)findViewById(R.id.cbtn2);
75        FragmentManager manager=getSupportFragmentManager();
76        FragmentTransaction transaction=manager.beginTransaction();
77        ChatFragment chatFragment = new ChatFragment();
78        Bundle bundle=new Bundle();
79
80        cbtn1.setOnClickListener(new View.OnClickListener() {
81            @Override
82            public void onClick(View v) {
83                finish();
84            }
85        });
86        cbtn2.setOnClickListener(new View.OnClickListener() {
87            @Override
88            public void onClick(View v) {
89                String cTitle=cet1.getText().toString();
90                String cText=cet2.getText().toString();
91
92
93
94                bundle.getString("mainTitle",cTitle);
95                bundle.getString("mainText1",cText);
96                transaction.replace(R.id.cbtn2,chatFragment).commit();
97                chatFragment.setArguments(bundle);
98
99            }
100        });
101    }
102}
103
104
105//BaseAdapter
106package com.example.project;
107
108import android.content.Context;
109import android.view.LayoutInflater;
110import android.view.View;
111import android.view.ViewGroup;
112import android.widget.BaseAdapter;
113import android.widget.TextView;
114
115import java.util.ArrayList;
116
117public class ChatListItem extends BaseAdapter {
118    ArrayList<ChatList> chatlist=new ArrayList<>();
119    @Override
120    public int getCount() {
121        return chatlist.size();
122    }
123
124    @Override
125    public Object getItem(int position) {
126        return chatlist.get(position);
127    }
128
129    @Override
130    public long getItemId(int position) {
131        return position;
132    }
133
134    @Override
135    public View getView(int position, View convertView, ViewGroup parent) {
136        Context c= parent.getContext();
137        if (convertView==null){
138            LayoutInflater li= (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
139            convertView=li.inflate(R.layout.chatcustom,parent,false);
140        }
141        TextView chatcustom1=convertView.findViewById(R.id.chatcustom1);
142        TextView chatcustom2=convertView.findViewById(R.id.chatcustom2);
143
144        ChatList cl=chatlist.get(position);
145        chatcustom1.setText(cl.getTitle());
146        chatcustom2.setText(cl.getWriter());
147        return convertView;
148    }
149    public void addChatList(String title, String writer){
150        ChatList cl=new ChatList();
151
152        cl.setTitle(title);
153        cl.setWriter(writer);
154
155        chatlist.add(cl);
156    }
157}
이 질문이 도움이 되었나요?
'추천해요' 버튼을 누르면 좋은 질문이 더 많은 사람에게 노출될 수 있어요. '보충이 필요해요' 버튼을 누르면 질문자에게 질문 내용 보충을 요청하는 알림이 가요.

답변 1

문승욱(카이론)님의 프로필 사진

제가 해본게 아니라 그냥 일반론으로만 참고해주세요. 1. 원인은 번들을 참고하고 있는 시점인 onclick에서 bundle이 null 인 상태인걸로 보입니다. 2. 생성자에서 getArgument() 할때 정상적으로 반환이 일어나는지 체크 3. 핸들러에서 bundle에 대한 null체크해보시면 원인이 나올거 같습니다. 4. 아마도 Community 클래스안에 private property로 bundle을 하나 만드시고 거기 넣어두시면 되지 않을까~ 하고 생각해봅니다.

지금 가입하면 모든 질문의 답변을 볼 수 있어요!

현직자들의 명쾌한 답변을 얻을 수 있어요.

또는

이미 회원이신가요?

AI 답변
커리어리 AI 봇 프로필 이미지

커리어리 AI 봇

GPT가 달아주는 답변입니다.

2023년 11월 25일

당신의 코드를 확인해 보니, 당신이 bundle에 데이터를 넣는 방법에 오류가 있습니다. Bundle을 사용하여 데이터를 넣을 때, `bundle.putString()` 메소드를 사용해야 합니다. 그러나 당신의 코드에서는 `bundle.getString()` 메소드를 사용하였습니다. 이는 Bundle로부터 값을 가져오려고 할 때 사용되는 메소드입니다. 따라서, 아래와 같이 코드를 수정하면 될 것 같습니다: ```java cbtn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String cTitle=cet1.getText().toString(); String cText=cet2.getText().toString(); bundle.putString("mainTitle",cTitle); bundle.putString("mainText1",cText); chatFragment.setArguments(bundle); transaction.replace(R.id.cbtn2,chatFragment).commit(); } }); ``` 그리고 한 가지 더 주의해야 할 점은, 활동(Activity)에서 fragment로 값들을 전달하는 방식입니다. 일반적으로 FragmentTransaction.commit()을 호출하기 전에 getArguments()를 설정해야합니다. 아무튼, NullPointerException은 대개 null인 객체에 대한 메서드 호출시 발생하는데 위의 방법으로 해결하면 해결될 수 있습니다.

목록으로

지금 가입하면 모든 질문의 답변을 볼 수 있어요!