图像上传时的排球库问题

时间:2015-03-01 20:15:38

标签: android

我正在尝试使用带有HTTP POST请求的Volley库将图像作为base64编码字符串上传到服务器 但是我在logcat上收到了这条消息:

03-02 01:20:35.412:I / dalvikvm(1538):找不到方法android.net.TrafficStats.setThreadStatsTag,从方法com.android.volley.NetworkDispatcher.addTrafficStatsTag中引用

我的执行控制器没有到达uploadfile()我猜,我该如何解决?

public class UploadActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.upload);
        txtPercentage = (TextView) findViewById(R.id.txtPercentage);
        btnUpload = (Button) findViewById(R.id.btnUpload);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        imgPreview = (ImageView) findViewById(R.id.imgPreview);
        // vidPreview = (VideoView) findViewById(R.id.videoPreview);

        // Changing action bar background color
        // getActionBar().setBackgroundDrawable(
        // new ColorDrawable(Color.parseColor(getResources().getString(
        // R.color.action_bar))));

        // Receiving the data from previous activity
        Intent i = getIntent();

        // image or video path that is captured in previous activity
        imgPath = i.getStringExtra("filePath");
        fileName = i.getStringExtra("fileName");

        // boolean flag to identify the media type, image or video
        boolean isImage = i.getBooleanExtra("isImage", true);

        if (imgPath != null) {
            // Displaying the image or video on the screen
            previewMedia(isImage);
        } else {
            Toast.makeText(getApplicationContext(),
                    "Sorry, file path is missing!", Toast.LENGTH_LONG).show();
        }

        btnUpload.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // uploading the file to server
                new UploadFileToServer().execute();
            }
        });

    }

    /**
     * Displaying captured image/video on the screen
     * */
    private void previewMedia(boolean isImage) {
        // Checking whether captured media is image or video
        if (isImage) {
            imgPreview.setVisibility(View.VISIBLE);
            // vidPreview.setVisibility(View.GONE);
            // bimatp factory
            BitmapFactory.Options options = new BitmapFactory.Options();

            // down sizing image as it throws OutOfMemory Exception for larger
            // images
            options.inSampleSize = 8;

            final Bitmap bitmap = BitmapFactory.decodeFile(imgPath, options);

            imgPreview.setImageBitmap(bitmap);
        } else {
            // imgPreview.setVisibility(View.GONE);
            // vidPreview.setVisibility(View.VISIBLE);
            // vidPreview.setVideoPath(filePath);
            // start playing
            // vidPreview.start();
        }
    }

    /**
     * Uploading the file to server
     * */
    private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
        @Override
        protected void onPreExecute() {
            // setting progress bar to zero
            progressBar.setProgress(0);
            super.onPreExecute();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            // Making progress bar visible
            progressBar.setVisibility(View.VISIBLE);

            // updating progress bar value
            progressBar.setProgress(progress[0]);

            // updating percentage value
            txtPercentage.setText(String.valueOf(progress[0]) + "%");
        }

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

            encodeImageToString();
            return uploadFile();


        }

        private String encodeImageToString() {


            BitmapFactory.Options options = null;
            options = new BitmapFactory.Options();
            options.inSampleSize = 3;
            bitmap = BitmapFactory.decodeFile(imgPath, options);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            // Must compress the Image to reduce image size to make upload easy
            bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
            byte[] byte_arr = stream.toByteArray();
            // Encode Image to String
            encodedString = Base64.encodeToString(byte_arr, 0);
            //Log.e(TAG, "encode" + encodedString);
            return "";

        }




        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);


            // showing the server response in an alert dialog
            showAlert(result);

        }

    }

    /**
     * Method to show alert dialog
     * */
    private void showAlert(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(message).setTitle("Response from Servers")
                .setCancelable(false)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // do nothing
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    private String uploadFile() {

        Log.e("upload starting" , "");

        String url = "http://fileupload.php";
        String tag_json_obj = "json_obj_req";
          resp = "";
        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, url,
                null, new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("Upload response", response.toString());
                        resp = response.toString();
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());

                    }
                }) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("image", encodedString );
                params.put("filename", fileName);
                params.put("password", "password123");

                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
        Log.e("upload finish",resp);
        return resp;

    }


}

0 个答案:

没有答案