从webservice获取多行并在android listview中显示它

时间:2015-11-28 05:06:07

标签: java android sql web-services

我有这个网络服务:

   [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。我从Android应用程序调用这个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的列表视图中显示它,怎么做?

查询将如下:select * from dbo.tblUser

我应该在网络服务中改变什么?我还应该在java for android中做什么?

3 个答案:

答案 0 :(得分:0)

试试这段代码 -

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[](如果是MainAsyncTask则返回那是一个错误)。您可以将结果代码存储在onPostExecute的实例变量中,并在出错时返回null。然后onPostExecute可以访问与当前代码相同的信息。最后,如果没有错误,只需从String[]调用主活动中的方法来执行UI更新,并将{{1}}结果传递给它。

答案 1 :(得分:0)

我建议你创建一个Model Class,它包含你需要发回的所有属性

Public class Address{
public int grade;
public String name;
public String grade;
}

Create List<Address> addressList;

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

修改 Android Side从列表中读取您可以参考此链接 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;

答案 2 :(得分:0)

宣布一个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 = new Gson();    for(int i = 0; i&lt; array.length(); i ++){        AllocatedData app = gson.fromJson(array.getJSONObject(i).toString(),AllocatedData .class);        list.add(APP);    }