如何在选择项目时在微调器中获取关联的其他json值

时间:2021-03-05 20:52:38

I am trying a simple app where I populating a spinner with the values (json value) I got from network call. But I am not getting how to get the associated json value, when an item selected from the spinner. Can any one provide me a article/reference on how to do this?

我正在尝试一个简单的应用程序,我用网络调用得到的值(json值)填充一个微调器。但是,当从微调器中选择一个项目时,我无法获得如何获取关联的json值。任何人都可以提供一篇关于如何做到的文章/参考吗?

this is my json response

这是我的json回复

{
item: {
       name: "xyz",
       brands: [
                {
                 id: 123,
                 name: "abc"
                }
               ]
     }
}

This is how I parsed the json.

这就是我解析json的方法。

public class user_activity extends ActionBarActivity {
RequestQueue queue;
    ArrayList<String> brand_list = new ArrayList<String>();
    Spinner spinner;
    String brand_id;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_activity);
        this.spinner= (Spinner) findViewById(R.id.spinner);
        loadUser();
    }

public void loadUser() {
        final ProgressDialog pDialog = new ProgressDialog(this);
        pDialog.setMessage("Please Wait..");
        pDialog.show();
        queue = Volley.newRequestQueue(this);
        String url = "http://myApiUrl";
        JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.GET, url,
                new Response.Listener<JSONObject>()
                {
                    @Override
                    public void onResponse(JSONObject response) {
                        pDialog.hide();
                        try {
                            JSONArray array = response.getJSONObject("item").getJSONArray("brands");
                            for (int i=0; i< array.length();i++) {
                                String b = array.getJSONObject(i).getString("name");
                                brand_list.add(b);
                            }
                            ArrayAdapter<String> adapter;
                            adapter = new ArrayAdapter<String>(user_activity.this,android.R.layout.simple_dropdown_item_1line,brand_list);
                            spinner.setAdapter(adapter);
                            spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                @Override
                                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                                    Toast.makeText(getBaseContext(),spinner.getSelectedItem().toString(),Toast.LENGTH_LONG).show();
                                }
                                @Override
                                public void onNothingSelected(AdapterView<?> adapterView) {

                                }
                            });

                        } catch (JSONException e) {
                            e.printStackTrace();
                            pDialog.hide();
                        }
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // error
                        Log.d("Error.Response", String.valueOf(error));
                    }
                }
        );
        queue.add(postRequest);

    }

I want to send the associated id values i,e "123" to next activity through a button intent.

我想通过按钮意图将关联的id值i,e“123”发送到下一个活动。

EDIT: Modified code as follows

编辑:修改代码如下

But function set spinner always returns empty

但是函数集微调器总是返回空

public class user_activity extends ActionBarActivity {

    String phone_number;
    String access_token;
    Button enterButton;
    String brand_id;
    TextView uName;
    RequestQueue queue;
    ArrayList<String> brand_list = new ArrayList<String>();
    ArrayList<String> _ids = new ArrayList<String>();
    Spinner spinner;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_activity);
        this.phone_number = getIntent().getStringExtra("phone");
        this.access_token = getIntent().getStringExtra("token");
        enterButton = (Button)findViewById(R.id.buttonEnter);
        uName = (TextView) findViewById(R.id.tvName);
        this.spinner= (Spinner) findViewById(R.id.spinner);
        loadUser(phone_number, access_token);
//        nextActivity(b[0]);
    }

    public void loadUser(String phone, String token) {
        final ProgressDialog pDialog = new ProgressDialog(this);
        pDialog.setMessage("Please Wait..");
        pDialog.show();
        queue = Volley.newRequestQueue(this);
        final String[] message = new String[1];
        final String[] my_id = new String[1];
        String url = "http://api_url";
        JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.GET, url,
                new Response.Listener<JSONObject>()
                {
                    @Override
                    public void onResponse(JSONObject response) {
                        pDialog.hide();
                        try {
                            message[0] = response.getJSONObject("item").getString("name");
                            uName.setText(message[0]);
                            JSONArray array = response.getJSONObject("item").getJSONArray("brands");
                            for (int i=0; i< array.length();i++) {
                                String b = array.getJSONObject(i).getString("name");
                                String id = array.getJSONObject(i).getString("id");
                                _ids.add(id);
                                brand_list.add(b);
                            }
                            String id = setSpinner();

                        } catch (JSONException e) {
                            e.printStackTrace();
                            pDialog.hide();
                        }
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // error
                        Log.d("Error.Response", String.valueOf(error));
                    }
                }
        );
        queue.add(postRequest);
    }

    public String setSpinner(){
        ArrayAdapter<String> adapter;
        final String[] id = new String[1];
        adapter = new ArrayAdapter<String>(user_activity.this,android.R.layout.simple_dropdown_item_1line,brand_list);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                id[0] = _ids.get(i);
//                Toast.makeText(getBaseContext(), id[0] + ":" + spinner.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
            }

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

            }
        });
        Toast.makeText(getBaseContext(), id[0].toString() , Toast.LENGTH_SHORT).show();
        return id[0];
    }

4 个解决方案

#1


There are many ways.

有很多方法。

One way is create id arrayList

一种方法是创建id arrayList

 ArrayList<String> _ids = new ArrayList<String>();

