java - URLEncoder 中的 NullPointerException

标签 java android

运行代码时出现以下错误:

java.lang.RuntimeException: An error occured while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:299)
    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
    at java.lang.Thread.run(Thread.java:864)
Caused by: java.lang.NullPointerException
    at libcore.net.UriCodec.encode(UriCodec.java:132)
    at java.net.URLEncoder.encode(URLEncoder.java:57)
    at com.example.ayushspc.fileupload.MainActivity$BackgroundTask.doInBackground(MainActivity.java:171)
    at com.example.ayushspc.fileupload.MainActivity$BackgroundTask.doInBackground(MainActivity.java:107)
    at android.os.AsyncTask$2.call(AsyncTask.java:287)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
    at java.lang.Thread.run(Thread.java:864)

代码 MainActivity :

package com.example.ayushspc.fileupload;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class MainActivity extends Activity {
EditText editText;
private String text = null;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;

private String upLoadServerUri = null;
private String imagepath = null;

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    editText = (EditText) findViewById(R.id.textbox);
    upLoadServerUri = "";
}

public void selectFile(View view) {
    Intent intent = new Intent();
    intent.setType("*/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
    text = editText.getText().toString();
    text += "/";
    Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}

public void uploadFile(View view) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {

            Toast.makeText(getApplicationContext(), "Uplaod Started", Toast.LENGTH_SHORT).show();
        }
    });

    new BackgroundTask().execute(imagepath, text);
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
        }
    });

}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    new BgTask().execute(requestCode, resultCode, data);
}

public String getPath(Uri uri) {
    String[] projection = {MediaStore.Images.Media.DATA};
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

class BackgroundTask extends AsyncTask<String, Void, Integer> {
    @Override
    protected Integer doInBackground(String... params) {
        String fileuri = params[0];
        String filePath = params[1];

        HttpURLConnection conn;
        DataOutputStream dos;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1024 * 1024;
        int maxSize = 1024 * 1024;
        File sourceFile = new File(fileuri);
        final long length = sourceFile.length();
        if (length / maxSize > 1) {
            dialog.dismiss();
            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(getApplicationContext(), "File Larger than 1MB", Toast.LENGTH_SHORT).show();
                }
            });
            return 0;
        }

        if (!sourceFile.isFile()) {

            dialog.dismiss();

            Log.e("uploadFile", "Source File not exist :" + imagepath);

            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(getApplicationContext(), "Source File not exist :", Toast.LENGTH_SHORT).show();
                }
            });

            return 0;

        } else {
            try {
                // open a URL connection to the Servlet

                FileInputStream fileInputStream = new FileInputStream(sourceFile);
                URL url = new URL(upLoadServerUri);

                // Open a HTTP  connection to  the URL
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true); // Allow Inputs
                conn.setDoOutput(true); // Allow Outputs
                conn.setUseCaches(false); // Don't use a Cached Copy
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                conn.setRequestProperty("uploaded_file", fileuri);

                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                String data = URLEncoder.encode("file_path", "UTF-8") + "=" + URLEncoder.encode(filePath, "UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();


                dos = new DataOutputStream(conn.getOutputStream());

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                        + fileuri + "\"" + lineEnd);

                dos.writeBytes(lineEnd);

                // create a buffer of  maximum size
                bytesAvailable = fileInputStream.available();

                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];

                // read file and write it into form...
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                while (bytesRead > 0) {

                    dos.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                }

                // send multipart form data necesssary after file data...
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                // Responses from the server (code and message)
                serverResponseCode = conn.getResponseCode();
                final String serverResponseMessage = conn.getResponseMessage();

                Log.i("uploadFile", "HTTP Response is : "
                        + serverResponseMessage + ": " + serverResponseCode);

                if (serverResponseCode == 200) {

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, serverResponseMessage, Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                //close the streams //

                fileInputStream.close();
                dos.flush();
                dos.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
            return serverResponseCode;

        } // End else block

    }
}

class BgTask extends AsyncTask<Object, Void, Void> {

    @Override
    protected Void doInBackground(Object... params) {
        Integer requestCode = (Integer) params[0];
        Integer resultCode = (Integer) params[1];
        Intent data = (Intent) params[2];
        if (requestCode == 1 && resultCode == RESULT_OK) {
            Uri selectedImageUri = data.getData();
            imagepath = getPath(selectedImageUri);
        }
        return null;
    }
}
}

而且它一直报错 String data = URLEncoder.encode("file_path", "UTF-8") + "=" + URLEncoder.encode(filePath, "UTF-8");

谁能指出错误是什么以及我应该做什么来纠正它?

最佳答案

显然,filePath 为空。在对其进行操作之前,请确保您的数据不为空。

关于java - URLEncoder 中的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35817864/

相关文章:

java - class is-a-JPanel 当它应该有-a

java - 登录Spring Security后如何返回Basic token?

android - 安装存储库并同步项目

java - 在 Android 中通过 exec 函数运行 Ping

android - 处理程序 postDelayed 无法更新 UI

java - 使用 EasyMock 在子类中模拟父类(super class)的对象

java - 想要统计Java中字符串的出现次数

java - 无法在 java servlet 中执行更新查询

Android 构建无法获取所有可用的 "VERSION_CODES"

android - 父级 wraps_content 和子级 fills_parent 是什么意思?