質問

anyone know why this is giving me an error on weights?

error:

Type mismatch: cannot convert from element type Object to String

 public void viewWeightHandler(View view) {
    List weights = this.dh.selectAll();
    StringBuilder sb = new StringBuilder();
    sb.append("Previous Weights:\n");
    for (String weight : weights) {
        sb.append(weight + "\n");
    }
    Log.d("WEIGHT", "weight size - " + weights.size());
    output.setText(sb.toString());
}

output is a textview to display results

weight is what the user has inputed

weights is the list that is produced.

as far as i know this above should loop and for each weight it should insert it into weights and display as such (if input is 1, 22,3)

1

22

3

any help would be appreciated

役に立ちましたか?

解決

Try changing your for loop:

for (Object weight : weights) {
    sb.append(weight.toString() + "\n");
}

The problem is you got the weights out of the database as type Object. But you can't just treat Objects as Strings without doing some sort of casting first.

他のヒント

I think you make an error in iterating the weights (using the enhanced for loop):

  for (List weight : weights) {
      sb.append(weight + "\n");
  }

Declaring it that way, means that every element of weights should be list (thus the iterating variable is also list). However, I think this is not the case. I do not exactly know what kind of elements the list store, I would assume it is String:

    List<String> weights =      this.dh.selectAll();
    StringBuilder sb = new StringBuilder();
    sb.append("Previous Weights:\n");
    for (String weight : weights) {
        sb.append(weight + "\n");
    }

It is very bad practise to use raw type, without generic parameter, it is harder to understand, disables the content assist and may lead to errors like yours (thus I added the <String>.

However, the error I am correcting will not cause compilation error but ClassCastException at runtime.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top