如何从Android中的Web服务获取ArrayList后填充它

时间:2012-07-02 10:04:49

标签: android

我是Android的新手,这是我第一次使用AsyncTask。我做了一个非常简单的Web服务,返回ArrayList,就像

一样
package pk.mazars.basitMahmood.weatherReport;

public class WeekDays {

    private String name;
    private String weather;
    private float temperature;

    public  WeekDays(String name, String weather, float temperature) {      
        this.name = name;
        this.weather = weather;
        this.temperature = temperature;         
    } //end of constructor  
    //--------------Getters and Setters 
} //end of class WeekDays

public class WeatherReport {

    public ArrayList<WeekDays> weatherReport() {

        ArrayList<WeekDays> weatherList = new ArrayList<WeekDays>();
        weatherList.add(new WeekDays("Monday", "Cloudy", 29.5F));
        weatherList.add(new WeekDays("Tuesday", "Normal", 32.3F));
        weatherList.add(new WeekDays("Wednesday", "Sunny", 37.7F));
        weatherList.add(new WeekDays("Thursday", "Cold", 20.2F));
        weatherList.add(new WeekDays("Friday", "Normal", 31.4F));
        weatherList.add(new WeekDays("Saturday", "Rainy", 22.6F));
        weatherList.add(new WeekDays("Sunday", "Rainy", 27.9F));

        return weatherList;     
    }
} //end of class WeatherReport 

然后在android端我使用了代码

public class MainActivity extends Activity {

    Button btnStart;
    MyTask objMyTask;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        btnStart = (Button) findViewById(R.id.btnstart);
        btnStart.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {

                objMyTask = new MyTask(MainActivity.this);              
                objMyTask.execute();                
            }           
            }); //end of anonymous class        
        } //end of onCreate()    
    } //end of class MainActivity

这是我的任务

public class MyTask extends AsyncTask<Void, Void, ArrayList<?>> {

    ProgressDialog dialog = null;
    Object result = null;
    MainActivity mainActivity;

    public MyTask(MainActivity mainActivity) {      
        this.mainActivity = mainActivity ;          
    }

    @Override
    protected void onPreExecute() {     
        super.onPreExecute();
        if (dialog == null) {           
            dialog = new ProgressDialog(mainActivity);          
        }           
        dialog.setMessage("Please Wait. Your authentication is in progress");       
        dialog.show();      
    } //end of onPreExecute()

    @Override
    protected ArrayList<?> doInBackground(Void... params) {     
        callWebService();           
        return null;        
    } //end of doInBackground()

    @Override
    protected void onPostExecute(ArrayList<?> result) {     
        super.onPostExecute(result);
        dialog.dismiss();   
    } //end of onPostExecute()

} //end of class MyTask

这是webservice方法

 private void callWebService() {
    ...       
     try {

        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);
        envelope.dotNet = false;
        envelope.setOutputSoapObject(request);

        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
        androidHttpTransport.call(SOAP_ACTION,envelope);

        result = envelope.getResponse();

        if (result instanceof ArrayList<?>) {               
            ArrayList<?> weatherList = (ArrayList<?>)result;                
            for (int i=0; i<weatherList.size(); i++)                    
                Object weekDay = weatherList.get(i);
                System.out.println();                   
            }

        } else {

        }

     } catch (SocketTimeoutException e) {            
         Toast.makeText(mainActivity, "Service is not connected, Please make sure your server is running", Toast.LENGTH_LONG).show();

    }  catch(Exception e) {         
        e.printStackTrace();                            
     }      
} //end of callWebService()

在第

result = envelope.getResponse();

我得到像

这样的ArrayList

enter image description here

但后来我不知道如何从列表中获取数据。到达线后

if (result instanceof ArrayList<?>) {..}

控件转移到onPostExecute()方法,这里我得到结果为null。如何从ArrayList获取结果后填充数据。另外,我正在尝试在callwebService方法中填充数据。如何在onPostExecute(ArrayList<?> result)结果变量中获取ArrayLIst。因为我的方法返回ArrayList并且返回结果从onPostExecute()方法转移到doInBackground()方法。同样在doInBackground()方法中我可以检查isCancel()类似

