Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Split data in two

I need to split a data into two, for example I am getting a data of users along with mobile number so data is like Arif||44444~Balin||33333~Cavin||55555~Den||66666~ So I this can be split like

//Splitting the values
String[] parts = stat.split("~");
final String part1 = parts[0];
final String part2 = parts[1];

But this will get data like Arif||44444, Balin||33333, Cavin||55555, Den||66666

I need to store the data including the name and phonenumber seperately, and I need to display the name in a spinner, so if user select the name from spinner I need to get its corresponding mobile number. I did code for selecting the name.. but for corresponding number I am not getting, if anyone knows please help.

ref = String.valueOf(refdetails.getString("ref", "not found"));

List<String> spinnerArray =  new ArrayList<String>();
//spinnerArray.add(ref);
spinnerArray = Arrays.asList(ref.split("~"));

ArrayAdapter<String> adapter = new ArrayAdapter<String>(
  this, android.R.layout.simple_spinner_item, spinnerArray);

// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
like image 249
Jocheved Avatar asked Mar 26 '26 07:03

Jocheved


1 Answers

Type 1: using regular Expression.

It split non-word character.

parts[i].split("[\W]{2}")

    String stat = "Arif||44444~Balin||33333~Cavin||55555~Den||66666~";
    String[] parts = stat.split("~");
    List<String> names = new ArrayList<>();
    List<String> numbers = new ArrayList<>();

    for(int i = 0; i < parts.length; i++) {         
        names.add(parts[i].split("[\\W]{2}")[0]);          
        numbers.add(parts[i].split("[\\W]{2}")[1]);
    }

Type 2: Using Substring

    String stat = "Arif||44444~Balin||33333~Cavin||55555~Den||66666~";
    String[] parts = stat.split("~");
    List<String> names = new ArrayList<>();
    List<String> numbers = new ArrayList<>();

    for(int i = 0; i < parts.length; i++) {         
        int found = parts[i].indexOf("||");
        names.add(parts[i].substring(0,found));         

        numbers.add(parts[i].substring(found+2,parts[i].length()));

    }


 spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()   {
   @Override
   public void onItemSelected(AdapterView<?> parent, View view, int posion, long id) {

     //here you can get the position (local argument position) of corresponding numbers to the names         

      String name = names.get(position); 
      String number = number.get(position);
   }
  @Override public void onNothingSelected(AdapterView<?> arg0) { 
    // TODO Auto-generated method stub
  } 
});
like image 96
arun Avatar answered Mar 28 '26 20:03

arun