[当我尝试为TextView设置值时,应用程序崩溃。如果我在onCreate的getUsername方法中编写它,则不会崩溃。每当我单击“从注册登录”时,应用程序就会崩溃。但是启动时一切正常。我在不同的地方尝试过OnCreate方法。该ID在导航布局中。为什么 ?提前致谢!
public class UserHomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, UserOnFragmentBtnSelected {
Toolbar toolbar;
DrawerLayout drawer;
ActionBarDrawerToggle toggle;
NavigationView navigationView;
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
Fragment fragment;
String username;
TextView tf, tf2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_user);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//kontostandUpdaten();
//getSupportActionBar().setTitle("Netvision");
drawer = findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = findViewById(R.id.nav_view);
navigationView.bringToFront();
navigationView.setCheckedItem(R.id.nav_home);
navigationView.setNavigationItemSelectedListener(this);
//Default Fragment laden
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.container_fragment, new UserFragmentHome());
fragmentTransaction.commit();
tf = (TextView) findViewById(R.id.nav_header_user_name);
tf2 = (TextView) findViewById(R.id.nav_header_user_amount);
tf2.setText("hallo");
getUsername();
}
private void getUsername() {
final FirebaseFirestore db = FirebaseFirestore.getInstance();
final FirebaseAuth mAuth = FirebaseAuth.getInstance();
DocumentReference docRef = db.collection("users").document(mAuth.getCurrentUser().getUid());
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
tf = (TextView) findViewById(R.id.nav_header_user_name);
tf2 = (TextView) findViewById(R.id.nav_header_user_amount);
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Users user = document.toObject(Users.class);
//getSupportActionBar().setTitle("Hallo " + user.getUsername());
username = user.getUsername();
if(user == null && username == null) {
//tf2.setText("Loading");
}else{
//tf.setText(username + "");
//tf2.setText(user.getKontostand() + "");
}
getSupportActionBar().setTitle(R.string.app_name);
kontostandUpdaten();
} else {
Toast.makeText(getApplicationContext(), "Der aktuelle Nutzer konnte nicht in der Datenbank gefunden werden.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Ein Problem ist aufgetreten " + task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
您能分享您遇到什么异常吗?
查看代码,好像您是在工作线程而不是UI线程中更改“ tf2”。