마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

밤늦게까지 고생많으십니다. listView에 정보가 새로추가되지않고 덮어씌워집니다.

0 추천
if(list_itemArrayList == null);
        list_itemArrayList = new ArrayList<list_item>();
        try {
            if (getIntent().hasExtra("json")) {
                JSONObject json = new JSONObject(getIntent().getStringExtra("json"));
                title = json.getString("postTitle");
                name = json.getString("postName");
                Log.i("asd","잘된다1");
                if(list_itemArrayList == null);
//                list_itemArrayList.add(new list_item("제목: "+title,"작성자: "+name,""));
            }
            Log.i("asd","잘된다2:");
            if(list_itemArrayList == null);
            Log.i("asd","잘된다3:");
            list_itemArrayList.add(new list_item("제목: "+title,"작성자: "+name,""));

        } catch (JSONException e) {
            e.printStackTrace();
        }

        ListAdapter = new listAdapter(MainActivity.this,list_itemArrayList);
        list1.setAdapter(ListAdapter);

        list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View v, int position, long id) {
                try {
                    if (getIntent().hasExtra("json")) {
                        JSONObject json = new JSONObject(getIntent().getStringExtra("json"));
                        title = json.getString("postTitle");
                        name = json.getString("postName");
                        Intent intent = new Intent(getApplicationContext(), readboard.class);
                        intent.putExtra("json", json.toString());
                        startActivity(intent);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
        
검색해보니 맨위에 줄처럼 if(list_itemArrayList == null); << 이렇게 설정하면 정상작동 된다고 검색한내용에 나와있었으나 제 코딩에서는 맞지않는지 리스트뷰에 데이터가 덮어씌워집니다. 중간에 
if(list_itemArrayList == null);
//                list_itemArrayList.add(new list_item("제목: "+title,"작성자: "+name,""));
            }
            Log.i("asd","잘된다2:");
            if(list_itemArrayList == null);
            Log.i("asd","잘된다3:");
            list_itemArrayList.add(new list_item("제목: "+title,"작성자: "+name,""));

        } catch (JSONException e) {
            e.printStackTrace();
        }
여기서 받는부분이 잘못된건가요?
큐더블유이알 (370 포인트) 님이 2019년 1월 8일 질문

1개의 답변

0 추천

if(list_itemArrayList == null); 가 잘 못 된듯 합니다.

if 문 뒤에 바로 ';' 문자가 있어서 있으나 마나 한 코드가 되었네요..

 

그래서  매번 list_itemArrayList 가 생성  되다보니, 추가가 안되는 듯 합니다.

아래와 같이 바꿔 보세요.


if(list_itemArrayList == null) {
        list_itemArrayList = new ArrayList<list_item>();
        try {
            if (getIntent().hasExtra("json")) {
                JSONObject json = new JSONObject(getIntent().getStringExtra("json"));
                title = json.getString("postTitle");
                name = json.getString("postName");
                Log.i("asd","잘된다1");
                if(list_itemArrayList == null);
//                list_itemArrayList.add(new list_item("제목: "+title,"작성자: "+name,""));
            }
            Log.i("asd","잘된다2:");
            if(list_itemArrayList == null);
            Log.i("asd","잘된다3:");
            list_itemArrayList.add(new list_item("제목: "+title,"작성자: "+name,""));
 
        } catch (JSONException e) {
            e.printStackTrace();
        }
 
        ListAdapter = new listAdapter(MainActivity.this,list_itemArrayList);
        list1.setAdapter(ListAdapter);
 
        list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View v, int position, long id) {
                try {
                    if (getIntent().hasExtra("json")) {
                        JSONObject json = new JSONObject(getIntent().getStringExtra("json"));
                        title = json.getString("postTitle");
                        name = json.getString("postName");
                        Intent intent = new Intent(getApplicationContext(), readboard.class);
                        intent.putExtra("json", json.toString());
                        startActivity(intent);
                    }
 
                } catch (JSONException e) {
                    e.printStackTrace();
                }
 
            }
        });
}

