Fifer Sheep
Fifer Sheep

Reputation: 2990

Adding an Object to StringBuilder

I'm pretty new to Android development, and what I'm trying to do is display the contents of an ArrayList in a TextView.

I've been attempting to convert the ArrayList into an Array, and then append each item to a StringBuilder. However, the StringBuilder doesn't appear to allow me to append an Object from the Array. Can anyone tell me why, or in fact provide a better solution?

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    ArrayList<String> temp = new ArrayList<String>();
    temp = data.getStringArrayListExtra("intentReturn");
    Object obj[] = temp.toArray();
    for(int i = 0; i < obj.length; i++){
        sBuilder.append((String)obj[i]); //This is the line which crashes the app
        if(i < obj.length - 1){
            sBuilder.append(", ");
        }
    }
    tvResult.setText(sBuilder.toString());
}

Many thanks in advance.

Upvotes: 0

Views: 2907

Answers (3)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

1. I did NOT understood your reason to convert the ArrayList to Array.

2. Try it this way... I am directly appending String from ArrayList to the StringBuilder, using For-Each Loop

Eg:

for (String te : temp){
    sBuilder.append(te);
}

Upvotes: 1

Fifer Sheep
Fifer Sheep

Reputation: 2990

Apparently I forgot to add StringBuilder sBuilder = new StringBuilder(); - silly newbie! Thanks to Jeffrey for his code clean up too, much appreciated!

In order to provide a sufficient answer, here is my new code:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    StringBuilder sBuilder = new StringBuilder();
    ArrayList<String> temp = new ArrayList<String>();
    temp = data.getStringArrayListExtra("intentReturn");
    for(int i = 0; i < temp.size(); i++){
        sBuilder.append(temp.get(i).toString());
        if(i < temp.size() - 1){
            sBuilder.append(", ");
        }
    }
    tvResult.setText(sBuilder.toString());
}

Upvotes: 0

Brad
Brad

Reputation: 9223

Change your sBuilder append line to this:

sBuilder.append(obj[i].toString());

That way you're not trying to cast an Object to a String, but rather getting the Object's String representation.

The documentation for Object.toString()

Upvotes: 1

Related Questions