2016-09-10 8 views
0

목록보기에 새 항목을 추가하고 목록보기에 여전히 표시된 이전 항목으로 새로 고칩니다. 이전에 나는SimpleAdapter를 사용하여 ListView를 새로 고칠 수 없습니다.

adapter.notifyDataSetChanged(); 

를 사용하여 새 항목을 추가 한 후 새로 고침 할 수 있었다 ArrayAdapter와를 사용했지만, 난 SimpleAdapter와 위의 코드를 사용할 수 없습니다입니다. 어떠한 제안? 몇 가지 솔루션을 시도했지만 지금까지 아무 것도 작동하지 않았습니다. 당신의 beta3 방법은 정말 ListView새로운 항목을 추가하는 함수의 경우

void beta3 (String X, String Y){ 
    //listview in the main activity 
    ListView POST = (ListView)findViewById(R.id.listView); 
    //list = new ArrayList<String>(); 
    String data = bar.getText().toString(); 
    String two= data.replace("X", ""); 
    ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>(); 

    HashMap<String,String> event = new HashMap<String, String>(); 
    event.put(Config.TAG_one, X); 
    event.put(Config.TAG_two, two); 
    event.put(Config.TAG_three, Y); 
    list.add(event); 
    ListAdapter adapter = new SimpleAdapter(this, list, R.layout.list, 
      new String[]{Config.TAG_one, Config.TAG_two, Config.TAG_three}, 
      new int[]{R.id.one, R.id.two, R.id.three});   
    POST.setAdapter(adapter); 
} 
+0

는 [이] 중복 같아 (http://stackoverflow.com/questions/9733572/android-adding-extra-item-on-listview). 어떻게 항목을 목록에 추가하려고합니까? – gus27

답변

0

: 아래

내가 항목을 추가하지 않은 사용하고있는 코드는 새로운 어댑터를 설정합니다 전화 할 때마다 새 목록이 나타납니다. 따라서 항상 하나의 항목이 포함 된 ListView이됩니다. beta3 메서드를 종료 한 후 목록에 대한 참조가 사라집니다.

list 인스턴스 변수를 다시 사용해야합니다. ArrayList<HashMap<String,String>> list을 클래스/활동 범위에 넣고 번 (예 : onCreate())으로 초기화합니다.

또 다른 문제점은 SimpleAdapter 인스턴스에 대한 참조로 ListAdapter 변수를 사용한다는 것입니다. ListAdapternotifyDataSetChanged 방법을 제공하지 않는 인터페이스입니다. 대신 SimpleAdapter 변수를 사용해야합니다. 여기

은 예이다 :

public class MyActivity { 

    ArrayList<HashMap<String,String>> list; 
    SimpleAdapter adapter; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     ... 
     ListView POST = (ListView)findViewById(R.id.listView); 
     list = new ArrayList<HashMap<String, String>>(); 
     adapter = new SimpleAdapter(this, list, R.layout.list, 
      new String[]{Config.TAG_one, Config.TAG_two, Config.TAG_three}, 
      new int[]{R.id.one, R.id.two, R.id.three});   
     POST.setAdapter(adapter); 
    } 


    void beta3 (String X, String Y){ 
     String two = ""; // adapt this to your needs 
     ... 
     HashMap<String,String> event = new HashMap<String, String>(); 
     event.put(Config.TAG_one, X); 
     event.put(Config.TAG_two, two); 
     event.put(Config.TAG_three, Y); 
     list.add(event); 
     adapter.notifyDataSetChanged(); 
    } 

} 
+0

내 프로젝트는 안드로이드 전화 내의 데이터베이스에서 데이터/문자열을 가져 와서 데이터/문자열을 beta3()에 전달하고 listview에 표시합니다. 샘플 코드를 제공하여 작업 할 수 있습니까? – Lockon

+0

@Lockon : 샘플 코드가 추가되었습니다. – gus27

+0

감사합니다. @ gus42 시험해 보겠습니다. – Lockon