我正在使用okhttp来处理网络请求和响应。我已经在web和github上搜索了很多关于这个问题的信息,但是我没有得到任何干净的解决方案,我不知道代码中有什么问题。当我点击btn_继续时,我得到了nullpointerexception。提供了代码和stacktrace。谢谢您。

07-28 02:11:18.407 16167-17029/com.donateblood.blooddonation E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.donateblood.blooddonation, PID: 16167
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:864)
Caused by: java.lang.NullPointerException
at okhttp3.HttpUrl.canonicalize(HttpUrl.java:1853)
at okhttp3.FormBody$Builder.add(FormBody.java:110)
at com.donateblood.blooddonation.UploadImage$AddUserAsync.doInBackground(UploadImage.java:203)
at com.donateblood.blooddonation.UploadImage$AddUserAsync.doInBackground(UploadImage.java:173)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:864)

public class UploadImage extends AppCompatActivity {

    @InjectView(R.id.imageView) ImageView ImageUpload;
    @InjectView(R.id.upload) Button Btn_Upload;
    @InjectView(R.id.proceed) Button Btn_Proceed;
    EditText code;
    public ProgressDialog pDialog;
    public String bloodgroup,name,password,number,email,age,ID;
    public String encodedPhotoString=null;
    GPSTracker gps; public  Bitmap myimage=null;
    public JSONObject json =null;
    public double latitude;

    public double longitude;
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try{
            setContentView(R.layout.uploadimage);
            ButterKnife.inject(this);
        }catch (OutOfMemoryError e){
            Toast.makeText(getBaseContext(), "Sorry,Something went wrong", Toast.LENGTH_SHORT).show();
        }


