8

我正在创建一个意图将数据从一个活动传输到另一个活动,如下所示:

Intent intent = new Intent(this, ActivityHighScore.class);
    intent.putExtra("USERNAME", username);
    intent.putExtra("PLAYERMOVES", playerMoves);

    this.startActivity(intent);

然后我想检查所有这些数据在活动开始时是否存在,因为它可以从其他来源启动而无需设置这些数据。我使用这个语句:

        Bundle bundle = getIntent().getExtras();

    if (!bundle.getString("USERNAME").equals(null) && bundle.getInt("PLAYERMOVES") != 0){
        String username = bundle.getString("USERNAME");
        int playerMoves = bundle.getInt("PLAYERMOVES");
        addHighScore(username, playerMoves);

    }   

但这会导致空指针异常,我完全确定如何。我以为我正在掌握字符串和.equals(),但我认为它......任何帮助将不胜感激。谢谢。

4

3 回答 3

18

代替

Bundle bundle = getIntent().getExtras();

    if (!bundle.getString("USERNAME").equals(null) && bundle.getInt("PLAYERMOVES") != 0){
        String username = bundle.getString("USERNAME");
        int playerMoves = bundle.getInt("PLAYERMOVES");
        addHighScore(username, playerMoves);

    } 

 if (getIntent().getStringExtra("USERNAME") != null && (getIntent().getIntExtra("PLAYERMOVES", 0) != 0){
        String username = bundle.getString("USERNAME");
        int playerMoves = bundle.getInt("PLAYERMOVES");
        addHighScore(username, playerMoves);

  } 
于 2012-05-20T14:47:37.823 回答
3

好吧,我有一个类似的问题。在我的情况下,NullPointerException当我检查 mybundle.getString()是否等于时发生null

在我的情况下,这是我解决它的方法:

Intent intent = getIntent();        
if(intent.hasExtra("nomeUsuario")){
    bd = getIntent().getExtras();
    if(!bd.getString("nomeUsuario").equals(null)){
        nomeUsuario = bd.getString("nomeUsuario");
    }
}
于 2015-03-31T16:19:38.517 回答
-1

您正在做的方法是正确的。空指针异常来了,因为片段没有被正确的片段对象替换。 这是工作代码活动类

Bundle bundle = new Bundle();
bundle.putString("message", "helloo");
Home tm = new Home();
tm.setArguments(bundle);
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frag,tm).commit();
getSupportActionBar().setTitle("Home");
item.setChecked(true);
drawerLayout.closeDrawers();

在片段中接收的代码

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    String myValue = getArguments().getString("message");
    Toast.makeText(getActivity(), myValue, Toast.LENGTH_SHORT).show();
    myview = inflater.inflate(R.layout.fragment_home, container, false);
    return myview;
}

如果有帮助,请告诉我!

于 2016-08-02T18:52:19.300 回答