如何基于第一个微调器显示第二个微调器数据。 Json来自网址?

时间:2016-02-29 09:14:51

标签: android arrays json spinner

直到现在我正在获得JSON并将它们放在3个不同的微调器中。但问题是如何根据第一个微调器和基于第二个微调器的第三个微调器数据制作第二个微调器数据。

       This is my code for JSON.

            try {
            // Locate the NodeList name
            jsonarray = jsonobject.getJSONArray("results");
            for (int i = 0; i < jsonarray.length(); i++) {
                jsonobject = jsonarray.getJSONObject(i);

                Results worldpop = new Results();

                worldpop.setSyllabus(jsonobject.optString("syllabus"));
                worldpop.setGrade(jsonobject.optString("grade"));
                worldpop.setSubject(jsonobject.optString("subject"));
                //worldpop.setFlag(jsonobject.optString("flag"));
                world.add(worldpop);


                worldlist.add(jsonobject.optString("syllabus"));
                worldlist2.add(jsonobject.optString("grade"));
                worldlist3.add(jsonobject.optString("subject"));

            }
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void args) {
        // Locate the spinner in activity_main.xml

        final Spinner mySpinner = (Spinner) findViewById(R.id.syllabus);
        Spinner mySpinner2 = (Spinner) findViewById(R.id.grade);
        Spinner mySpinner3 = (Spinner) findViewById(R.id.subject);

        // Spinner adapter


        LinkedHashSet<String> listToSet = new LinkedHashSet<String>(worldlist);

        //Creating Arraylist without duplicate values
        final List<String> worldlistnew = new ArrayList<String>(listToSet);




     mySpinner
                .setAdapter(new ArrayAdapter<String>(MainActivity.this,
                        android.R.layout.simple_spinner_dropdown_item,
                        worldlistnew));

        listToSet = new LinkedHashSet<String>(worldlist2);

        //Creating Arraylist without duplicate values
        final List<String> worldlistnew2 = new ArrayList<String>(listToSet);



        mySpinner2
                .setAdapter(new ArrayAdapter<String>(MainActivity.this,
                        android.R.layout.simple_spinner_dropdown_item,
                        worldlistnew2));

        listToSet = new LinkedHashSet<String>(worldlist3);

        //Creating Arraylist without duplicate values
        final List<String> worldlistnew3 = new ArrayList<String>(listToSet);
        mySpinner3
                .setAdapter(new ArrayAdapter<String>(MainActivity.this,
                        android.R.layout.simple_spinner_dropdown_item,
                        worldlistnew3));

        // Spinner on item click listener
        mySpinner
                .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                    @Override
                    public void onItemSelected(AdapterView<?> arg0,
                                               View arg1, int position, long arg3) {

这里要做的事情。

                      //  Results population = (Results)                   mySpinner.getItemAtPosition(position);
                      //  worldlistnew2.setText("" + population.getGrade());
                       // worldlistnew3.setText("" + population.getSubject());


                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> arg0) {
                        // TODO Auto-generated method stub
                    }
                });

    }
}

5 个答案:

答案 0 :(得分:0)

