在android中实现两个Spinners之间的关系

时间:2015-02-27 10:11:50

标签: android json android-spinner

我的应用程序中有2个微调器。我已经加载了从json响应中获取的所有项目。但现在我想实现这两个Spinners之间的连接。在微调器1中选择一个项目时,微调器2应根据微调器1的选择加载内容。

这就是现在发生的事情,

旋转器1加载 1,2,3,4

旋转器2加载 1.1,1.2,2.1,2.2,3.1,4.1,4.2

但我想要发生的是,

第一阶段

旋转器1加载 1,2,3,4

旋转器2加载 没有

第二阶段

用户在微调器1中选择数字1,然后微调器2应仅加载1.1,1.2。

当前代码

@Override
public void onTaskCompleted(JSONArray responseJson) {

    try {
        List<String> crust = new ArrayList<String>();
        List<String> description = new ArrayList<String>();
        List<String> extraDescription = new ArrayList<String>();

        for (int i = 0; i < responseJson.length(); ++i) {
            JSONObject object = responseJson.getJSONObject(i);

            if ((object.getString("MainCategoryID")).equals("1")
                    && (object.getString("SubCategoryID")).equals("1")) {

                JSONArray subMenuArray = object
                        .getJSONArray("SubMenuEntity");
                for (int j = 0; j < subMenuArray.length(); ++j) {
                    JSONObject subMenuObject = subMenuArray
                            .getJSONObject(j);
                    Log.i("Crust", subMenuObject.getString("Crust"));
                    crust.add(subMenuObject.getString("Crust"));

                    Log.i("Description",
                            subMenuObject.getString("Description"));
                    description.add(subMenuObject.getString("Description"));
                }

            }
            crustSP = (Spinner) findViewById(R.id.sp_crust);
            ArrayAdapter<String> dataAdapterCru = new ArrayAdapter<String>(
                    this, android.R.layout.simple_spinner_item, crust);
            dataAdapterCru
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            crustSP.setAdapter(dataAdapterCru);

            sizeSP = (Spinner) findViewById(R.id.sp_pizza_size);
            ArrayAdapter<String> dataAdapterDes = new ArrayAdapter<String>(
                    this, android.R.layout.simple_spinner_item, description);
            dataAdapterDes
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            sizeSP.setAdapter(dataAdapterDes);

        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

我该怎么做才能做到这一点?任何帮助将不胜感激。

最新代码

ArrayAdapter<String> dataAdapterCru = new ArrayAdapter<String>(
                        this, android.R.layout.simple_spinner_item, crust);
                crust = Utils.removeDuplicatesFromList(crust);
                dataAdapterCru
                        .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                crustSP.setAdapter(dataAdapterCru);
                crustSP.setOnItemSelectedListener(new OnItemSelectedListener() {

                    public void onNothingSelected(AdapterView<?> arg0) {
                    }

                    @Override
                    public void onItemSelected(AdapterView<?> parent,
                            View view, int position, long id) {

                        String crustSelectedItem = crustSP.getSelectedItem()
                                .toString();

                        getFilteredDescriptions(crustSelectedItem, description);

                    }
                });

然后发送选定的地壳值

List<String> getFilteredDescriptions(String crustSelectedItem,
            List<String> description) {
        List<String> resultDescription = new ArrayList<String>();
        crustSelectedItem = crustSP.getSelectedItem().toString();

        if (description == null || description.isEmpty())
            return resultDescription;

        for (int i = 0; i < description.size(); i++) {
            description = Utils.removeDuplicatesFromList(description);
            if (!description.get(i).contains(crustSelectedItem))
                continue;

            resultDescription.add(description.get(i));

        }

        return resultDescription;

    }

现在resultDescription选择了地壳,各自的描述值。

这是我收到resultDescription

的地方
sizeSP.setOnItemSelectedListener(new MyOnItemSelectedListener());

                ArrayAdapter<String> dataAdapterDes = new ArrayAdapter<String>(
                        this, android.R.layout.simple_spinner_item,
                        resultDescription); //resultDescription cannot be resolved to a variable
                dataAdapterDes
                        .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                sizeSP.setAdapter(dataAdapterDes);
                sizeSP.setAdapter(new NothingSelectedSpinnerAdapter(
                        dataAdapterDes,
                        R.layout.contact_spinner_row_nothing_selected, this));

2 个答案:

答案 0 :(得分:2)

要使两个微调器之间的关系;),请按照以下步骤进行操作

1)分别为 Spinner1 Spinner2 两个列表中的数据。

2)将第一个列表数据加载到Spinner1中。

