简体   繁体   中英

Potential null pointer access: The variable stream may be null at this location

I received this error in this function and do not know exactly how to solve. "Potential null pointer access: The variable stream may be null at this location" Below is the code:

public void downloadAudioIncrement(String mediaUrl) throws IOException {
        /*URLConnection cn = new URL(mediaUrl).openConnection(Proxy.NO_PROXY);  

        cn.connect();  
        InputStream stream = cn.getInputStream();*/
        URL url = new URL(mediaUrl);

        InputStream stream = url.openStream();
        //Toast.makeText(this.context, "here3", Toast.LENGTH_LONG);

        if (stream == null) {
            Log.e(getClass().getName(), "Não é possível criar InputStream para a url: " + mediaUrl);
        }

        //downloadingMediaFile = new File(context.getCacheDir(),"downloadingMedia_" + (counter++) + ".dat");
        downloadingMediaFile = new File(context.getCacheDir(),"downloadingMedia_.dat");
        FileOutputStream out = new FileOutputStream(downloadingMediaFile);   
        byte buf[] = new byte[16384];

        int totalBytesRead = 0, incrementalBytesRead = 0;
        do {
            int numread = ***stream***.read(buf);   
            if (numread <= 0)
                break;   

            out.write(buf, 0, numread);
            totalBytesRead += numread;
            incrementalBytesRead += numread;
            totalKbRead = totalBytesRead/1000;

            testMediaBuffer();
            fireDataLoadUpdate();
        } while (validateNotInterrupted());   

        if (validateNotInterrupted()) {
            fireDataFullyLoaded();
            //testMediaBuffer();
            //fireDataLoadUpdate();
        }
        ***stream***.close();
        out.close();
    }

How do I fix this error? The error occurs here:

 numread ***stream***.Read = int (buf);

and here:

 ***stream***.Close ();
    if (stream == null) {
        Log.e(getClass().getName(), "Não é possível criar InputStream para a url: " + mediaUrl);
    }

Here, you check if stream is null , and log it, but you still proceed with the method, and you never make a new stream or anything. My suggestion: add a return; to your block:

    if (stream == null) {
        Log.e(getClass().getName(), "Não é possível criar InputStream para a url: " + mediaUrl);
        return;
    }

Change this line to read

 if (stream == null) {
            Log.e(getClass().getName(), "Não é possível criar InputStream para a url: " +     mediaUrl);
return;
    }

that way, the erroneous lines won't be reached with a null value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM