728x90
반응형
Stringrequest를 보내고, Listview에 Adapter가 제대로 적용이 안될 때
해결 방법
초반에 그냥 1개만 선언하고
Onresponse 로 json 파일을 List에 전부 넣었다면
try문 끝나기 전에 notifyDataSetChanged(); 실행!!
그러면 잘 적용된다.
예시
첫 번째, 로컬 데이터베이스에서 데이터를 가져올 때
todoLists = localdb.Read(date); // 로컬 데이터베이스에서 데이터를 읽어오고
todoListAdapter.updateDataSet(todoLists); // 로컬 데이터베이스 내용을 적용해준 뒤
todoListAdapter.notifyDataSetChanged(); // notifyDataSetChanged()를 실행해서 화면에도 적용될 수 있도록 해줍니다.
두 번째, 외부 데이터베이스에서 StringRequest를 하여 결과를 가져올 때
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<jsonArray.length();i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
TodoList todoList = new TodoList();
todoList.setListID(Integer.parseInt(jsonObject.getString("listID")));
todoList.setUserID(jsonObject.getString("userID"));
todoList.setTitle(jsonObject.getString("title"));
todoList.setContent(jsonObject.getString("content"));
todoList.setImportance(Integer.parseInt(jsonObject.getString("importance")));
todoList.setProcessHours(Integer.parseInt(jsonObject.getString("processHours")));
todoList.setUploadDate(jsonObject.getString("uploadDate"));
todoList.setIsAchieved(Integer.parseInt(jsonObject.getString("isAchieved")));
todoLists.add(todoList);
}
todoListAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
내가 작업한 코드 중, StringRequest의 onResponse부분만 가져왔다.
JSON응답으로 넘어온 데이터들을 for문을 이용해서 데이터를 갱신하고,
Adapter의 notifyDataSetChanged()를 실행해서 변경사항을 적용한 부분이다.
사용한 ListView Adapter
코드의 todoListAdapter
는 직접 정의한 custom adapter이고, ArrayAdapter를 상속받아서 만들었다.
정의한 adapter 코드는 todolistAdapter.java에서 볼 수 있다.
다른 방법?
외부 함수로 빼서 리턴하기는 불가능하다.
이유는 파악 못했는데 둘이 따로따로 실행되면서 리턴을 못한다.
내가 리턴위치를 잘못 잡았을 확률이 크지만, 위의 방법이 가장 깔끔해보여서 위의 방법을 추천한다!
728x90
반응형
'Computer Science > Troubleshooting' 카테고리의 다른 글
[MySQL] MySQL ERROR 1213 (0) | 2022.08.16 |
---|---|
[Git] gitignore 적용 안될 때 (0) | 2022.08.15 |
[PHP] 데이터 값에 table HTML이 적용되어 있을 때 (0) | 2022.08.15 |
[Django] SECRET KEY 관리 방법 (1) | 2022.08.14 |
[Tomcat, Ubuntu] 파일/폴더 소유권자를 변경하는 명령어 (0) | 2022.08.14 |