如何解决我试图解决但无法解决的代码中的空指针异常

时间:2019-05-02 07:07:57

标签: java android nullpointerexception

public class MainActivity extends AppCompatActivity {

    public static String URL = "http://192.168.2.6/imageCapture/uploads/uploadimage.php";
    private static final String IMAGE_CAPTURE_FOLDER = "imageCapture/upload";
    private static final int CAMERA_PIC_REQUEST = 1111;
    private Button btnCamera;
    private static File file;
    private static Uri _imagefileUri;
    private TextView resultText;
    private static String _bytes64Sting, _imageFileName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        _imageFileName = String.valueOf(System.currentTimeMillis());
        btnCamera = (Button) findViewById(R.id.button);
        btnCamera.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View view) {
                capture();
            }
        });
    }
    private void capture()
    {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        _imagefileUri = Uri.fromFile(getFile());

        intent.putExtra(MediaStore.EXTRA_OUTPUT, _imagefileUri);
        startActivityForResult(intent, CAMERA_PIC_REQUEST);
    }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == CAMERA_PIC_REQUEST) {
                uploadImage(_imagefileUri.getPath());
            }
        } else if (resultCode == RESULT_CANCELED) {
            // user cancelled Image capture
            Toast.makeText(getApplicationContext(),
                    "User cancelled image capture", Toast.LENGTH_SHORT).show();
        } else {
            // failed to capture image
            Toast.makeText(getApplicationContext(),
                    "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                    .show();
        }
    }

    private void uploadImage(String picturePath) {
        Bitmap bm = BitmapFactory.decodeFile(picturePath);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
        byte[] byteArray = bao.toByteArray();
        _bytes64Sting =  Base64.encodeToString(byteArray,Base64.DEFAULT);
        RequestPackage rp = new RequestPackage();
        rp.setMethod("POST");
        rp.setUri(URL);
        rp.setSingleParam("base64", _bytes64Sting);
        rp.setSingleParam("ImageName", _imageFileName + ".jpg");

        // Upload image to server
        new uploadToServer().execute(rp);

    }

    public class uploadToServer extends AsyncTask<RequestPackage, Void, String> {

        ProgressDialog pd = new ProgressDialog(MainActivity.this);

        protected void onPreExecute() {
            super.onPreExecute();
            resultText = (TextView) findViewById(R.id.textView);
            resultText.setText("New file "+_imageFileName+".jpg created\n");
            pd.setMessage("Image uploading!, please wait..");
            pd.setCancelable(false);
            pd.show();
        }

        @Override
        protected String doInBackground(RequestPackage... params) {

            String content = MyHttpURLConnection.getData(params[0]);
            return content;

        }

        protected void onPostExecute(String result) {

            super.onPostExecute(result);
            pd.hide();
            pd.dismiss();
            resultText.append(result);
        }
    }

    private File getFile() {
        String filepath = Environment.getExternalStorageDirectory().getPath();
        file = new File(filepath, IMAGE_CAPTURE_FOLDER);
        if (!file.exists()) {
            file.mkdirs();
        }

        return new File(file + File.separator + _imageFileName
                + ".jpg");
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
       getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}

这是logcat跟踪:

2019-05-02 12:18:31.424 11584-11670/com.example.imagesnew E/ActivityThread: Failed to find provider info for cn.teddymobile.free.anteater.den.provider
2019-05-02 12:18:47.710 11584-11584/com.example.imagesnew E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.imagesnew, PID: 11584
    java.lang.NullPointerException: Attempt to invoke interface method 'int java.lang.CharSequence.length()' on a null object reference
        at android.widget.TextView.append(TextView.java:4944)
        at com.example.imagesnew.MainActivity$uploadToServer.onPostExecute(MainActivity.java:120)
        at com.example.imagesnew.MainActivity$uploadToServer.onPostExecute(MainActivity.java:94)
        at android.os.AsyncTask.finish(AsyncTask.java:695)
        at android.os.AsyncTask.-wrap1(Unknown Source:0)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:198)
        at android.app.ActivityThread.main(ActivityThread.java:7038)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:523)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:836)

0 个答案:

没有答案