@Override
protected Void doInBackground(Void... params) {     
    for (int i = 1; i <100; i++) {                  
        if (isCancelled()) {                
            break;              
        } else {                
            System.out.println(i);               
            callWebService();                                   
        }

    } //end of for()                
    return null;        
} //end of doInBackground()

但如果我在内部检查循环,那么我的callWebService()方法调用100次。所以在我的情况下是否需要调用isCancelled()方法。

由于

2 个答案:

答案 0 :(得分:1)

您的方法应该声明为private ArrayList<?> callWebService(),并且在完成后应该从该方法返回arrayList。

同样如上所述,您应该检查结果对象是否以Vector的形式返回。如果它作为Vector返回,则将其修改为ArrayList。

最后,在您的AsyncTask的doInBackround中,您应该将return null代码更改为return callWebService();,因为您的callWebService()方法将返回带有上述修改的结果ArrayList。然后在onPostExecute(ArrayList<?> result)中,结果变量不会为null,但会从您的Web服务中获得结果ArrayList。

因此,对于bove修改,您将拥有类似的内容:

private ArrayList<?> callWebService() {
...       
 try {

    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

    SoapSerializationEnvelope envelope = new    SoapSerializationEnvelope(SoapEnvelope.VER12);
    envelope.dotNet = false;
    envelope.setOutputSoapObject(request);

    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
    androidHttpTransport.call(SOAP_ACTION,envelope);

    result = envelope.getResponse();

    if (result instanceof ArrayList<?>) {               
        ArrayList<?> weatherList = (ArrayList<?>)result;                
        for (int i=0; i<weatherList.size(); i++)                    
            Object weekDay = weatherList.get(i);
            System.out.println();                   
        }

    } else {

    }

    return result;

 } catch (SocketTimeoutException e) {            
     Toast.makeText(mainActivity, "Service is not connected, Please make sure your server is running", Toast.LENGTH_LONG).show();

}  catch(Exception e) {         
    e.printStackTrace();                            
 }      
 } //end of callWebService()

AsyncTask:

public class MyTask extends AsyncTask<Void, Void, ArrayList<?>> {

ProgressDialog dialog = null;
Object result = null;
MainActivity mainActivity;

public MyTask(MainActivity mainActivity) {      
    this.mainActivity = mainActivity ;          
}

@Override
protected void onPreExecute() {     
    super.onPreExecute();
    if (dialog == null) {           
        dialog = new ProgressDialog(mainActivity);          
    }           
    dialog.setMessage("Please Wait. Your authentication is in progress");       
    dialog.show();      
} //end of onPreExecute()

@Override
protected ArrayList<?> doInBackground(Void... params) {     

    return callWebService();       
} //end of doInBackground()

@Override
protected void onPostExecute(ArrayList<?> result) {     
    super.onPostExecute(result);
    dialog.dismiss();   
} //end of onPostExecute()

} //end of class MyTask

您可以使用以下内容更改Vector to Array列表:

ArrayList<WeekDays> arraylist = new ArrayList<WeekDays>();
Collectios.copy(arraylist, vector_containing_the_data);

修改(巴西特) -------------------------------------------------- -------------

@Override
protected void onPostExecute(Vector<?> result) {

    super.onPostExecute(result);

    if (result != null) {

        for (int i=0; i<result.size(); i++) {

            Object weekDay = result.get(i);

            if (weekDay instanceof SoapObject) {

                SoapObject weekDayObject = (SoapObject)weekDay;

                String objectName = weekDayObject.getName();  //WeekDays
                String dayName = weekDayObject.getProperty("name").toString();
                String weather = weekDayObject.getProperty("weather").toString();
                String temp = weekDayObject.getProperty("temperature").toString();

            } //end of if (weekDay instanceof SoapObject)

        } //end of for (int i=0; i<result.size();...)

    } //end of if (result != null)

    dialog.dismiss();

} //end of onPostExecute()

但我认为这应该在doBackGround()方法中完成,并在填充bean中的值之后。然后我应该在我的onPostExecute()方法中使用该bean来更新UIThread。但是这段代码对我来说很好。

答案 1 :(得分:0)

您的结果对象将作为Vector返回,而不是ArrayList。

尝试将事情改为:

  if (result instanceof Vector) {               
            Vector weatherList = (Vector)result;   

看看你是否到了任何地方。