如何在对象上检查null,然后如果它为NULL则继续?

时间:2013-02-21 02:00:07

标签: java if-statement nullpointerexception

在Java中,检查对象是否有价值或正在返回null的最佳方法是什么?我发现的大多数例子都不是很好。基本上我有这个代码:

mDBApi.getSession().setAccessTokenPair(reAuthTokens);
System.out.println(reAuthTokens);
if(reAuthTokens.equals(null)) {
    mDBApi.getSession().startAuthentication(Main.this);
    Log.e(TAG, "Keys not set -- I'm starting authentication");
}

我正在尝试检查reAuthTokens的值,如果没有,请继续进行身份验证。但是,我只是在if语句行上得到NullPointerException。有什么我可以做得更好吗?

__ _ __ _ __ _ __ _ onCreate for rcook _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ < / p>

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);


    //AccessTokenPair tokens=null;      
    //AccessTokenPair tokens = getStoredKeys();   
    //System.out.println(access + "here I am"); 
    //clearKeys();
    //Log.e(TAG, "keys cleared");


    AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
    AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
    mDBApi = new DropboxAPI<AndroidAuthSession>(session);
    AccessTokenPair reAuthTokens = new AccessTokenPair(APP_KEY, APP_SECRET);
    mDBApi.getSession().setAccessTokenPair(reAuthTokens);

        System.out.println(reAuthTokens);

    if(reAuthTokens == null) {       
    mDBApi.getSession().startAuthentication(Main.this);
    Log.e(TAG, "Keys not set -- I'm starting authentication");



    }


//



    /*read settings*/
    mSettings = getSharedPreferences(PREFS_NAME, 0);
    boolean hide = mSettings.getBoolean(PREFS_HIDDEN, false);
    boolean thumb = mSettings.getBoolean(PREFS_THUMBNAIL, true);
    int space = mSettings.getInt(PREFS_STORAGE, View.VISIBLE);
    int color = mSettings.getInt(PREFS_COLOR, -1);
    int sort = mSettings.getInt(PREFS_SORT, 3);



    mFileMag = new FileManager();
    mFileMag.setShowHiddenFiles(true);
    mFileMag.setSortType(sort);

    if (savedInstanceState != null)
        mHandler = new EventHandler(Main.this, mFileMag, savedInstanceState.getString("location"));
    else
        mHandler = new EventHandler(Main.this, mFileMag);

    mHandler.setTextColor(color);
    mHandler.setShowThumbnails(thumb);
    mTable = mHandler.new TableRow();

    /*sets the ListAdapter for our ListActivity and
     *gives our EventHandler class the same adapter
     */
    mHandler.setListAdapter(mTable);
    setListAdapter(mTable);

    /* register context menu for our list view */
    registerForContextMenu(getListView());

    mStorageLabel = (TextView)findViewById(R.id.storage_label);
    mDetailLabel = (TextView)findViewById(R.id.detail_label);
    mPathLabel = (TextView)findViewById(R.id.path_label);
    mPathLabel.setText("path: /sdcard");

    updateStorageLabel();
    mStorageLabel.setVisibility(space);

    mHandler.setUpdateLabels(mPathLabel, mDetailLabel);

    /* setup buttons */
    int[] img_button_id = {R.id.help_button, R.id.home_button, 
                           R.id.back_button, R.id.info_button, 
                           R.id.manage_button, R.id.multiselect_button,
                           R.id.dropbox_button
                           };

    int[] button_id = {R.id.hidden_copy, R.id.hidden_attach,
                       R.id.hidden_delete, R.id.hidden_move};

    ImageButton[] bimg = new ImageButton[img_button_id.length];

    Button[] bt = new Button[button_id.length];

    for(int i = 0; i < img_button_id.length; i++) {
        bimg[i] = (ImageButton)findViewById(img_button_id[i]);
        bimg[i].setOnClickListener(mHandler);

        if(i < 4) {
            bt[i] = (Button)findViewById(button_id[i]);
            bt[i].setOnClickListener(mHandler);
        }
    }

    Intent intent = getIntent();

    if(intent.getAction().equals(Intent.ACTION_GET_CONTENT)) {
        bimg[5].setVisibility(View.GONE);
        mReturnIntent = true;

    } else if (intent.getAction().equals(ACTION_WIDGET)) {
        Log.e("MAIN", "Widget action, string = " + intent.getExtras().getString("folder"));
        mHandler.updateDirectory(mFileMag.getNextDir(intent.getExtras().getString("folder"), true));

    }
}

1 个答案:

答案 0 :(得分:5)

请改用if (reAuthTokens == null))。你不是要比较对象的内容;你试图比较参考文献。 “reAuthTokens是否指向与null相同的地址?”

来自OP的更新

编辑reAuthTokens的类型为AccessTokenPair(我打赌许多读者最初认为这是List ..我知道我做了。它在这一行中被实例化:

AccessTokenPair reAuthTokens = new AccessTokenPair(APP_KEY, APP_SECRET);

这就是为什么以下条件总是错误的:reAuthTokens == null。这就是为什么,当编码if (reAuthTokens == null)时,你得到一个“死代码”警告:编译器知道这个条件永远不会成立,因为你在上面几行实例化reAuthTokens

因此,您所追求的比较类型不是参考,而是内容。您想检查reAuthTokens是否为“空”。但是从你引用的代码中没有意义。你怎么实例化对象,然后想检查它是否“空”?

我认为你的逻辑不对。您应该首先从您期望的位置(会话?)获取访问令牌对,并将结果与​​null进行比较。像这样:

AccessTokenPair reAuthTokens = mDBApi.getSession().getAccessTokenPair();

if (reAuthTokens == null) {
    reAuthTokens = new AccessTokenPair(...);
    mDBApi.getSession().setAccessTokenPair(reAuthTokens);
}