如何向android Spinner显示id和Name?

时间:2018-01-30 04:27:37

标签: android android-spinner

美好的一天,现在我能够从我的数据库表中显示一个微调器,这是我的工作方式

  @Override
    public void onStart() {
        super.onStart();
        BackTask bt=new BackTask();
        bt.execute();
        getDialog().getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
    }

     @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {

            ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.addticket_layout, container, false);

            sp = rootView.findViewById(R.id.masalahval);

            adapter= new ArrayAdapter<String>(getActivity(),R.layout.spinner_layout,R.id.txt,problemId);
            sp.setAdapter(adapter);

            Button uploadButton = rootView.findViewById(R.id.uploadButton);
            Button saveTicket   = rootView.findViewById(R.id.saveTicket);

            uploadButton.setOnClickListener(this);
            saveTicket.setOnClickListener(this);

            return rootView;
        }

这是asynctask

private class BackTask extends AsyncTask<Void,Void,Void> {
    ArrayList<String> list;
    String result="";
    protected void onPreExecute(){
        super.onPreExecute();
        list=new ArrayList<>();
    }
    protected Void doInBackground(Void... params) {
        try {
            url = new URL("http://192.168.3.223:84/my_api/GenerateProblemlists");

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

        try {
            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection)url.openConnection();
            conn.setConnectTimeout(100);
            conn.setRequestMethod("POST");
            // setDoInput and setDoOutput method depict handling of both send and receive
            conn.setDoInput(true);
            conn.setDoOutput(true);
            // Append parameters to URL
            Uri.Builder builder = new Uri.Builder();

            OutputStream os = conn.getOutputStream();

            os.close();
            conn.connect();

        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {

            int response_code = conn.getResponseCode();

            if (response_code == HttpURLConnection.HTTP_OK) {
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    result += line;
                }

                try{
                    JSONArray jArray =new JSONArray(result);

                    for(int i=0;i<jArray.length();i++){
                        JSONObject jsonObject=jArray.getJSONObject(i);

                        String ProblemCode = jsonObject.getString("ProblemCode");

                        Log.e("URUT " + i,  "Data" + ProblemCode);

                         list.add(ProblemCode);
                    }

                }
                catch(JSONException e){
                    Log.e("Tag",   "Err" + e );
                     e.printStackTrace();
                }

            }else{
                Toast.makeText(getActivity(), "It's a bug !!!!", Toast.LENGTH_SHORT).show();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            conn.disconnect();
        }

        return null;
    }
    protected void onPostExecute(Void result){
        problemId.addAll(list);
        adapter.notifyDataSetChanged();
        //Log.d("Tag 1" , "OnPostExecute " + result);

    }
}

所以,正如您在上面的脚本中所看到的,我在doInBackground()

中执行此操作
list.add(ProblemCode);

然后这是我的微调结果

enter image description here

因为该字段为ProblemCode所以它会显示表格中的Id。但现在我想做这样的事情。我的微调器将显示Description,但当我选择它们时,我可以得到ProblemId

我试图改变我的代码

 JSONArray jArray =new JSONArray(result);

                    for(int i=0;i<jArray.length();i++){
                        JSONObject jsonObject=jArray.getJSONObject(i);

                        String ProblemCode = jsonObject.getString("ProblemCode");
                        String ProblemDesc = jsonObject.getString("ProblemDesc");

                        Log.e("URUT " + i,  "Data" + ProblemCode);

                         list.add(ProblemCode + " -- " +  ProblemDesc);
                    }

我的旋转器就像这样

enter image description here

所以,在我最新的微调图像中,我只想显示描述,当我选择其中一个时,我可以得到id。我怎样才能实现这一目标?提前谢谢,对不起我的英文

更新 -

使用Dileep Patel方式后,我收到此错误

  

01-30 13:34:47.825 6971-6971 / xxx.example.boby.helpdesk   E / AndroidRuntime:FATAL EXCEPTION:main

     
    

处理:com.example.xxx.helpdesk,PID:6971                                                                          显示java.lang.NullPointerException                                                                              在android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)                                                                              在android.widget.AbsSpinner.setAdapter(AbsSpinner.java:114)                                                                              在android.widget.Spinner.setAdapter(Spinner.java:413)                                                                              在     android.support.v7.widget.AppCompatSpinner.setAdapter(AppCompatSpinner.java:399)                                                                              在com.example.boby.helpdesk.AddTicket.onCreateView(AddTicket.java:99)                                                                              在android.app.Fragment.performCreateView(Fragment.java:1700)                                                                              在     android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)                                                                              在     android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)                                                                              在android.app.BackStackRecord.run(BackStackRecord.java:684)                                                                              在     android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)                                                                              在android.app.FragmentManagerImpl $ 1.run(FragmentManager.java:443)                                                                              在android.os.Handler.handleCallback(Handler.java:733)                                                                              在android.os.Handler.dispatchMessage(Handler.java:95)                                                                              在android.os.Looper.loop(Looper.java:136)                                                                              在android.app.ActivityThread.main(ActivityThread.java:5019)                                                                              at java.lang.reflect.Method.invokeNative(Native Method)                                                                              在java.lang.reflect.Method.invoke(Method.java:515)                                                                              在     com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:779)                                                                              在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)                                                                              在dalvik.system.NativeStart.main(本地方法)

  

