Lai Lai - 18 days ago 7
Android Question

Extract String from ArrayList which get the item from listview

I want to extract string from the arraylist of String which is filled by the selected items from the listView.

The result of the array list is:

{studentName=XXX,studentID=SF10001}
{studentName=YYYY,studentID=SF10002}


I want only get the studentID which are SF10001 and SF10002. Below is my code:

SparseBooleanArray checked = list.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<String>();

for (int i = 0; i < checked.size(); i++) {
// Item position in adapter
int position = checked.keyAt(i);
// Add sport if it is checked i.e.) == TRUE!
if (checked.valueAt(i))
selectedItems.add(adapter.getItem(position));
}

String[] outputStrArr = new String[selectedItems.size()];

for (int i = 0; i < selectedItems.size(); i++) {

outputStrArr[i] = selectedItems.get(i);

}

Intent intent = new Intent(getApplicationContext(),
ResultActivity.class);

// Create a bundle object
Bundle b = new Bundle();
b.putStringArray("selectedItems", outputStrArr);

// Add the bundle to the intent.
intent.putExtras(b);

// start the ResultActivity
startActivity(intent);
}


And this the Result Activity.java

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
Bundle b = getIntent().getExtras();
String[] resultArr = b.getStringArray("selectedItems");

ListView lv = (ListView) findViewById(R.id.outputList);

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, resultArr);
lv.setAdapter(adapter);


}

Answer

Two ways of solving your problem :

1) Simpler way , but not efficient: (You can use this if all your strings are guaranteed to use that exact template, or add further validations to the below function)

 public string extractStudentID(string input)
 {
      string [] parts = input.substring(1,input.length-1).split(",");

      return parts[1].split("=")[1];
 }

and use it in your code as follows

 for (int i = 0; i < checked.size(); i++) {
    // Item position in adapter
    int position = checked.keyAt(i);
    // Add sport if it is checked i.e.) == TRUE!
    if (checked.valueAt(i))
        selectedItems.add(extractStudentID(adapter.getItem(position)));
}

2) Create a class for you student data

class StudentData
{
       public string studentName;
       public string studentID;
}

Use an arraylist of these objects, instead of an arraylist of strings and modify your code in all other places accordingly:

 ArrayList<StudentData> selectedItems = new ArrayList<StudentData>();

Then, at any point, you can access the student ID easily by

 selectedItems.get(index).studentID;
Comments