2016-09-10 63 views
0

我想添加一个新的条目到我的列表视图并刷新它仍然显示在列表视图中的旧条目。以前我是用ArrayAdapter我是能够通过使用无法刷新ListView与SimpleAdapter

adapter.notifyDataSetChanged(); 

添加新条目之后刷新但是我无法使用以上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())。

另一个问题是,您使用ListAdapter变量作为参考SimpleAdapter实例。 ListAdapter是一个不提供notifyDataSetChanged方法的接口。您应该使用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

我的项目从Android手机的数据库中获取数据/字符串,并将数据/字符串传递给beta3()并在列表视图中显示它。 你能给我一些示例代码,以便我可以使用它吗? – Lockon

+0

@Lockon:添加了示例代码。 – gus27

+0

谢谢@ gus42让我试试 – Lockon