Append a comma with StringBuilder

Issue

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();
}

Solution

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");            
}

Answered By – Sanj

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published