如何在第一次调用活动时处理没有数据的意图?

时间:2012-02-07 14:44:34

标签: android android-intent

我有两项活动; 主页是我的第一个活动,设置是我的第二项活动。

从Home活动的菜单中调用Settings活动,并通过intent将数据返回到home活​​动。

但是第一次运行android应用程序时,intent会为空,因为第二个活动尚未被调用,所以我在那里得到了异常(Java空指针异常)。

有人可以帮我解决这个问题吗?

编辑:代码

第一项活动:

public class LoginActivity extends Activity {

    public static final int SETTINGS_ID = 1;
    Intent intn;

    EditText edt1;
    EditText edt2;
    String user, pass;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        intn= new Intent(this,SettingsActivity.class);
    }

    private class HttpConnectionRequest extends AsyncTask<Void, Void, Void>{
        @Override
        protected Void doInBackground(Void...params) {
            // TODO Auto-generated method stub
            //Code not included
        }
        return null;
    }
}

public void login(View V){

    edt1 = (EditText) this.findViewById(R.id.editText1);
    edt2 = (EditText) this.findViewById(R.id.editText2);
    user = edt1.getText().toString();
    pass = edt2.getText().toString();
    System.out.println("Username-->" + user);
    System.out.println("Password-->" + pass);
    String url="";
    url = getIntent().getExtras().getString("serverurl");
    System.out.println("url----->"+url);

    if(((null==user) || ("".equals(user))) && ((null==pass) || ("".equals(pass)) )){
        Toast.makeText(getApplicationContext(), "Please provide username and password", Toast.LENGTH_SHORT).show();  
    }
    else if((null==user) || ("".equals(user))){
        Toast.makeText(getApplicationContext(), "Please provide username", Toast.LENGTH_SHORT).show();  
    }
    else if ((null==pass) || ("".equals(pass))){
        Toast.makeText(getApplicationContext(), "Please provide password", Toast.LENGTH_SHORT).show();  
    }

    if ((null==url) || ("".equals(url))) {
        Toast.makeText(getApplicationContext(), "Please provide the Server url Settings->Server URL->Save", Toast.LENGTH_SHORT).show();  
    }

    HttpConnectionRequest conn= new HttpConnectionRequest();
    conn.execute();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // boolean result = super.onCreateOptionsMenu(menu);
    menu.add(0, SETTINGS_ID, 0, "Settings");
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.layout.menu, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case SETTINGS_ID:
            //this.finish();
            this.startActivity(intn);
            System.out.println("This Invoked . . .");
            break;
        }
        return false;
    }
}

第二项活动

public class SettingsActivity extends Activity {

    EditText edt1;
    Intent intn;

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings);
        intn = new Intent (this,LoginActivity.class);
    }

    public void save(View v){
        edt1= (EditText) this.findViewById(R.id.serverurl);
        String url = edt1.getText().toString();
        intn.putExtra("serverurl",url);
        startActivity(intn);        
    }
}

5 个答案:

答案 0 :(得分:35)

您可以检查resultCode,如下所示。

http://developer.android.com/guide/topics/fundamentals/activities.html#StartingAnActivityForResult

另外,你能确定你获得例外的确切位置吗? (可能会发布一些代码)

修改

好的,我仍然不知道你在哪里调用login()方法,但你可以做这个检查以避免你提到的行中的空例外:

if( getIntent().getExtras() != null)
{
  //do here
}

答案 1 :(得分:5)

您可以尝试:

if(intent.getExtras() == null) {
   //Do first time stuff here
} else {
  //Do stuff with intent data here
}

如果每次传回不同的意图值,可以检查Bundle对象(使用intent.getExtras()返回)是否具有使用此设置的某些字段:

Bundle extras = intent.getExtras()
if(extras.containsKey("keytocheck")) {
  //Do stuff because extra has been added
}

答案 2 :(得分:1)

你应该发布更多代码,但它们很可能归结为:

onCreate()
{
  ...
  Intent sourceIntent = getIntent();
  if(sourceIntent == null)
  {
      //rare case where setIntent has been called with null
  }else{
    Bundle params = sourceIntent.getExtras();
    if(params != null)
    {
      //read params
    }else{
      //use defaults
    }
  }
  ...
}

这是伪代码,但您基本上需要检查传递给您的意图是否为null。如果为null,则需要使用一些默认值。

答案 3 :(得分:1)

使用Intent.hasExtra(String name)检查意图中是否传递了名称的额外内容。  例如。你可以尝试这样:

Intent intent = getIntent();    
if(intent.hasExtra(String name)) {      
    // If extra was passed then this block is executed because hasExtra() method would return true on getting extra.    
} else {    
    // If extra was not passed then this block is executed because hasExtra() method would return false on not getting extra.
}

答案 4 :(得分:1)

使用intent.resolveActivity(getPackageManager())可以避免空指针异常。

    if (intent.resolveActivity(getPackageManager())!= null) {
                    startActivity(intent);
//Write startActivity code here

                }