TechCabana
TechCabana

Reputation: 367

Append a comma with StringBuilder

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

Upvotes: 2

Views: 14260

Answers (2)

Sanj
Sanj

Reputation: 850

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

Upvotes: 6

CubeJockey
CubeJockey

Reputation: 2219

Try something like

jsonStringBuilder.append(product.getString(TAG_LATITUDE) + ", ");

Alternatively, you can precede your longitude instead:

jsonStringBuilder.append(", " + product.getString(TAG_LONGITUDE));

Upvotes: 1

Related Questions