如何根据从webservice收到的结果构建ArrayAdapter?

时间:2013-04-03 23:06:40

标签: android ksoap2

我正在使用在asp.net中开发的返回数据类型List (List(of String))的Web服务, 我正在使用Ksoap2 api调用上面的Web服务并从中获取结果,如下所示:

从Web服务收到的结果:

anyType{string=username1; string=username2; string=username3; string=username4; }
anyType{string=Text_news1; string=Text_News2; string=Text_News3; string=Text_News4; }
anyType{string=01-Apr-2013; string=01-Apr-2013; string=02-Apr-2013; string=02-Apr-2013; }

上面收到的第一个结果是关于发布新闻的用户的用户名,而第二个结果是Text_News本身,第三行是用户发布text_News的日期,以及我使用的代码得到上述结果如下:

我在doInBackground(String...params)方法

中使用过
List<String> data= new ArrayList<String>();
    SoapObject result = (SoapObject)envelope.bodyIn;
    if(result != null)
    {
        data.add(((SoapObject)result.getProperty(0)).getPropertyAsString(0));
            data.add(((SoapObject)result.getProperty(0)).getPropertyAsString(1));
            data.add(((SoapObject)result.getProperty(0)).getPropertyAsString(2));
    }

并且将通过以下方法处理结果以得出上述结果

protected void onPostExecute(List<String> result){
dialog.dismiss();
if(!result.isEmpty())
 {
   System.out.println("First Element :"+result.get(0));
   System.out.println("Second Element :"+result.get(1));
   System.out.println("Third Element :"+result.get(2));
}
}

但我真的不知道如何构建一个ArrayAdapter,用于以下列形式将数据插入列表视图

Username1    Text_News1   date1   to be the first Item in listView 
userName2    Text_News2   date2   to be the second item in listView
.........
.......

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

为自己定义一个对象,比如&#34; Row&#34;:

Class Row{
    String text;
    String date;
    ....

然后在解析响应时创建这些对象的ArrayList

List<Row> rows = new ArrayList<Row>();
for (all your parsed string data)
{
    Row row = new Row();
    row.setText("your parsed text");
    row.setDate("your parsed date");
    rows.add(row); 
}

最后创建一个适配器:

private class CustomAdapter extends ArrayAdapter<Row>
{   
    private ArrayList<Row> list;

    public CustomAdapter(Context context, int textViewResourceId, ArrayList<Row> rowsList) 
    {
        super(context, textViewResourceId, rowsList);
         this.list = new ArrayList<SubTask>();
         this.list.addAll(rowsList);
    }

    public View getView(final int position, View convertView, ViewGroup parent)
    {
        ViewHolder holder = new ViewHolder();

            LayoutInflater inflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflator.inflate(R.layout.list_item_new, null);

            holder.text = (TextView) convertView.findViewById(R.id.tvText);
            holder.date = (TextView) convertView.findViewById(R.id.tvDate); 

            holder.text.setText(rows.get(position).getText());
            holder.date.setText(rows.get(position).getDate());
            return convertView;
    }
}

当您的ViewHolder成为:

static class ViewHolder 
{
     TextView text;
     TextView date;
}

并且不要忘记创建list_item_new这将是您的列表项自定义布局文件。