当前位置: 首页 > 知识库问答 >
问题:

ClassCastException:java.util.HashMap不能强制转换为java.lang.String

通学真
2023-03-14
import java.lang.String;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle; 
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;

import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;

public class MainActivity extends AppCompatActivity {

private Firebase mRef;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Firebase.setAndroidContext(this);
}

@Override
protected void onStart() {
    super.onStart();
    Button b1 = (Button) findViewById(R.id.buttonSunny);
    Button b2 = (Button) findViewById(R.id.buttonFoggy);
   final  TextView t1 = (TextView) findViewById(R.id.textView);

    mRef = new Firebase("https://docs-    examples.firebaseio.com/web/saving-data/fireblog/posts");

    mRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String value = (String) dataSnapshot.getValue();
            t1.setText(value);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });
}
}

有人知道怎么解决这个问题吗?

共有1个答案

柴宝
2023-03-14

@Rahul Chaurasia的回答很棒!但我只是想扩展一下如何返回另一个类。

假设您有一个Todo类:

public class Todo {
  private String author;
  private String message;

  public Todo() {
    // empty default constructor, necessary for Firebase to be able to deserialize blog posts
  }

  public String getAuthor() {
    return author;
  }

  public String getMessage() {
    return message;
  }

}

因为这个类有一个空的构造函数,所以它可以用Firebase进行反序列化。

  // Text view
  final TextView t1 = (TextView) findViewById(R.id.textView);

  // Get a reference to our posts
  Firebase ref = new Firebase("<my-firebase-db>/todos/1");

  // Get the todos
  ref.addValueEventListener(new ValueEventListener() {
      @Override
      public void onDataChange(DataSnapshot snapshot) {
         Todo todo = snapshot.getValue(Todo.class);
         t1.setText(todo.getMessage());
      }

      @Override
      public void onCancelled(FirebaseError firebaseError) {
          System.out.println("The read failed: " + firebaseError.getMessage());
      }
  });
 类似资料: