Devil Raily Devil Raily - 21 days ago 8
Android Question

After split array gives only first character

I have a value in the database table that I would like to split by

|
the value is
Company|company.pdf|images.pdf
. When I run the following code, it only returns
C
in the Debug.

What am I doing wrong?

String cname = null;
String cpdf = null;
String cimages = null;
String catGetGeneralNameSQL = "SELECT * FROM categorymeta WHERE key = 'category_general' AND company = " + dashboard_company_id;
Cursor catGetGeneralNameQuery = myDB.rawQuery(catGetGeneralNameSQL, null);
while(catGetGeneralNameQuery.moveToNext()){
String name = catGetGeneralNameQuery.getString(catGetGeneralNameQuery.getColumnIndex("value"));
String[] separated = name.split("|");
Log.d("LOG", separated[1]);
}

Answer

It's because the split() method take a regular expression as parameter, and | is a reserved character in regexp.

Try with : \\| to escape it.

public static void main(String[] args) {
  String test = "Company|company.pdf|images.pdf";
  String[] result = test.split("\\|");
  System.out.println(result[1]);
}

It outputs :

company.pdf

See the split() method documentation : https://docs.oracle.com/javase/8/docs/api/java/lang/String.html

The pipe (without being escaped) is used in regular expressions to separate alternate matching patterns, eg: aaa|bbb will match "aaa" or "bbb", that's why it's matching every single character when not escaped.

Hope it helps.