-1

i have this webservice:

   [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;


    }

which retrieve row values like this: Id, name, grade. and im calling this webservice from android application:

   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);
            }
        });
    }
}

I want to fetch all of the rows and display it in a list view in the android, how to do it?

the query will be like : select * from dbo.tblUser

what should i change in the webservice? also what should i do in java for android?

2
  • what is problem in your own code? Commented Nov 28, 2015 at 5:13
  • @sud my code is fine, but its fetching a single row and display it in textview in android. what i want is to fetch multiple rows and display it in listview in android. Commented Nov 28, 2015 at 5:20

3 Answers 3

0

try this code-

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");
    }
}

I would recommend that you declare your MainAsyncTask like this:

public class MainAsyncTask extends AsyncTask<String, Void, String[]> { Then modify doInBackground to do all the processing that you are now doing in onPostExecute (except for the Toast part if any) and have it return the String[] (or null if there's an error). You can store the result code in an instance variable of MainAsyncTask and return null on error. Then onPostExecute has access to the same info that it does with your current code. Finally, if there is no error, just call a method in your main activity from onPostExecute to do the UI updates, passing it the String[] result.

Sign up to request clarification or add additional context in comments.

2 Comments

firstly, what should i change in the webservice code so it will return an array?
try to declare your array in class MainActivity
0

Declare one POJO -

class AllocatedData{
    String Id, name, grade;

    getters and constructor
}

Code -

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);

        }
    } 
}

Which function handles if property is Null

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

But my Suggestion is use JSON reponse Or generate response in JSON. I tried it before in Asp.net web services in which difficult to generated JSON. try WCF services Link :- http://www.codeproject.com/Articles/167159/How-to-create-a-JSON-WCF-RESTful-Service-in-sec

By Using json you can parse directly by GSON liabrary this is very fast as compate to SOAP.

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

2 Comments

i want to use JSON but i dont have a complete good tutorial of how to do it, can you refer to one please?
You can refer this url. I used it before matijabozicevic.com/blog/android-development/…
0

I would suggest you to create a Model Class which holds all the Property you need to send back

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

Create List<Address> addressList;

Iterate through the result set you get from database and in each iteration create a address object and put it in List and return List as response

Edit Android Side reading from list you can refer this link http://seesharpgears.blogspot.in/2010/10/web-service-that-returns-array-of.html

SERVICE SIDE

Instead of this Line

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

change it to

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;

5 Comments

could you please write the webservice code and the java code?
whhich language you have used to write webService? Java Or C#
i used C#. in the address class i declare getters and setters? also i didnt get this line: Create List<Address> addressList;
can you please post the whole address class and the whole webservice method? because im new to this and tried to do it and i got alot of errors. so can you post it so i can understand please?
stackoverflow.com/a/8362958/2793134 See this post as I am not that expert in c#. It has good example exactly what you looking for .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.