这是答案。在此示例中,取决于第一个微调器,第二个微调器值会发生变化。它还会改变actoteivty中的文本,这是你在第二个微调器中选择的值。如果这有助于你请投票。

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.text.Html;
import android.view.Menu;
 import android.view.View.OnClickListener;
 import java.util.ArrayList;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
 import android.widget.Button;
 import android.widget.ImageView;
 import android.widget.Spinner;
 import android.widget.TextView;

 public class Courses extends Activity {




Spinner s1,s2;
TextView seats_t,t2,hod_det;
ImageView im1;
String s;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.courses);



    s1 = (Spinner) findViewById(R.id.grad);
    s2 = (Spinner) findViewById(R.id.streams);
    seats_t=(TextView)findViewById(R.id.about1);
    t2=(TextView)findViewById(R.id.hodname1);
    hod_det=(TextView)findViewById(R.id.hoddetails);
    im1=(ImageView)findViewById(R.id.hodimage);
    t2.setText(Html.fromHtml("<b>H.O.D</b>"));

    final ArrayList<String> s1_options = new ArrayList<String>();
    final ArrayList<String> s2_options = new ArrayList<String>();

    s1_options.add("Under Graduate");
    s1_options.add("Post Graduate");


    ArrayAdapter<String> friendAdapter = new ArrayAdapter<String>(
            getApplicationContext(), android.R.layout.simple_spinner_item,
            s1_options);
    s1.setAdapter(friendAdapter);

    ArrayAdapter<String> subFriendAdapter = new ArrayAdapter<String>(
            getApplicationContext(), android.R.layout.simple_spinner_item,
            s2_options);
    s2.setAdapter(subFriendAdapter);

    s1.setOnItemSelectedListener(new OnItemSelectedListener() {

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

            String friendName = s1_options.get(position).toString();
            resetFriend(friendName);
      //                subFriend.setAdapter(null);

        }

        private void resetFriend(String friendName) {
            s2_options.removeAll(s2_options);
            if (friendName.equals("Under Graduate")) {
                s2_options.add("B.Tech(C.S.E)");
                s2_options.add("B.Tech(E.C.E)");
                s2_options.add("B.Tech(E.E.E)");
                s2_options.add("B.Tech(I.T)");

            } else if (friendName.equals("Post Graduate")) {
                s2_options.add("M.B.A");
                s2_options.add("M.C.A");
                s2_options.add("M.Tech(C.N)");
                s2_options.add("M.Tech(C.S)");
                s2_options.add("M.Tech(C.S.E)");
                s2_options.add("M.Tech(V.L.S.I)");
                s2_options.add("M.Tech(D.S.C.E)");
            } 
            ArrayAdapter<String> subFriendAdapter = new ArrayAdapter<String>(
                    getApplicationContext(),
                    android.R.layout.simple_spinner_item, s2_options);
            s2.setAdapter(subFriendAdapter);

        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {

        }

    });

    s2.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {


             s=((TextView)arg1).getText().toString();

            if(s.equals("B.Tech(C.S.E)"))
            {

                seats_t.setText(Html.fromHtml("<b>Computer Science Engineering:</b> - 180 seats"));



            }

            if(s.equals("B.Tech(E.C.E)"))
            {

                seats_t.setText(Html.fromHtml("<b>Electronics and Communication Engineering:</b> - 180 seats"));



            }
            if(s.equals("B.Tech(E.E.E)"))
            {   

                seats_t.setText(Html.fromHtml("<b>Electrical and Electronics Engineering:</b> - 60 seats"));



            }

            if(s.equals("M.Tech(D.S.C.E)"))
            {   
                seats_t.setText(Html.fromHtml("<b>M.Tech. ( D.S.C.E.):</b> - 24(2nd shift seats"));

            }


        }
        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }
    });

}


  }

答案 1 :(得分:0)

您可以实施Spinner.OnItemSelectedListener

并使用下面的代码将侦听器设置为微调器

 spinner1.setOnItemSelectedListener(this);

 spinner2.setOnItemSelectedListener(this);

以及onItemSelected您可以使用

根据在第一个微调器上选择的值将数据填充到第二个微调器中
 @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        Spinner spinner = (Spinner) parent;
        if (spinner.getId() == R.id.spinner1) {

 // here you can populate  data in to second spinner
}
}

希望这有助于你

答案 2 :(得分:0)

首先指定json data formate。 我处理一种类型的json数据格式。

{
  "City": [
    {
      "name": "Ahmedabad",
      "City_area1" : "Ghatlodia",
      "City_area2" : "Chandlodia",
      "City_area3" : "Other"
    },
    {
      "name": "Hydarabad",
      "City_area1" : "IIT",
      "City_area2" : "Faridabad",
      "City_area3" : "Other"
    },
    {
      "name": "Noida",
      "City_area1" : "Sector-50",
      "City_area2" : "Sector-41",
      "City_area3" : "Other"
    }
  ]
}

city.java

public class city {
    private String city;
    private String Area1;
    private String Area2;
    private String Area3;

    public String getArea1() {
        return Area1;
    }

    public void setArea1(String area1) {
        Area1 = area1;
    }

    public String getArea2() {
        return Area2;
    }

    public void setArea2(String area2) {
        Area2 = area2;
    }

    public String getArea3() {
        return Area3;
    }

    public void setArea3(String area3) {
        Area3 = area3;
    }

    public city(String area1, String area2, String area3, String city) {

        Area1 = area1;
        Area2 = area2;
        Area3 = area3;
        this.city = city;
    }



    public city() {

    }

