Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android list view with additional extra hidden fields

I am using listview in android. Previously i used to pull data from database so I used CursorAdapter but now I am fetching response from website and on the website I have different links and each link has its name associated with it. I have names and links in two arrays of string. I have to show only the names and when clicked each name will open a same new intent with link as parameter.

Here is what I am doing

listView = (ListView) findViewById(R.id.list);


String[] names= new String[] { "name1", 
                               "name2"
                             };
String[] links= new String[] { "link1", 
                               "link2"
                             };

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
  android.R.layout.simple_list_item_1, android.R.id.text1, send names and links);

            listView.setAdapter(adapter); 

        listView.setOnItemClickListener(new OnItemClickListener() {

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

               String  itemValue    = (String) listView.getItemAtPosition(position);
               Intent myIntent = new Intent(arg0.getContext(), NewPage.class);          
            myIntent.putExtra("Url",how to get this);               
            startActivity(myIntent);
              }

         }); 
    }
like image 832
Hamza Avatar asked Mar 21 '23 19:03

Hamza


1 Answers

Wrap the two pieces of information in a custom object:

class Data {
   String name;
   String link;

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

Building the list of data items:

String[] names= new String[] { "name1", 
                               "name2"
                             };
String[] links= new String[] { "link1", 
                               "link2"
                             };
List<Data> output = new ArrayList<Data>();
for (int i = 0; i < names.length; i++) {
     Data d = new Data();
     d.name = names[i];
     d.link = links[i]
     output.add(d);
}
ArrayAdapter<Data> adapter = new ArrayAdapter<Data>(this,
  android.R.layout.simple_list_item_1, android.R.id.text1, output);

You can then use the Data in the OnItemClickListener:

Data  item = (Data) listView.getItemAtPosition(position);
Intent myIntent = new Intent(arg0.getContext(), NewPage.class);          
myIntent.putExtra("Url", d.link);               
startActivity(myIntent);
like image 170
user Avatar answered Apr 01 '23 18:04

user