错误是: - 由以下引起:java.lang.NullPointerException:尝试在com的空对象引用上调用虚方法'void android.support.v7.app.ActionBar.setTitle(java.lang.CharSequence)' .example.pratikrathi.registerapp.MainActivity.onCreate(MainActivity.java:49)
如何解决这个问题?为什么我收到此错误?帮助我
public class MainActivity extends AppCompatActivity {
public Button register_button;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
getSupportActionBar().setTitle("RegisterApp");
}
@Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
if (currentUser == null) {
sendToLogin();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()){
case R.id.action_logout_btn:
logOut();
return true;
case R.id.action_settings_btn:
Intent settingsIntent = new Intent(MainActivity.this,SetupActivity.class);
startActivity(settingsIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
private void sendToLogin() {
Intent loginIntent = new Intent(MainActivity.this,LoginActivity.class);
startActivity(loginIntent);
finish();
}
private void logOut() {
mAuth.signOut();
sendToLogin();
}
}
Xml布局文件包含在下面。
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.pratikrathi.registerapp.MainActivity">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
app:title="RegisterApp">
</android.support.v7.widget.Toolbar>
</android.support.design.widget.CoordinatorLayout>
答案 0 :(得分:0)
尝试像这样设置工具栏标题,并检查您的工具栏ID
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle("RegisterApp");