以编程方式设置操作栏高程会抛出NullPointer异常

时间:2015-07-29 21:18:07

标签: java android android-actionbar android-support-library android-elevation

以编程方式设置操作栏的高程后,代码将以黄色突出显示,并且会抛出下面的警告。如何删除此警告?

getSupportActionBar().setElevation(0);

警告

  

方法调用'getSupportActionBar()。setElevation(0);'可能会产生'java.lang.NullPointerException'

2 个答案:

答案 0 :(得分:4)

添加空检查:

enum SerialProcessState
    {
        SERIAL_PROCESS_SEARCH_START,
        SERIAL_PROCESS_VERIFY_ELEMENTS,
        SERIAL_PROCESS_DATA,
        SERIAL_PROCESS_SEARCH_END}

    ;
SerialProcessState serialProcessState = SerialProcessState.SERIAL_PROCESS_SEARCH_START;

enum SerialProcessValue
    {
        SERIAL_PACKET_START = 0xF0,
        SERIAL_PACKET_END = 0xF1,
        SERIAL_PACKET_ESCAPE = 0xF2,
        SERIAL_PACKET_ESCAPE_START = 0x00,
        SERIAL_PACKET_ESCAPE_END = 0x01,
        SERIAL_PACKET_ESCAPE_ESCAPE = 0x02,
        SERIAL_PACKET_ELEMENTS = 0x06}

    ;

private void SerialProcess(byte serialData)
    {
        UInt16 Dummy;

        for (Dummy = 0; Dummy < 63; Dummy++) {
            serialhistory[Dummy] = serialhistory[Dummy + 1];
        }
        serialhistory[63] = serialData;

        if ((SerialProcessValue)serialData == SerialProcessValue.SERIAL_PACKET_START) {
            serialProcessState = SerialProcessState.SERIAL_PROCESS_SEARCH_START;
            serialEscaped = false;
        }

        switch (serialProcessState) {
            case SerialProcessState.SERIAL_PROCESS_SEARCH_START:
                if ((SerialProcessValue)serialData == SerialProcessValue.SERIAL_PACKET_START) {
                    checksum = 0;
                    serialProcessState = SerialProcessState.SERIAL_PROCESS_VERIFY_ELEMENTS;
                }
                break;
  .
  .

}

答案 1 :(得分:2)

//foo.h
class foo
{
    public:
        foo(const QString fileName);
        foo(QFile *fp);
        ...
        ...
}

//foo.cpp

class foo::foo(const QString fileName)
{
    if(fileName.isEmpty()) {
        // Return error.
    } else {
        // Open file and pass the address to the second constructor.
        fp = new QFile(fileName);
        fp->open(...);
        foo::foo(fp);   // Execute second constructor.
    }
}

class foo::foo(QFile *fp)
{
    if(fp == NULL) {
        // Return error.
    } else {
        // Do stuff with open file and further initiate the object.
    }
}