add values from JSON to this arryList

将JSON中的值添加到此arryList

 String id = array.getJSONObject(i).getString("id");
_ids.add(id);

and then used it in your spinner.setOnItemSelectedListener(....)

然后在你的spinner.setOnItemSelectedListener(....)中使用它

  spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
  @Override
  public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {

    String id=_ids.get(position);//Used this id to pass to another Activity 

    }
    ....
  });

#2


I think you need to store the data first in an array list like below..

我认为您需要先将数据存储在如下所示的数组列表中。

JSONArray array = response.getJSONObject("item").getJSONArray("brands");
    for (int i=0; i< array.length();i++) {
    JSONObject mItemObject = array.getJSONObject(i);
    String b = mItemObject.getString("name");
    brand_list.add(b);
    JSONArray mBrandsArray = mItemObject.getJSONArray("brands");
    JSONObject mBrandsObject = mBrandsArray.getJSONObject(0);
    String brandsId = mBrandsObject.getString("id");
    String brandsName = mBrandsObject.getString("name");
    brand_id.add(brandId); //make this array list likebrand_list
    brand_name.add(brandName); //make this array list like ..
}

And then in your spinner

然后在你的旋转器中

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        Toast.makeText(getBaseContext(),spinner.getSelectedItem().toString(),Toast.LENGTH_LONG).show();

        Intent mIntent = new Intent(this, NewActivity.class);
        // load data using putExtra
        mIntent.putExtra("id", brand_id.get(i));
        ...
        ...
        startActivity(mIntent);

    }
    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {
    }
});

#3


Create a Class called Brand as below

创建一个名为Brand的类,如下所示

    class Brand {
    int id;
    String name;

    @Override
    public String toString() {
        return name;
    }
}

Now change your parsing code and make the Brand object in place of just getting name and add it to brand_list. Once user select anything you can get the selected index find the brand object and send the id from object to the other activity.

现在更改解析代码并使Brand对象代替获取名称并将其添加到brand_list。一旦用户选择了任何内容,您就可以获得所选索引,找到品牌对象并将id从对象发送到另一个活动。

#4


You need to create your own omplementation of OnItemSelectedListener interface and place it to spinner by spinner.setOnItemSelectedListener(listener). Your listener object should look like

您需要创建自己的OnItemSelectedListener接口实现,并通过spinner.setOnItemSelectedListener(listener)将其放置到spinner。你的监听器对象应该是这样的

listener = new OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
        JSONObject selectedObject = globalItemsObject.optJSONObject(position);
        //make some actions with "selectedObject" 
    }

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

};

#1


There are many ways.

有很多方法。

One way is create id arrayList

一种方法是创建id arrayList

 ArrayList<String> _ids = new ArrayList<String>();

add values from JSON to this arryList

将JSON中的值添加到此arryList

 String id = array.getJSONObject(i).getString("id");
_ids.add(id);

and then used it in your spinner.setOnItemSelectedListener(....)

然后在你的spinner.setOnItemSelectedListener(....)中使用它

  spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
  @Override
  public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {

    String id=_ids.get(position);//Used this id to pass to another Activity 

    }
    ....
  });

#2


I think you need to store the data first in an array list like below..

我认为您需要先将数据存储在如下所示的数组列表中。

JSONArray array = response.getJSONObject("item").getJSONArray("brands");
    for (int i=0; i< array.length();i++) {
    JSONObject mItemObject = array.getJSONObject(i);
    String b = mItemObject.getString("name");
    brand_list.add(b);
    JSONArray mBrandsArray = mItemObject.getJSONArray("brands");
    JSONObject mBrandsObject = mBrandsArray.getJSONObject(0);
    String brandsId = mBrandsObject.getString("id");
    String brandsName = mBrandsObject.getString("name");
    brand_id.add(brandId); //make this array list likebrand_list
    brand_name.add(brandName); //make this array list like ..
}

And then in your spinner

然后在你的旋转器中

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        Toast.makeText(getBaseContext(),spinner.getSelectedItem().toString(),Toast.LENGTH_LONG).show();

        Intent mIntent = new Intent(this, NewActivity.class);
        // load data using putExtra
        mIntent.putExtra("id", brand_id.get(i));
        ...
        ...
        startActivity(mIntent);

    }
    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {
    }
});

#3


Create a Class called Brand as below

创建一个名为Brand的类,如下所示

    class Brand {
    int id;
    String name;

    @Override
    public String toString() {
        return name;
    }
}

Now change your parsing code and make the Brand object in place of just getting name and add it to brand_list. Once user select anything you can get the selected index find the brand object and send the id from object to the other activity.

现在更改解析代码并使Brand对象代替获取名称并将其添加到brand_list。一旦用户选择了任何内容,您就可以获得所选索引,找到品牌对象并将id从对象发送到另一个活动。

#4


You need to create your own omplementation of OnItemSelectedListener interface and place it to spinner by spinner.setOnItemSelectedListener(listener). Your listener object should look like

您需要创建自己的OnItemSelectedListener接口实现,并通过spinner.setOnItemSelectedListener(listener)将其放置到spinner。你的监听器对象应该是这样的

listener = new OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
        JSONObject selectedObject = globalItemsObject.optJSONObject(position);
        //make some actions with "selectedObject" 
    }

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

};