        code = (EditText) findViewById(R.id.code);
        myimage = CroppingActivity.finalImage;
        CheckImage();
        // Upload image ====================================
        Btn_Upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), CroppingActivity.class);
                startActivity(intent);
                UploadImage.this.finish();
            }
        });
        Btn_Proceed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(code.length()==0){
                    Toast.makeText(getBaseContext(), "Enter verification code", Toast.LENGTH_LONG).show();
                }
                else {
                    Prcoess();
                }
            }
        });
    }
    public  void CheckImage(){
        if(myimage!=null){
            Uri uri = getImageUri(myimage);
            String url = getRealPathFromURI(uri);
            File file = new File(url);
            Glide.with(UploadImage.this).load(file).asBitmap().diskCacheStrategy( DiskCacheStrategy.NONE ).skipMemoryCache( true ).override(300,300)
                    .transform(new CenterCrop(UploadImage.this),new CustomCenterCrop(UploadImage.this)).into(ImageUpload);

        }else {
            encodedPhotoString= null;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }

    public String getRealPathFromURI(Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = UploadImage.this.getContentResolver().query(contentUri,  proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    public Uri getImageUri( Bitmap inImage) {

        String path = MediaStore.Images.Media.insertImage(UploadImage.this.getContentResolver(), inImage, "Title", null);
        return Uri.parse(path);
    }

    // Processing and adding user to database from here ====================================
    public void Prcoess(){
        String userentered=code.getText().toString();
        String sentcode = SignupActivity.Code;
        setPhoto();
        if(userentered.equals(sentcode) && encodedPhotoString!=null ){

            new AddUserAsync().execute();

        }
        else {
            Toast.makeText(getBaseContext(), "Oopps...Sorry...Upload Again", Toast.LENGTH_LONG).show();
        }
    }

    public void setPhoto() {
        // resize the image to store to database
        myimage=  getResizedBitmap(myimage,400,400);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        myimage.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        byte[] byte_arr = stream.toByteArray();
        encodedPhotoString = Base64.encodeToString(byte_arr, 0);
        Log.e("photo string ", encodedPhotoString);
    }


    public class AddUserAsync extends AsyncTask<Void,Void,Void> {

        JSONObject json = null;
        String fromServer = "";
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(UploadImage.this);
            pDialog.setMessage("Creating Account...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
        @Override
        protected Void doInBackground(Void... voids) {
            GetUserDetails();
            GenerateGCMID();
            email= email.trim().toLowerCase();
            //HashMap<String ,String> userDetails = new HashMap<>();
            latitude = GPSTracker.getLatitude();
            longitude =  GPSTracker.getLongitude();
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(50, TimeUnit.SECONDS)
                    .writeTimeout(50, TimeUnit.SECONDS)
                    .readTimeout(50, TimeUnit.SECONDS)
                    .build();

            FormBody.Builder formBuilder = new FormBody.Builder() // Null pointer exception is thrown here
                    .add("ID",ID)
                    .add("Name",name)
                    .add("email",email)
                    .add("password",password)
                    .add("age",age)
                    .add("number",number)
                    .add("bloodgroup",bloodgroup)
                    .add("lat",latitude+"")
                    .add("longi",longitude+"")
                    .add("image",encodedPhotoString);

            RequestBody formBody = formBuilder.build();
            Request request = new Request.Builder()
                    .url("http://faceblood.website/blood_app/Adduser.php")
                    .post(formBody)
                    .build();
            try {
                Response response = client.newCall(request).execute();
                String res = response.body().string();
                json = new JSONObject(res);
                fromServer = json.getString("added");
                Log.e("stringtest",json.getString("added"));
                // Do something with the response.
            } catch (IOException e) {
                Log.e("stringtest IO",e.toString());
                e.printStackTrace();
            } catch (JSONException e) {
                Log.e("stringtest JSON",e.toString());
                e.printStackTrace();
            }
            //json = new HttpCall().postForJSON("http://faceblood.website/blood_app/Adduser.php",userDetails);
            return null;
        }
        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            pDialog.dismiss();

            Log.e("fromServer",fromServer);
            if(fromServer.equals("addeduser")){
                Toast.makeText(getBaseContext(), "Created Successfully", Toast.LENGTH_LONG).show();
                onSignupSuccess();
            }else {
                Toast.makeText(getBaseContext(), "Network problem. Click again", Toast.LENGTH_LONG).show();
            }
        }
    }
    public void GenerateGCMID(){
        GCMClientManager pushClientManager = new GCMClientManager(this, "921544902369");
        pushClientManager.registerIfNeeded(new GCMClientManager.RegistrationCompletedHandler() {
            @Override
            public void onSuccess(String registrationId, boolean isNewRegistration) {
                ID = registrationId;
                Log.e("reg",ID);
            }
            @Override
            public void onFailure(String ex) {
                super.onFailure(ex);
            }
        });
    }
    // Go to another activity on success ====================================
    public void onSignupSuccess() {
        // stop the service we got the latitude and longitude now
        myimage.recycle();
        myimage = null;
        ImageUpload.setImageResource(0);
        stopService(new Intent(this, GPSTracker.class));
        Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
        startActivity(intent);
        finish();
    }

    // fetch user details ====================================
    public void GetUserDetails(){

        bloodgroup = SignupActivity.bloodgroup.toString();
        name = SignupActivity.name.toString();
        email = SignupActivity.email.toString();
        password = SignupActivity.password.toString();
        number = SignupActivity.number.toString();
        age = SignupActivity.age.toString();
    }


    // Resize the image ====================================
    public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth)
    {
        int width = bm.getWidth();
        int height = bm.getHeight();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // create a matrix for the manipulation
        Matrix matrix = new Matrix();
        // resize the bit map
        matrix.postScale(scaleWidth, scaleHeight);
        // recreate the new Bitmap
        Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
        return resizedBitmap;
    }
}

最佳答案

暗示
在okhttp3.formbody$builder.add上(formbody.java:110)
在…uploadimage$adduserasync.doinbackground(uploadimage.java:203)
您在这里的表单中添加了一个空值(在第203行)

FormBody.Builder formBuilder = new FormBody.Builder()
        .add("ID",ID)
        .add("Name",name)
        .add("email",email)
        .add("password",password)
        .add("age",age)
        .add("number",number)
        .add("bloodgroup",bloodgroup)
        .add("lat",latitude+"")
        .add("longi",longitude+"")
        .add("image",encodedPhotoString);

我猜这是从这里开始的,在这里您正在执行另一个异步请求。
public void GenerateGCMID(){
    GCMClientManager pushClientManager = new GCMClientManager(this, "921544902369");
    pushClientManager.registerIfNeeded(new GCMClientManager.RegistrationCompletedHandler() {
        @Override
        public void onSuccess(String registrationId, boolean isNewRegistration) {
            ID = registrationId;
            Log.e("reg",ID);
        }
        @Override
        public void onFailure(String ex) {
            super.onFailure(ex);
        }
    });
}

或者这里是因为static值不是在活动之间传递数据的方式。不能将当前活动中的EditText值“访问”到其他活动中。
// fetch user details ====================================
public void GetUserDetails(){

    bloodgroup = SignupActivity.bloodgroup.toString();
    name = SignupActivity.name.toString();
    email = SignupActivity.email.toString();
    password = SignupActivity.password.toString();
    number = SignupActivity.number.toString();
    age = SignupActivity.age.toString();
}

您可以参考How do I pass data between Activities

07-25 21:22