从webservice获取多行,并将其显示在android列表视图中



我有这个Web服务:

   [WebMethod]
    public string findUserNameById(int Id)
    {
        return getStudent(Id);
    }
    public String getStudent(int id)
    {
        SqlConnection conn;
        conn = Class1.ConnectionManager.GetConnection();
        conn.Open();
        SqlCommand newCmd = conn.CreateCommand();
        newCmd.CommandType = CommandType.Text;
        newCmd.CommandText = "select * from dbo.tblUser where Id=" + id + "";
        SqlDataReader sdr = newCmd.ExecuteReader();
        String address = null;
        if (sdr.Read())
        {
            address = sdr.GetValue(0).ToString();
            address += "," + sdr.GetValue(1).ToString();
            address += "," + sdr.GetValue(2).ToString();
        }
        conn.Close();
        return address;

    }

它检索的行值如下:Id、name、grade。我从安卓应用程序调用此Web服务:

   public class MainActivity extends AppCompatActivity {
private EditText editText;
private TextView textView;
private Handler mHandler= new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    editText = (EditText)findViewById(R.id.editText);
    textView = (TextView)findViewById(R.id.textView);
}
public void getName(View v){
    String inputId =editText.getText().toString();
    //String[] params= new String[]{"10.0.2.2",inputId};
    String[] params= new String[]{"192.168.1.17:90",inputId};
    new MyAsyncTask().execute(params);
}
class MyAsyncTask extends AsyncTask<String, Void, String>
{
    public String SOAP_ACTION="http://tempuri.org/findUserNameById";
    public String OPERATION_NAME ="findUserNameById";
    public String WSDL_TARGET_NAMESPACE ="http://tempuri.org/";
    public String SOAP_ADDRESS;
    private SoapObject request;
    private HttpTransportSE httpTransport;
    private SoapSerializationEnvelope envelop;
    Object response= null;

    @Override
    protected String doInBackground(String... params) {
        SOAP_ADDRESS="http://"+params[0]+"/myWebService.asmx";
        request= new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
        PropertyInfo pi=new PropertyInfo();
        pi.setName("Id");
        pi.setValue(Integer.parseInt(params[1]));
        pi.setType(Integer.class);
        request.addProperty(pi);
        pi= new PropertyInfo();
        envelop= new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelop.dotNet=true;
        envelop.setOutputSoapObject(request);
        httpTransport=new HttpTransportSE(SOAP_ADDRESS);
        try{
            httpTransport.call(SOAP_ACTION,envelop);
            response=envelop.getResponse();
        }
        catch (Exception e){
            response=e.getMessage();
        }
        return response.toString();
    }
    @Override
    protected void onPostExecute(final String result){
        super.onPostExecute(result);
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                textView.setText(result);
            }
        });
    }
}

我想获取所有的行,并在android中的列表视图中显示它,如何做到?

查询如下:从dbo.tblUser 中选择*

我应该在web服务中更改什么?另外,我应该在java中为android做什么?

试试这个代码-

SoapObject response = (SoapObject) envelope.getResponse();

yourArray=new String[response.getPropertyCount()];
   for(int i=0;i<response.getPropertyCount();i++){    
       Object property = response.getProperty(i);
       if(property instanceof SoapObject){
           SoapObject final_object = (SoapObject) property;
           yourArray[i] = final_object.getProperty("YOUR_PROPERTY_NAME");
    }
}

我建议您这样声明MainAsyncTask:

public class MainAsyncTask extends AsyncTask<String, Void, String[]> {然后修改doInBackground以执行您现在在onPostExecute中执行的所有处理(除了Toast部分(如果有的话)),并让它返回String[](如果有错误,则返回null)。您可以将结果代码存储在MainAsyncTask的实例变量中,并在出现错误时返回null。然后onPostExecute可以访问与当前代码相同的信息。最后,如果没有错误,只需从onPostExecute调用主活动中的一个方法来执行UI更新,并将String[]结果传递给它。

声明一个POJO-

class AllocatedData{
    String Id, name, grade;
    getters and constructor
}

代码-

List<AllocatedData> list = new ArrayList<AllocatedData>();
if (responseLevel4 != null) {
        for(int i = 0; i < responseLevel4.getPropertyCount(); i++){
            responseLevel5 = (SoapObject) responseLevel4.getProperty(i);                
            Data allocated = new AllocatedData(checkStringProperty("Id"),checkStringProperty("name"),
                    checkStringProperty("grade"));
            list.add(allocated);
        }
    } 
}

如果属性为Null ,哪个函数处理

public String checkStringProperty(String propertyName){
    if(responseLevel5.hasProperty(propertyName)){
        return responseLevel5.getProperty(propertyName).toString();
    } else {
        return null;
    }
}

但我的建议是使用JSON响应或在JSON中生成响应。我以前在Asp.net web服务中尝试过,在该服务中很难生成JSON。尝试WCF服务链接:-http://www.codeproject.com/Articles/167159/How-to-create-a-JSON-WCF-RESTful-Service-in-sec

通过使用json,您可以直接通过GSON liabrary进行解析,这与SOAP兼容,速度非常快。

Gson Gson=新Gson();for(int i=0;i<array.length();i++){AllocatedData app=gson.fromJson(array.getJSONObject(i).toString(),AllocatedData.class);list.add(应用程序);}

我建议您创建一个模型类,它包含您发送回所需的所有属性

Public class Address{
public int grade;
public String name;
public String grade;
}
Create List<Address> addressList;

遍历从数据库获得的结果集,在每次迭代中创建一个地址对象并将其放入List中,然后返回List作为响应

编辑Android侧阅读列表你可以参考这个链接http://seesharpgears.blogspot.in/2010/10/web-service-that-returns-array-of.html

服务侧

代替此线路

if (sdr.Read())
        {
            address = sdr.GetValue(0).ToString();
            address += "," + sdr.GetValue(1).ToString();
            address += "," + sdr.GetValue(2).ToString();
        }

将其更改为

List<Address> addressList=new ArrayList<Address>();
while (sdr.Read())
        {
           Address address=new Address();
            address.id = sdr.GetValue(0);
            address.name= sdr.GetValue(1).ToString();
            address.grade=sdr.GetValue(2).ToString();
addressList.add(address);
        }
return addressList;

最新更新