YVS1102
YVS1102

Reputation: 2748

How Show id and Name to android Spinner?

Good day, now i'm able to show a spinner from my database table, here is how i do it

  @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;
        }

and here is the 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);

    }
}

So, as you can see from my script above i do this in doInBackground()

list.add(ProblemCode);

And then here is my spinner result

enter image description here

Because that field is ProblemCode so it will showing the Id from table. But now i want to do something like this. My spinner will show the Description but when i get choose on of them i can get the ProblemId.

I'm trying to change my code like this

 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);
                    }

and my spinner became like this

enter image description here

So, in my newest spinner image i'm only want to show description only, when i choose one of them i can get the id . How can i achieve that ? thanks in advance and sorry for my english

Update --

After i use Dileep Patel way i get this error

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

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

Upvotes: 0

Views: 3176

Answers (2)

Dileep Patel
Dileep Patel

Reputation: 1988

Use below code it's working

Layout

// for just checking

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

Your Class

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);

     }
   }

Model

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();
    }
 }

then get value in spinner

          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) {

         }
      });

Upvotes: 1

Saurabh Vadhva
Saurabh Vadhva

Reputation: 511

Please check this code

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);
                }

After then you can set the listener on 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) {

        }
    });

Upvotes: 0

Related Questions