3)在Spinner上应用onItemSelectedListener监听器。

4)当用户选择你的onItemSelected听众时 会被称为。您将获得所选位置所选项目

5)有一种方法可以根据你在第4点中得到的所选项目过滤掉list2中的数据。

6)将第4点中的列表数据设置为Spinner2。

你已经建立了这种关系。

第5点的

编辑我写了以下方法。在此方法中传递选定的Crust / Value,这将返回Spinner2的大小/描述列表。

List<String> getFilteredDescriptions(String crust,List<String> descs){
        List<String> result = new ArrayList<String>();
        if(descs == null || descs.isEmpty())
            return result;

        for (int i = 0; i < descs.size(); i++) {
            if(!descs.get(i).contains(crust)) //ignore all descriptions which doesnt have same Crust
                continue;

            result.add(descs.get(i)); // Change

        }

        return result;

    }

答案 1 :(得分:0)

以下是示例

我需要Spinner,一个是选择部门,另一个是选择执行工程师,当选择特定部门时,他们的相关执行工程师名称将填入第二个旋转器。

case_list_selection.xml布局

    <?xml version="1.0" encoding="UTF-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#fff"
        android:orientation="vertical"
        android:weightSum="4" >

        <LinearLayout
            android:id="@+id/llDept"
            android:layout_width="match_parent"
            android:layout_height="0px"
            android:layout_margin="10dp"
            android:layout_weight="1"
            android:background="#fff"
            android:orientation="horizontal"
            android:weightSum="2" >

            <TextView
                android:id="@+id/tvDept"
                android:layout_width="0px"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_weight="1"
                android:text="Department :"
                android:textColor="#000"
                android:textSize="20sp" />

            <Spinner
                android:id="@+id/spinnerDept"
                android:layout_width="0px"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@+id/tvDept"
                android:layout_weight="1"
                android:prompt="@string/dept_prompt"
                android:layout_gravity="center_vertical"
                 />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/llEE"
            android:layout_width="match_parent"
            android:layout_height="0px"
            android:layout_below="@+id/llDept"
            android:layout_margin="10dp"
            android:layout_weight="1"
            android:background="#fff"
            android:orientation="horizontal"
            android:weightSum="2" >

            <TextView
                android:id="@+id/tvExecutiveEngineer"
                android:layout_width="0px"
                android:layout_height="wrap_content"
                android:layout_below="@+id/tvDept"
                android:layout_gravity="center_vertical"
                android:layout_weight="1"
                android:text="Executive Engineer :"
                android:textColor="#000"
                android:textSize="20sp" />

            <Spinner
                android:id="@+id/spinnerExecutiveEngineer"
                android:layout_width="0px"
                android:layout_height="wrap_content"
                android:layout_below="@+id/tvDept"
                android:layout_toRightOf="@+id/tvExecutiveEngineer"
                android:layout_weight="1"
                android:prompt="@string/exec_prompt" 
                android:layout_gravity="center_vertical"
                />
        </LinearLayout>
     <LinearLayout
            android:id="@+id/llFromDate"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:weightSum="2" 
            android:layout_margin="10dp"
            >

            <Button
                android:id="@+id/btnFromDate"
                android:layout_width="0px"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text=" From Date "
                android:textColor="#000000"
                android:textSize="17sp"
                            android:background="@drawable/bg"
                            android:textStyle="bold" 

                 />

            <EditText
                android:id="@+id/txtFromDate"
                android:layout_width="0px"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:hint=" From Date "
                android:textColor="#000000"
                android:textSize="17sp"
                android:gravity="center"
                android:enabled="false"

                android:focusable="false"
                />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/llToDate"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:weightSum="2" 
            android:layout_margin="10dp"
            >

            <Button
                android:id="@+id/btnToDate"
                android:layout_width="0px"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text=" To Date "
                android:textColor="#000000"
                android:textSize="17sp"
                            android:background="@drawable/bg"
                                        android:textStyle="bold" 


                />

            <EditText
                android:id="@+id/txtToDate"
                android:layout_width="0px"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@+id/btnToDate"
                android:layout_weight="1"
                android:hint=" To Date "
                android:textColor="#000000"
                android:textSize="17sp"
                android:gravity="center"
                android:enabled="false"
                     android:focusable="false"
                 />
        </LinearLayout>
        <RelativeLayout
            android:id="@+id/llBtn"
            android:layout_width="match_parent"
            android:layout_height="0px"
            android:layout_margin="10dp"
            android:layout_weight="2"
            android:background="#fff"
           >
            <Button 
                android:id="@+id/btnSearch"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="#00728f"
                android:drawableRight="@drawable/search"
                android:layout_centerInParent="true" 
                android:padding="5dp"
                android:text=" Search "
                android:textColor="#FFF"
                android:textSize="18sp" />
        </RelativeLayout>

    </LinearLayout>

