mvasco
mvasco

Reputation: 5107

Getting the values of ListView selected item

I have this ListView adapter:

public class UpicksAdapter extends BaseAdapter
{
    Context context;

    List<Upick> upick_list;

    public UpicksAdapter(List<Upick> listValue, Context context)
    {
        this.context = context;
        this.upick_list = listValue;
    }

    @Override
    public int getCount()
    {
        return this.upick_list.size();
    }

    @Override
    public Object getItem(int position)
    {
        return this.upick_list.get(position);
    }

    @Override
    public long getItemId(int position)
    {
        return position;
    }



    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        ViewItem viewItem = null;
        if(convertView == null)
        {
            viewItem = new ViewItem();

            LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

            convertView = layoutInfiater.inflate(R.layout.listview_items, null);

            viewItem.SubNameTextView = (TextView)convertView.findViewById(R.id.SubjectNameTextView);

            viewItem.SubFullFormTextView = (TextView)convertView.findViewById(R.id.SubjectFullFormTextView);
            convertView.setTag(viewItem);
        }
        else
        {
            viewItem = (ViewItem) convertView.getTag();
        }

        viewItem.SubNameTextView.setText(upick_list.get(position).Subject_Name);

        viewItem.SubFullFormTextView.setText(upick_list.get(position).Subject_Full_Form);

        return convertView;
    }
}


class ViewItem
{
    TextView SubNameTextView;
    TextView SubFullFormTextView;
}

The ListView is in a fragment.

I need to get data from the listview selected item. I have this listener:

 UpicksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {

                String item = UpicksListView.getItemAtPosition(position).toString();

                Log.d("VALOR","VALOR "+item);



            }
        });

How can I get the values of the selected item?

EDIT:

Complete Fragment code:

public class MisUpicksFragment extends Fragment   {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";



    private SessionManager session;
    private ProgressDialog loading;
    private EditText txtbusqueda;
    private Button botonbuscar,botonrefrescar;

    //movies
    private static final String TAG = MainActivity.class.getSimpleName();
    public List<Upick> upicks;
    private RecyclerView recyclerView;
    private GridLayoutManager gridLayout;
    private UpicksAdapter adapter;


    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private String user_id;
    private Button btnNew;




    ListView UpicksListView;
    ProgressBar progressBar;
    String HttpURL = "http://***/upicks_todos.php";
    private OnFragmentInteractionListener mListener;

    public MisUpicksFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MensajesFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MisUpicksFragment newInstance(String param1, String param2) {
        MisUpicksFragment fragment = new MisUpicksFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }



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






        View view = inflater.inflate(R.layout.fragment_misupicks, container, false);





        UpicksListView = (ListView) view.findViewById(R.id.UpicksListView);

        progressBar = (ProgressBar) view.findViewById(R.id.ProgressBar1);

        new ParseJSonDataClass(getActivity()).execute();


        UpicksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {

                String item = UpicksListView.getItemAtPosition(position).toString();



                Log.d("VALOR","VALOR "+item);



            }
        });





        return view;
    }


    private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> {
        public Context context;
        String FinalJSonResult;
        List<Upick> upickFullFormList;

        public ParseJSonDataClass(Context context) {

            this.context = context;
        }

        @Override
        protected void onPreExecute() {

            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... arg0) {

            HttpServiceClass httpServiceClass = new HttpServiceClass(HttpURL);

            try {
                httpServiceClass.ExecutePostRequest();

                if (httpServiceClass.getResponseCode() == 200) {

                    FinalJSonResult = httpServiceClass.getResponse();

                    if (FinalJSonResult != null) {

                        JSONArray jsonArray = null;
                        try {

                            jsonArray = new JSONArray(FinalJSonResult);
                            JSONObject jsonObject;
                            Upick upick;

                            upickFullFormList = new ArrayList<Upick>();

                            for (int i = 0; i < jsonArray.length(); i++) {

                                upick = new Upick();

                                jsonObject = jsonArray.getJSONObject(i);

                                upick.Subject_Name = jsonObject.getString("id_servicio");

                                upick.Subject_Full_Form = jsonObject.getString("cliente_servicio");

                                upickFullFormList.add(upick);
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                } else {

                    Toast.makeText(context, httpServiceClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result)

        {
            progressBar.setVisibility(View.GONE);

            UpicksListView.setVisibility(View.VISIBLE);

            if (upickFullFormList != null) {

                UpicksAdapter adapter = new UpicksAdapter(upickFullFormList, context);

                UpicksListView.setAdapter(adapter);
            }
        }
    }


    private void logoutUser() {
        session.setLogin(false);



        // Launching the login activity
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        startActivity(intent);
        //finish();
    }



    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }


}

Upvotes: 0

Views: 1057

Answers (3)

Anjal Saneen
Anjal Saneen

Reputation: 3219

Change this code to setters.

upick.Subject_Name = jsonObject.getString("id_servicio");
upick.Subject_Full_Form = jsonObject.getString("cliente_servicio");

eg:

upick.setSubjectname(jsonObject.getString("id_servicio"));

Then inside onclick you can take values using getters

String item = upicks.get(position).getSubjectname();

parent.getItemAtPosition(position) will return an Object (the model used in your adapter).To get some field from your Object don't call Object.toString(); it will return the object reference not the value that you're looking for. Use Object.yourField; instead.

Upvotes: 1

IntelliJ Amiya
IntelliJ Amiya

Reputation: 75778

The ArrayList.get() method is used to get the element of a specified position within the list.

String str_ITEM= upicks.get(position).yourGETMETHOD();

Upvotes: 1

vikas kumar
vikas kumar

Reputation: 11018

in your callback listener you have adapter object just use that like below.

UpicksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {

                String item = parent.getSelectedItem().toString();

                Log.d("VALOR","VALOR "+item);

            }
        });

Upvotes: 0

Related Questions