不断收到尝试在空对象引用上调用虚拟方法的尝试

时间:2019-06-05 18:13:34

标签: java android android-intent nullpointerexception

我试图从注册活动的“编辑文本”到主活动中获取一个字符串,但是当我运行代码时,出现错误消息:

  

试图调用虚拟方法'java.lang.String   android.content.Intent.getStringExtra(java.lang.String)'上的null   对象引用

RegisterActivity

public class RegisterActivity extends AppCompatActivity {
    LeaderboardManager databaseManager;
    Leaderboard Leaderboard;
    String Username = "User";
    Bundle bundle = new Bundle();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

    }

在RegisterActivity中获取用户名的方法

    public void GoHomeRegister(View v) {

        EditText User = (EditText) findViewById(R.id.User);
        Username = User.getText().toString();
        //SharedPreferences.Editor editor = getSharedPreferences("SharedPreferances", MODE_PRIVATE).edit();
        //editor.putBoolean("IsLoggedIn", true);
        //editor.apply();
        Intent intentR = new Intent(this, MainActivity.class);
        intentR.putExtra("Username", Username);
        startActivity(intentR);
        finish();
        }
    }

MainActivity

public class MainActivity extends AppCompatActivity {
    Intent intentR = getIntent();
    String Username;

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

使用结果的方法

    public void onclick(View v) {

        if (v.getId() == R.id.leaderboard) {
            score = (int) DrawBalls.getScore();
            time = SystemClock.elapsedRealtime() - simpleChronometer.getBase();
            TimeString = getTimeString(time);
            Username = intentR.getStringExtra("Username");
            //Leaderboard = new Leaderboard(Username, score, TimeString);
            //databaseManager.insert(Leaderboard);
            //Intent intent = new Intent(MainActivity.this, LeaderBoardScreenActivity.class);
            //startActivity(intent);

我在下一行后得到错误

Username = intentR.getStringExtra("Username");

0 个答案:

没有答案