CaseListSelection.java类

    package com.smartcity;

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.Date;

    import android.app.Activity;
    import android.app.DatePickerDialog;
    import android.content.Context;
    import android.content.Intent;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.Window;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemSelectedListener;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.DatePicker;
    import android.widget.EditText;
    import android.widget.Spinner;
    import android.widget.Toast;

    import com.city.data.ExceutiveNamesCollection;
    import com.city.webservices.Department_Webservice;
    import com.city.webservices.GetExecutive_Webservices;
    import com.smartcity.R;

    public class CaseListSelection extends Activity{
        Context context;
        Spinner spinnerDept,spinnerExecutiveEngineer;
        ArrayList<ExceutiveNamesCollection> listEE,listExcecutiveNames;
        String executiveNames[];
        ArrayAdapter<String> dataAdapter;
        String selectedDept, selectedEE,selectedDeptId,selectedEEId;
        Button btnSearch;
        SimpleDateFormat fmtDateAndTime =new SimpleDateFormat("yyyy-MM-dd");
        EditText txtFromDate,txtToDate;
        Calendar myCalendar;
        String fromdate,todate;
        public static int posDept,posEE;
        int pos;
        public String TAG ="CaseListSelection";

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            try
            { 
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            setContentView(R.layout.case_list_selection);

            context=this;
            spinnerDept = (Spinner) findViewById(R.id.spinnerDept);

            new Department_Webservice(context,dataAdapter,spinnerDept).execute();

            btnSearch = (Button) findViewById(R.id.btnSearch);
            spinnerExecutiveEngineer = (Spinner) findViewById(R.id.spinnerExecutiveEngineer);



                    spinnerDept.setOnItemSelectedListener(new OnItemSelectedListener() {

                        public void onNothingSelected(AdapterView<?> arg0) { }
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view,
                                int position, long id) {
                            // TODO Auto-generated method stub
                            selectedDept = spinnerDept.getSelectedItem().toString();
                            selectedDeptId = Department_Webservice.deptId[position];
                            //Toast.makeText(context, "Selected selectedDeptId : "+selectedDeptId, 2).show();
                            posDept = position;
                            new GetExecutive_Webservices(context,selectedDeptId,dataAdapter,spinnerExecutiveEngineer).execute();

                        }
                    });
                    spinnerExecutiveEngineer.setOnItemSelectedListener(new OnItemSelectedListener() {

                        public void onNothingSelected(AdapterView<?> arg0) { }
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view,
                                int position, long id) {
                            // TODO Auto-generated method stub
                            selectedEE  = spinnerExecutiveEngineer.getSelectedItem().toString();
                            selectedEEId = GetExecutive_Webservices.exceutiveIds[position];
                            //Toast.makeText(context, "Selected EE : "+selectedEE, 2).show();
                            pos = position;
                            posEE = position;
                        }
                    });

            Log.v("selectedDeptId", "<<<<<<<<<<<"+selectedDeptId);

            btnSearch.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                     fromdate = txtFromDate.getText().toString();
                     todate = txtToDate.getText().toString();
                        Log.v(TAG, "selectedDeptId="+selectedDeptId);
                        Log.v(TAG, "selectedEEId="+selectedEEId);
                        Log.v(TAG, "fromdate="+fromdate);
                        Log.v(TAG, "todate="+todate);



                     Intent i = new Intent(context, CaseList.class);
                        i.putExtra("DeptId", selectedDeptId);
                        i.putExtra("Executive_Id", selectedEEId);
                        i.putExtra("position", pos);

    //              i.putExtra("Dept", selectedDept);
    //              i.putExtra("EE", selectedEE);
                    i.putExtra("FromDate", fromdate);
                    i.putExtra("ToDate", todate);

                    startActivity(i);
                }
            }); 


            myCalendar = Calendar.getInstance();
            txtFromDate = (EditText) findViewById(R.id.txtFromDate);
            txtToDate = (EditText)findViewById(R.id.txtToDate);
            Button btnFromDate = (Button) findViewById(R.id.btnFromDate);
            btnFromDate.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    new DatePickerDialog(context, d, myCalendar
                            .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                            myCalendar.get(Calendar.DAY_OF_MONTH)).show();
                } 
            });

            Button btnToDate = (Button) findViewById(R.id.btnToDate);
            btnToDate.setOnClickListener(new View.OnClickListener() {
                public  void onClick(View v) {
                    new DatePickerDialog(context, todateListener, myCalendar
                            .get(Calendar.YEAR), myCalendar
                            .get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show();
                }
            });

            }catch(Exception e)
            {
                e.printStackTrace(); 
            }
        } 
         DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(DatePicker view, int year, int monthOfYear,
                        int dayOfMonth) {
                myCalendar.set(Calendar.YEAR, year);
                myCalendar.set(Calendar.MONTH, monthOfYear);
                myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                updateFromDate();
                } 
                };
                 DatePickerDialog.OnDateSetListener todateListener = new DatePickerDialog.OnDateSetListener() {
                    public void onDateSet(DatePicker view, int year, int monthOfYear,
                            int dayOfMonth) {
                    myCalendar.set(Calendar.YEAR, year);
                    myCalendar.set(Calendar.MONTH, monthOfYear);
                    myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                    updateToDate();
                    }
                    };
        private void updateFromDate() {
            txtFromDate.setText(fmtDateAndTime.format(myCalendar.getTime()));
        }
        private void updateToDate() {
            txtToDate.setText(fmtDateAndTime.format(myCalendar.getTime()));
            if (txtFromDate.getText().toString()!=null || txtToDate.getText().toString()!=null)
            {
                try {

                     fromdate = txtFromDate.getText().toString();
                     todate = txtToDate.getText().toString();

                    Date dateFrom = fmtDateAndTime.parse(fromdate); 
                    Date dateTo = fmtDateAndTime.parse(todate); 

                    if (dateTo.before(dateFrom)) 
                    {

                        Toast.makeText(context, "To Date should be greater than From date!", 2).show();
                        txtToDate.setText("Invalid date");

                    } 
                    else
                    {
                        txtToDate.setText(fmtDateAndTime.format(myCalendar.getTime()));
                    }
                    } catch (ParseException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } 
            }
            else
            {
                Toast.makeText(context, "Please select the valid date!", 2).show();
            }
        }
    }

