Evan Gunawan
Evan Gunawan

Reputation: 429

How to get a value from listview with multidimensional array?

So I have a multidimensional array for my listview, it constructed like this:

    String[][] listControls = {
            {"Shutdown Host","10"},
            {"Close Connection","1"}};

Let say the first String is the text I want to display in the list view, and the other one is a id/message to send via socket (lets say it a secret value).

I coded the Adapter like this:

    ArrayAdapter adapter = new ArrayAdapter<String>(this,R.layout.layout_listview);
        for(int i = 0; i < listControls.length; i++) {
            adapter.add(listControls[i][0]);
        }

    listView = (ListView) findViewById(R.id.controls_listView);
    listView.setAdapter(adapter);
    listView.setClickable(true);

And I constructed the click listener of an item:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Object obj = listView.getItemAtPosition(position);

                //What should I add here? to get specific value from the array?
                //Integer cmdId = Integer.parseInt( ... );


            }
        });

From the click listener, i want to get the other value, e.g. If I clicked "Close Connection" in list view, I want to get the "1" value from it and put it into a variable. Thanks in advance for the help.

Upvotes: 0

Views: 691

Answers (2)

TheAnkush
TheAnkush

Reputation: 915

Write custom adapter for your case. Use HashMap which is always better.

HashMap<String, Integer> map = new LinkedHashMap<>();
map.add("Shut Down Host", 0);
map.add("Close connection", 1);

And most importantly use RecyclerView.

Tutorial for RecyclerView https://developer.android.com/guide/topics/ui/layout/recyclerview

Upvotes: 1

r2rek
r2rek

Reputation: 2233

What you could do is

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                  String value = listControls[position][1] 
            }

This will, of course work only if you have access to listControls. If not, I'd opt for creating an object SomethingWithCode(String text, Int code)[or just Pair in kotlin] and creating a custom adapter.

Hope this helps!

Also, you probably don't need multidimensional array for it, if you're always passing just two values(refer to object with string and int parameters)

Upvotes: 1

Related Questions