我遇到问题,我试图创建一个使用以前创建的数据填充来自firebase数据库的数据的着陆页。我在这里使用MainActivity中的代码
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private FirebaseAuth firebaseAuth;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
private TextView userName;
NavigationView navigationView = null;
Toolbar toolbar = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//FIREBASE LOGGED IN CHECK
firebaseAuth = FirebaseAuth.getInstance();
if(firebaseAuth.getCurrentUser() == null){
finish();
startActivity(new Intent(this, LoginActivity.class));
}
FirebaseUser user = firebaseAuth.getCurrentUser();
//Set the fragment initially
MainFragment fragment = new MainFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Nothing to see here, move along!", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
View headerView = navigationView.getHeaderView(0);
userName = (TextView) headerView.findViewById(R.id.textViewUserName);
//GET INSTANCE OF DATABASE FROM URL
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReferenceFromUrl("https://userdata-57a47.firebaseio.com/");
DatabaseReference mChild = databaseReference.getRef().child("name");
mChild.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.getValue(String.class);
userName.setText(name);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
我使用DatabaseReference来获取ID,但是当我尝试通过将其转换为使用TextView来输出此信息时,该程序似乎无法替换Textview文本这个名字'我的数据库中的字段
答案 0 :(得分:1)
发布后解决了我自己的问题!
简单修复,在我放置的行上;
DatabaseReference mChild = databaseReference.getRef().child("name");
我以为我在引用我的ID但是getRef()是错误的。相反,我应该使用.getUid()。所以现在我的代码看起来像这样......
DatabaseReference mChild = databaseReference.child(user.getUid().child("name");