    public String getCity() {

        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
}

MainActivity.java

public class MainActivity extends Activity {
    Spinner selectcityspinner;
    ArrayList<String> citylist;
    ArrayList<city> cityandarealist;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);
    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        selectcityspinner = (Spinner)findViewById(R.id.selectcityspin);
        citylist = new ArrayList<>();
        new cityAsynTask().execute("Jason data url");//put your url over here
    }
    public class cityAsynTask extends AsyncTask<String,Void,Boolean>
    {

        @Override
        protected Boolean doInBackground(String... params) {

            cityandarealist = new ArrayList<city>();

            try {
                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost(params[0]);
                HttpResponse response = client.execute(post);
                int status = response.getStatusLine().getStatusCode();
                if (status == 200) {
                    HttpEntity entity = response.getEntity();
                    String data = EntityUtils.toString(entity);
                    JSONObject jobjcity = new JSONObject(data);
                    JSONArray jarray = jobjcity.getJSONArray("City");
                    for (int i = 0;i < jarray.length();i++){
                        city city = new city();
                        JSONObject jrealobject = jarray.getJSONObject(i);
                        city.setCity(jrealobject.getString("name"));
                        city.setArea1(jrealobject.getString("City_area1"));
                        city.setArea2(jrealobject.getString("City_area2"));
                        city.setArea3(jrealobject.getString("City_area3"));
                        cityandarealist.add(city);
                        citylist.add(jrealobject.getString("name"));

                    }
                    return true;
                }

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


            return false;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            if(aBoolean == false){
                Toast.makeText(MainActivity.this,"data isnot recieved",Toast.LENGTH_SHORT).show();

            } else  {
                ArrayAdapter<String> adapter = new ArrayAdapter<String> (MainActivity.this,android.R.layout.simple_spinner_item,citylist);
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                selectcityspinner.setAdapter(adapter);
                selectcityspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        Toast.makeText(getBaseContext(), parent.getItemAtPosition(position) + " selected", Toast.LENGTH_LONG).show();

                        String Country = String.valueOf(parent.getItemAtPosition(position));
                        Spinner selectareaspinner = (Spinner) findViewById(R.id.selectareaspin);
                        List<String> AreaList = new ArrayList<String>();
                        AreaList.add(cityandarealist.get(position).getArea1());
                        AreaList.add(cityandarealist.get(position).getArea2());
                        AreaList.add(cityandarealist.get(position).getArea3());
                        ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, AreaList);
                        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        adapter1.notifyDataSetChanged();
                        selectareaspinner.setAdapter(adapter1);
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });
            }

        }
    }

}

Main_axtivity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
>


<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/Select_City"
    android:layout_alignParentLeft="true"
    android:id="@+id/Country"/>
<Spinner
    android:id="@+id/selectcityspin"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_toRightOf="@+id/Country"
    ></Spinner>

<Spinner
    android:id="@+id/selectareaspin"
    android:layout_width="150dp"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/selectcityspin"
    ></Spinner>

如果您满意而不是upvote,否则请评论您的json数据格式/

答案 3 :(得分:0)

嗨shewtabh singh首先你需要将json数据存储到hashmap中,如下所示在将第一个微调器应用set on itemselected侦听器的类型转换为spinner引用之后,请执行此操作

private HashMap hmBillDispute = new HashMap();

spn_DisputeBill.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            // TODO Auto-generated method stub
            strCustomerCode = hmBillDispute.get(spn_DisputeBill.getSelectedItem().toString());
            String strFromCustomerName = spn_DisputeBill.getSelectedItem().toString();

            if (!strFromCustomerName.equalsIgnoreCase("Customer Name")) {

                doInBackground(GET_DISPUTE_BILL_HISTORY_LIST);

            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // TODO Auto-generated method stub

        }
    }); 

现在您将根据第一个微调器项目选择获取数据

答案 4 :(得分:0)

我知道,已经晚了,但是这段代码正在我的项目中运行,请看一下,也许这是给即将到来的人的。在第一个微调器上单击,您必须将Json数据添加到第二个微调器,就像对第三个微调器一样。

BetterSpinner spinnerOne, spinnerTwo;
ArrayAdapter<String> taxTypeDisAdaptor;
String taxTypeDisArray[] = {"Addition", "Discount", "Tax"};

private void setSipnnerAdaptors() {

    taxTypeDisAdaptor = new ArrayAdapter<>(mContext, R.layout.support_simple_spinner_dropdown_item, taxTypeDisArray);
    spinnerOne.setAdapter(taxTypeDisAdaptor);
    spinnerOne.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            gSttaxTypeDis = taxTypeDisArray[position];

            switch (gSttaxTypeDis) {
                case "Addition":
                    ledgertype_id = "4";
                    getLedgerData();
                    break;
                case "Tax":
                    ledgertype_id = "2";
                    getLedgerData();
                    break;
                case "Discount":
                    ledgertype_id = "3";
                    getLedgerData();
                    break;
            }
        }
    });

    spinnerTwo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            SetterAndGetter swt = (SetterAndGetter) parent.getItemAtPosition(position);
            gSTax_Ledgerid = String.valueOf((Integer) swt.tag);

        }
    });
}

public void getLedgerData() {

    String urls = "Json url " + ledgertype_id + "";
    String keyIds = "key";
    String values = "value";
    itemListLedger = CommonSpinnerDAta.addSpinnerdata(urls, keyIds, values);

    ArrayAdapter<SetterAndGetter> adapter = new ArrayAdapter<SetterAndGetter>(mContext, R.layout.support_simple_spinner_dropdown_item, itemListLedger);
    spinnerTwo.setAdapter(adapter);

}