Department_Webservice.java asynk类填写部门列表

    package com.city.webservices;

    import java.io.IOException;
    import java.io.InputStream;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;

    import org.apache.http.HttpResponse;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.util.EntityUtils;
    import org.json.JSONArray;
    import org.json.JSONObject;

    import android.app.AlertDialog;
    import android.app.ProgressDialog;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.os.AsyncTask;
    import android.util.Log;
    import android.widget.ArrayAdapter;
    import android.widget.Spinner;

    import com.city.data.DeptBean;
    import com.city.data.HttpUrl;
    import com.smartcity.CityApplication;

    public class Department_Webservice extends AsyncTask<Void, Void, Void>
    {

        Context contxt;
        InputStream is;
        ProgressDialog pDialog;
        DeptBean beanlist;
        ArrayList<DeptBean>listDept;
        public String TAG = "Department_Webservice";
        HttpResponse response;
        String str = "";
        ArrayAdapter<String> dataAdapter;
        public static String deptNames[],deptId[];
        Spinner spinnerDept;


        public Department_Webservice(Context ctx,ArrayAdapter<String> dataAdapter,Spinner spinnerDept) {
            this.contxt  = ctx;
            this.dataAdapter  = dataAdapter;
            this.spinnerDept  = spinnerDept;

        }

        @Override
        protected void onPreExecute() {

            super.onPreExecute();
            pDialog = new ProgressDialog(contxt);
            pDialog.setIndeterminate(false);
            pDialog.setMessage("Please Wait...");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            try
            {
                    HttpClient myClient = new DefaultHttpClient();
                    HttpPost myConnection = new HttpPost(HttpUrl.get_department);

                        response = myClient.execute(myConnection);
                        str = EntityUtils.toString(response.getEntity(), "UTF-8");
            } 
            catch (UnsupportedEncodingException e) 
            {
                e.printStackTrace();
            }   
            catch (ClientProtocolException e) 
            {
                e.printStackTrace();
            }
            catch (IOException e) 
            {
                e.printStackTrace();
            }

            try {
                if(response.toString()!=null){

                        JSONArray  jarray = new JSONArray(str);
                        listDept = new ArrayList<DeptBean>();
                        for(int i = 0; i<jarray.length();i++)
                        {
                            JSONObject jobj = jarray.getJSONObject(i);
                            beanlist =  new DeptBean();
                            beanlist.setDeptId(jobj.getString("jobid"));        
                            beanlist.setDeptName(jobj.getString("role"));
                            listDept.add(beanlist);
                        }
                        Log.v(TAG, "listDept size>>>>>>>>>> " + listDept.size());

                }

            } catch (Exception e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
            return null;
        } 

        @Override
        protected void onPostExecute(Void result) {

            super.onPostExecute(result);
            pDialog.dismiss();
            if(response.toString()!=null)
            {
                    CityApplication.setDeptBeanlist(listDept);

                        deptNames = new String[listDept.size()];
                        deptId = new String[listDept.size()];
                        for (int i=0; i<listDept.size(); i++)
                        {
                            deptNames[i] = listDept.get(i).getDeptName();
                            deptId[i] = listDept.get(i).getDeptId();
                        }



                        dataAdapter = new ArrayAdapter<String>(contxt,
                            android.R.layout.simple_spinner_item, deptNames);
                        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        spinnerDept.setAdapter(dataAdapter);
            }
            else
            {

                new AlertDialog.Builder(contxt).setTitle("Message").setMessage("Server is not responding." ).setPositiveButton("Ok", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.dismiss();
                    }
                }).create().show();
            }

        }

    }

