2015-07-21 21 views
0

我有一个包含不同项目的活动,其中一个项目是ListView。 我创建了一个自定义列表适配器并发送给它一个json数组。 列表的数据来自服务器。评论Android中的列表视图

列表的目的是作出评论列表。我允许用户插入 评论,然后我在ListView中显示它。 当我有一些项目在列表中的作品,并显示项目。 问题是当列表视图为空并且用户发表评论时。 我看到数据已更改,但没有看到该项目,表示该列表未更新。

因此,我尝试向列表视图添加空视图,但它不起作用。

这里是一个更新的代码:(UPDATE

 if (!s.isEmpty() && !s.equals("{}")) { 

      try { 
       if (commentsListAdapter == null) { 
        commentsList.setEmptyView(findViewById(R.id.dummy)); 
        commentsListAdapter = new CommentsListAdapter(PostView.this); 
       } 
       JSONObject resObj = new JSONObject(s); 
       list.add(resObj); 

       commentsListAdapter.setDataSet(list); 

       cmntTxt.setText(""); 
       inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 
         InputMethodManager.HIDE_NOT_ALWAYS); 

       commentCounter.setText(Integer.toString(list.size())); 

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

和适配器里面我有这样的功能:

public void setDataSet(List<JSONObject> list){ 
    commentsList = list; 
    notifyDataSetChanged(); 
} 

但问题是不固定的..

+1

listview.setAdapter()的代码在哪里?也许在这个方法或Activity中发布更多的代码。 –

回答

1

我注意到代码list.add(resObj)出现在new CommentsListAdapter之后,当列表为空且出现在new CommentsListAdapter之前时当列表不为空时。

我怀疑适配器CommentsListAdapter未使用对象list进行数据存储。在这种情况下,您需要在适配器中创建一个公共方法来进行更新。换句话说,适配器正在使用另一个对象进行数据存储。

它也可能有助于张贴CommentsListAdapter的代码。但我希望我对我的发言是正确的。 我希望这是明确的......

+0

嗨,谢谢,我更新了我的代码,但我得到了与前面的代码相同的结果 – Elior

+0

@Elior,这个问题不应该很难解决。发布适配器代码。 –

+1

谢谢:)我看了我的其他代码,并没有注意到我忘记设置listview的adaper。谢谢你的帮助! – Elior

0

请更改下面的代码:

public void setDataSet(List<JSONObject> list){ 
    commentsList = list; 
    notifyDataSetChanged(); 
} 

到:

private List<JSONObject> commentsList = new ArrayList<>(); 

public void setDataSet(List<JSONObject> list){ 
    commentsList.clear(); 
    commentsList.addAll(list); 
    notifyDataSetChanged(); 
} 

而且使用commentsList在您的适配器的所有其他方法。这是notifyDataSetChanged()工作的更好方法。

希望它有帮助! :)

0

如果您从外部添加您的评论,即从活动而不是从适配器添加您的评论比您设置适配器执行此操作。

youradapterobject.notifyDataSetChanged();

和不做commentsListAdapter ==比setemptyview空

它会自动如果空设定emptyview

正确的用法 list.setEmptyView(findViewById(R.id.erromsg));