익명사용자 님이 2019년 1월 9일 답변
답변해주셔서 감사드리며, 코드 가독성이 떨어지는점 죄송합니다.
코드에서 이부분이 사실 다른 activity에서 값을 getIntent하는부분이라 try앞에 if문을 실행하니 아예값을 받지못하는 상황이 발생하네요...
try {
            if (getIntent().hasExtra("json")) {
                JSONObject json = new JSONObject(getIntent().getStringExtra("json"));
                title = json.getString("postTitle");
                name = json.getString("postName");
                Log.i("asd","잘된다1");
                if(list_itemArrayList == null);
//                list_itemArrayList.add(new list_item("제목: "+title,"작성자: "+name,""));
            }
            Log.i("asd","잘된다2:");
            if(list_itemArrayList == null);
            Log.i("asd","잘된다3:");
            list_itemArrayList.add(new list_item("제목: "+title,"작성자: "+name,""));
 
        } catch (JSONException e) {
            e.printStackTrace();
        }
그래서 데이터값을받아 배열에 추가하는부분에 if문을 넣었는데도 덮어씌어지더라구요. 값을받아 배열에 추가하는 이부분을 손대면 될것같은데 방법을 잘모르겠다..
 if (getIntent().hasExtra("json")) {
                JSONObject json = new JSONObject(getIntent().getStringExtra("json"));
                title = json.getString("postTitle");
                name = json.getString("postName");
                Log.i("asd","잘된다1");
                if(list_itemArrayList == null);
//                list_itemArrayList.add(new list_item("제목: "+title,"작성자: "+name,""));
            }
            Log.i("asd","잘된다2:");
            if(list_itemArrayList == null);
            Log.i("asd","잘된다3:");
            if(list_itemArrayList != null) {  // if문을 추가
            list_itemArrayList.add(new list_item("제목: "+title,"작성자: "+name,""));
}
 
        } catch (JSONException e) {
            e.printStackTrace();
        }
코드를 알아보기 힘드네요. 적어주신 내용은 맞는듯 한데 일부 소스라.. 답변이 힘듭니다. 풀소스를 정리해서 다시 올리시던지,
...break 걸어서,  ListAdapter를 생성하는 로직을 다시 타는 시점을 확인 해 보세요 . 초기화 됐다는건 이 값이 재 생성되었다는 애기니요.
@Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        list1 = (ListView) findViewById(R.id.list1);
        myItem = new ArrayList<list_item>();

        adapter = new listAdapter(MainActivity.this, R.layout.list_item, myItem);
        list1.setAdapter(adapter);

try {
            if (getIntent().hasExtra("json")) {

                JSONObject json = new JSONObject(getIntent().getStringExtra("json"));

                Iterator x = json.keys();
                JSONArray jsonArray = new JSONArray();

                while ( x.hasNext()) {
                    String key = (String) x.next();
                    jsonArray.put(json.get(key));

                }
                    for (int i = 0; i < jsonArray.length(); i++) {

                        title = jsonArray.getString(i);
                        name = jsonArray.getString(i);

                    }

                myItem.add(new list_item("제목: " + title, "작성자: " + name));
                adapter.notifyDataSetChanged();

                }

        } catch (JSONException e) {
            e.printStackTrace();
        }
답변 감사드리며, 말씀하신 내용은 잘봤습니다.

가독성을위해 띄어쓰기나 로그삭제등 노력해봤지만 여전히 지저분하네요..

초보개발자의 엉성한 코드니 양해부탁드리며,

현재 출력값은 잘나오지만,  A게시글을 작성하고 새로운 B게시글을 작성하면
이전에있던 A게시글에 덮어쓰기가되어 A게시글이 사라집니다.

어느부분이 문제일지 짐작가시는부분이 있을까요?  

  *  각 activity간의 데이터전송을 intent로 보내고있습니다.
적어주신 코드는 무조건 onCreate 시 intent로 보내준 json을 분석해서, 리스트 뷰에 추가하는 내용만 있습니다.  onCreate 는 Activity가 Create 될 때 불리는 것으로, 사용하시는 의도에 맞추려면, A 게시판에 있던  json 값도 포함해서 intent로 보내던지,
Activity가 동작 하고 있을 땐 intent가 아닌 setter를 통해 json 정보를 넘겨, Activity의 값을 업데이트 하셔야 할 듯 합니다.
...