2 个答案:

答案 0 :(得分:1)

使用以下代码正常工作

<强>布局

//只是为了检查

    <Spinner
    android:id="@+id/sp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

您的班级

ArrayList<Model> models;
Spinner sp;

   sp =(Spinner) findViewById(R.id.sp);

private class BackTask extends AsyncTask<Void, Void, Void> {
    ArrayList<String> list;
    String result = "";

    protected void onPreExecute() {
        super.onPreExecute();
        // list = new ArrayList<>();
    }

    protected Void doInBackground(Void... params) {
        try {
            url = new URL("http://192.168.3.223:84/my_api/GenerateProblemlists");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        try {
            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(100);
            conn.setRequestMethod("POST");
            // setDoInput and setDoOutput method depict handling of both send and receive
            conn.setDoInput(true);
            conn.setDoOutput(true);
            // Append parameters to URL
            Uri.Builder builder = new Uri.Builder();
            OutputStream os = conn.getOutputStream();
            os.close();
            conn.connect();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            int response_code = conn.getResponseCode();
            if (response_code == HttpURLConnection.HTTP_OK) {
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    result += line;
                }
                try {
                    JSONArray jArray = new JSONArray(result);
                    models = new ArrayList<>();
                    for (int i = 0; i < jArray.length(); i++) {
                        JSONObject jsonObject = jArray.getJSONObject(i);
                        String ProblemCode = jsonObject.getString("ProblemCode");
                        String ProblemDesc = jsonObject.getString("ProblemDesc");

                        models.add(new Model(ProblemCode, ProblemDesc));
                        Log.e("Log ", "ProblemCode " + ProblemCode + " ProblemDesc " + ProblemDesc);
       // list.add(ProblemCode);
                    }

                } catch (JSONException e) {
                    Log.e("Tag", "Err" + e);
                    e.printStackTrace();
                }

            } else {
                Toast.makeText(getActivity(), "It's a bug !!!!", Toast.LENGTH_SHORT).show();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            conn.disconnect();
        }

        return null;
    }

    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
       if (models.size() > 0) {
        ArrayAdapter<Model> arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_spinner_item, models);
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp.setAdapter(arrayAdapter);
     }
   //  problemId.addAll(list);
   // adapter.notifyDataSetChanged();
        //Log.d("Tag 1" , "OnPostExecute " + result);

     }
   }

<强>模型

public class Model {

String strCode,strDesc;

public Model(String strCode, String strDesc) {
    this.strCode = strCode;
    this.strDesc = strDesc;
}

public String getStrCode() {
    return strCode;
}

public void setStrCode(String strCode) {
    this.strCode = strCode;
}

public String getStrDesc() {
    return strDesc;
}

public void setStrDesc(String strDesc) {
    this.strDesc = strDesc;
  }
  // add this line
  @Override
    public String toString() {
        return getStrDesc();
    }
 }

然后在微调器中获取值

          sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            String id = models.get(i).getStrCode();
            String desc = models.get(i).getStrDesc();

            Log.e("Log", "id " + id + " desc " + desc);
        }

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

         }
      });

答案 1 :(得分:0)

请检查此代码

ArrayList<Integer> list1 = new ArrayList<>();
JSONArray jArray =new JSONArray(result);

                for(int i=0;i<jArray.length();i++){
                    JSONObject jsonObject=jArray.getJSONObject(i);

                    String ProblemCode = jsonObject.getString("ProblemCode");
                    String ProblemDesc = jsonObject.getString("ProblemDesc");
                    int id = jsonObject.getInt("id");

                    Log.e("URUT " + i,  "Data" + ProblemCode);

                     list.add(ProblemCode + " -- " +  ProblemDesc);
                     list1.add(id);
                }

之后你可以在Spinner上设置监听器

Spinner sp;
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
             Toast.makeText(this,list1.get(position)+"",Toast.LENGTH_SHORT).show();
        }

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

        }
    });