java / android NullPointerException thrown on a St

2019-08-08 17:08发布

I have what seems like a very simple method, written in java for an android application:

EDIT 1: private String newResponse;

public SOME METHOD CALLED FIRST
{
    newResponse = "";
}

END OF EDIT 1

public synchronized void reportMessage(String message)
{
    try
    {
        newResponse = newResponse + message;

        confirmQE(); //Look for qe in the message
    }
    catch (Exception e)
    {
        response = e.getCause().toString();
    }
}

When I run the application in debugger mode, it 'suspends' on the line:

newResponse = newResponse + message;

It says in the debug window:

Thread[<9> Thread-10] (Suspended (exception NullPointerException))

This occurs only some of the time. Sometimes it runs the line fine.

It never goes into the catch clause and when you click continue, the app crashes. There isn't a break point on the line so I don't even know why it is suspending there.

newResponse is of type String, defined as a global variable.

Can anyone help?

4条回答
爷的心禁止访问
2楼-- · 2019-08-08 17:36
public synchronized void reportMessage(String message)
{
    try
    {
        if(newResponse == null){
            newResponse = message;
        }else{
            newResponse = newResponse + message;
        }

        confirmQE(); //Look for qe in the message
    }
    catch (Exception e)
    {
        response = e.getCause().toString();
    }
}

Try above code..

查看更多
小情绪 Triste *
3楼-- · 2019-08-08 17:36

I have fixed the problem.

For anyone wondering, I added

if("".equals(newResponse))
{ 
    newResponse = new String();
}

before

newResponse = newResponse + message;

And that prevents the error.

Thanks for everyone's help.

查看更多
在下西门庆
4楼-- · 2019-08-08 17:38

Inspect the individual variables to see which one is null.

Also, e.getCause() may be returning null also, so you may have an exception inside your exception handler as well.

查看更多
劫难
5楼-- · 2019-08-08 17:40
try
    {
        // NOW add following condition and initialize newResponce only when it is null
        if(null == newResponse)
        {
            newResponse = new String();
        }
        System.out.println("newResponse"+newResponse);  //<--Add this two lines
        System.out.println("message"+message); // and check which line gives you NullPointerException

        newResponse = newResponse + message;

        confirmQE(); //Look for qe in the message
    }
查看更多
登录 后发表回答