Android开发nullpointerexception致命错误doinbackground

时间:2014-03-21 15:43:32

标签: java android android-asynctask nullpointerexception fatal-error

我需要你的帮助,我的代码中存在致命错误。我不知道如何解决这个问题...请帮帮我:)。

我的代码

public class MainActivity extends Activity {

// button to show progress dialog
Button btnShowProgress;

// Progress Dialog
private ProgressDialog pDialog;
ImageView my_image;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0; 

// File url to download
private static String file_url = "https://example.pdf";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // show progress bar button
    btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
    // Image view to show image after downloading
    my_image = (ImageView) findViewById(R.id.my_image);
    /**
     * Show Progress bar click event
     * */
    btnShowProgress.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // starting new Async Task
            new DownloadFileFromURL().execute(file_url);
        }
    });
}

/**
 * Showing Dialog
 * */
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case progress_bar_type: // we set this to 0
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Downloading file. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setMax(100);
        pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pDialog.setCancelable(true);
        pDialog.show();
        return pDialog;
    default:
        return null;
    }
}

/**
 * Background Async Task to download file
 * */
class DownloadFileFromURL extends AsyncTask<String, String, String> {


    private SSLContext context;

    /**
     * Before starting background thread
     * Show Progress Bar Dialog
     * */

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(progress_bar_type);
    }

    /**
     * Downloading file in background thread
     * */
    @Override
    protected String doInBackground(String... f_url) {
        int count;
        try {

此行是以下错误:网址url =新网址(f_url [0]);

           HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();


         // Load the truststore that includes self-signed cert as a "trusted" entry.
            KeyStore truststore;
            truststore = KeyStore.getInstance("BKS");
            InputStream in = getActivity().getResources().openRawResource(R.raw.mykeystore);
            truststore.load(in, "mysecret".toCharArray());

            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(truststore);

            // Create custom SSL context that incorporates that truststore
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustManagerFactory.getTrustManagers(), null);

     connection.setSSLSocketFactory(sslContext.getSocketFactory());


            connection.connect();
            // this will be useful so that you can show a tipical 0-100% progress bar
            int lenghtOfFile = connection.getContentLength();

            // download the file
            InputStream input = new BufferedInputStream(connection.getInputStream(), 8192);

            // Output stream
            OutputStream output = new FileOutputStream("/sdcard/downloadedfile.pdf");

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                // After this onProgressUpdate will be called
                publishProgress(""+(int)((total*100)/lenghtOfFile));

                // writing data to file
                output.write(data, 0, count);
            }

            // flushing output
            output.flush();

            // closing streams
            output.close();
            input.close();

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

        return null;
    }

    private ContextWrapper getActivity() {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * Updating progress bar
     * */
    protected void onProgressUpdate(String... progress) {
        // setting progress percentage
        pDialog.setProgress(Integer.parseInt(progress[0]));
   }

    /**
     * After completing background task
     * Dismiss the progress dialog
     * **/
    @Override
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after the file was downloaded
        dismissDialog(progress_bar_type);

        // Displaying downloaded image into image view
        // Reading image path from sdcard
        String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.pdf";
        // setting downloaded into image view
        my_image.setImageDrawable(Drawable.createFromPath(imagePath));
    }

}
}

这是我的Logcat:

03-21 16:36:26.747: E/AndroidRuntime(5751): FATAL EXCEPTION: AsyncTask #1
03-21 16:36:26.747: E/AndroidRuntime(5751): Process: com.example.test2, PID: 5751
03-21 16:36:26.747: E/AndroidRuntime(5751): java.lang.RuntimeException: An error occured while executing doInBackground()
03-21 16:36:26.747: E/AndroidRuntime(5751):     at android.os.AsyncTask$3.done(AsyncTask.java:300)
03-21 16:36:26.747: E/AndroidRuntime(5751):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
03-21 16:36:26.747: E/AndroidRuntime(5751):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
03-21 16:36:26.747: E/AndroidRuntime(5751):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
03-21 16:36:26.747: E/AndroidRuntime(5751):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-21 16:36:26.747: E/AndroidRuntime(5751):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-21 16:36:26.747: E/AndroidRuntime(5751):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-21 16:36:26.747: E/AndroidRuntime(5751):     at java.lang.Thread.run(Thread.java:841)
03-21 16:36:26.747: E/AndroidRuntime(5751): Caused by: java.lang.NullPointerException: println needs a message
03-21 16:36:26.747: E/AndroidRuntime(5751):     at android.util.Log.println_native(Native Method)
03-21 16:36:26.747: E/AndroidRuntime(5751):     at android.util.Log.e(Log.java:232)
03-21 16:36:26.747: E/AndroidRuntime(5751):     at com.example.test1.MainActivity$DownloadFileFromURL.doInBackground(MainActivity.java:194)
03-21 16:36:26.747: E/AndroidRuntime(5751):     at com.example.test1.MainActivity$DownloadFileFromURL.doInBackground(MainActivity.java:1)
03-21 16:36:26.747: E/AndroidRuntime(5751):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
03-21 16:36:26.747: E/AndroidRuntime(5751):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-21 16:36:26.747: E/AndroidRuntime(5751):     ... 4 more

Stacktrace输出

03-21 18:39:45.957: W/System.err(2061): java.lang.NullPointerException 03-21 18:39:45.967: W/System.err(2061): at com.example.test1.MainActivity$DownloadFileFromURL.doInBackground(MainActivity.java:147) 03-21 18:39:45.967: W/System.err(2061): at com.example.test1.MainActivity$DownloadFileFromURL.doInBackground(MainActivity.java:1) 03-21 18:39:45.967: W/System.err(2061): at android.os.AsyncTask$2.call(AsyncTask.java:288) 03-21 18:39:45.967: W/System.err(2061): at java.util.concurrent.FutureTask.run(FutureTask.java:237) 03-21 18:39:45.967: W/System.err(2061): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 03-21 18:39:45.967: W/System.err(2061): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 03-21 18:39:45.967: W/System.err(2061): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 03-21 18:39:45.967: W/System.err(2061): at java.lang.Thread.run(Thread.java:841)

2 个答案:

答案 0 :(得分:0)

尝试

 Log.e("Error:", " " + e.getMessage());

而不是Log.e(&#34;错误:&#34;,e.getMessage());

// e.getMessage()可以为null或为空。

还添加catch(MalformedURLException e){}并查看为什么抛出url异常

答案 1 :(得分:0)

使您的AsyncTask扩展AsyncTask<String, Void, String>