GetExecutive_Webservices.java asynk类填写相关的执行姓名列表

    package com.city.webservices;

    import java.io.IOException;
    import java.io.InputStream;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.List;

    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    import org.json.JSONArray;
    import org.json.JSONObject;

    import android.app.AlertDialog;
    import android.app.ProgressDialog;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.os.AsyncTask;
    import android.util.Log;
    import android.widget.ArrayAdapter;
    import android.widget.Spinner;

    import com.city.data.ExecutiveBean;
    import com.city.data.HttpUrl;

    public class GetExecutive_Webservices extends AsyncTask<Void, Void, Void> {

        Context contxt;
        InputStream is;
        ProgressDialog pDialog;
        String deptId;
        public static ArrayList<ExecutiveBean> alist;
        public String TAG = "GetExecutive_Webservices";
        ArrayAdapter<String> dataAdapter;
        Spinner spinnerExecutive;
        public static String exceutiveNames[],exceutiveIds[];
        String str = "";
        HttpResponse response;
        public GetExecutive_Webservices(Context ctx, String deptId,
                ArrayAdapter<String> dataAdapter, Spinner spinnerExecutive) {
            this.contxt = ctx;
            this.deptId = deptId;
            this.dataAdapter = dataAdapter;
            this.spinnerExecutive = spinnerExecutive;
        }

        @Override 
        protected void onPreExecute() {

            super.onPreExecute();
            pDialog = new ProgressDialog(contxt);
            pDialog.setIndeterminate(false);
            pDialog.setMessage("Please Wait...");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {

                List<NameValuePair> params1 = new ArrayList<NameValuePair>();
                params1.add(new BasicNameValuePair("department_id", deptId));

                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(HttpUrl.get_executive);
                httpPost.setEntity(new UrlEncodedFormEntity(params1));

                Log.v(TAG, "params1" + params1);

                response = httpClient.execute(httpPost);

                str = EntityUtils.toString(response.getEntity(), "UTF-8");

                Log.v(TAG, "str>>>>>>>>>>>>>>>" + str);


            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (response.toString() != null) {

                    alist = new ArrayList<ExecutiveBean>();

                    JSONArray jaray = new JSONArray(str);
                    for (int i = 0; i < jaray.length(); i++) {
                        JSONObject jobj = jaray.getJSONObject(i);
                        ExecutiveBean bean = new ExecutiveBean();
                        bean.setExecutiveId(jobj.getString("id"));
                        bean.setExecutiveName(jobj.getString("username"));
                        alist.add(bean);
                        Log.v(TAG, "Username>>>>>>>>>>" + jobj.getString("username"));

                    }
                    Log.v(TAG, "executive list size>>>>>>>>>>" + alist.size());

                }

            } catch (Exception e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {

            super.onPostExecute(result);
            try {
            pDialog.dismiss();
            if (response.toString() != null) {

                exceutiveNames = new String[alist.size()];
                exceutiveIds = new String[alist.size()];
                for (int i=0; i<alist.size(); i++)
                {
                    exceutiveNames[i] = alist.get(i).getExecutiveName();
                    exceutiveIds[i] = alist.get(i).getExecutiveId();
                }



                dataAdapter = new ArrayAdapter<String>(contxt,
                    android.R.layout.simple_spinner_item, exceutiveNames);
                dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinnerExecutive.setAdapter(dataAdapter);


            } else {

                new AlertDialog.Builder(contxt)
                        .setTitle("Message")
                        .setMessage("Server is not responding.")
                        .setPositiveButton("Ok",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                            int which) {

                                        dialog.dismiss();
                                    }
                                }).create().show();
            }
            } catch (Exception e) {
                Log.e("JSON Parser", "onPostExecute" + e.toString());
            }
        }
    }
  1. 这是HttpUrl.get_department&amp; HttpUrl.get_executive是webservices方法的url
    1. DeptBean&amp; ExecutiveBean是Getter Setter
  2. 希望这篇文章能为您提供帮助