Append a comma with StringBuilder
10,602
Solution 1
That line.separator after get the latitude will put a new line after it, I do not think you want that.
To add the comma just do another append.
Only need one try/catch block on failure.
StringBuilder jsonStringBuilder = new StringBuilder();
// display profile data in EditText
try
{
jsonStringBuilder.append(product.getString(TAG_LATITUDE));
jsonStringBuilder.append(", ");
jsonStringBuilder.append(product.getString(TAG_LONGITUDE));
lblDummyLocation.setText(jsonStringBuilder.toString());
}
catch (JSONException e)
{
e.printStackTrace(); // use a logger for this ideally
lblDummyLocation.setText("Failed to get co-ordinates");
}
Solution 2
Try something like
jsonStringBuilder.append(product.getString(TAG_LATITUDE) + ", ");
Alternatively, you can precede your longitude instead:
jsonStringBuilder.append(", " + product.getString(TAG_LONGITUDE));
![Ankhit Sharma](https://i.stack.imgur.com/XkhpA.jpg?s=256&g=1)
Comments
-
Ankhit Sharma about 2 years
I've got a small problem, my code works and sends me the output of a longitude and latitude. I would simply like a comma and space to separate the value in the textview. I do not want a line separator.
What I get: 32.67543-55.986454
What I want: 32.67543, -55.986454 (comma and space)
Any ideas?
Code:
/** * After completing background task Dismiss the progress dialog * * */ protected void onPostExecute(JSONObject product) { if (product != null) { // product with this pid found // Edit Text lblDummyLocation = (TextView) findViewById(R.id.lblDummyLocation); StringBuilder jsonStringBuilder = new StringBuilder(); //Create StringBuilder for concatenation of JSON results // display profile data in EditText try { //txtMessage.setText(product.getString(TAG_FIRSTNAME)); //Don't set the text here jsonStringBuilder.append(product.getString(TAG_LATITUDE)); //Concatenate each separate item jsonStringBuilder.append(System.getProperty("line.separator")); } catch (JSONException e) { e.printStackTrace(); } try { //txtMessage.setText(product.getString(TAG_LASTNAME)); jsonStringBuilder.append(product.getString(TAG_LONGITUDE)); //jsonStringBuilder.append(System.getProperty("line.separator")); } catch (JSONException e) { e.printStackTrace(); } lblDummyLocation.setText(jsonStringBuilder.toString()); } // dismiss the dialog once got all details pDialog.dismiss(); }
}
-
brso05 about 9 years
jsonStringBuilder.append(", ")
-
-
KevinL about 9 yearsI don't like this approach, as it defeats the purpose of having StringBuilders. Java does some stuff under the hood and translates
jsonStringBuilder.append(product.getString(TAG_LATITUDE) + ", ");
tojsonStringBuilder.append(product.getString(new StringBuilder().append(TAG_LATITUDE).append(", ").toString());
So, it's better from a performance point of view to just make separate append calls like Sanj suggested