将图像上传到服务器时出现Android错误

时间:2014-03-30 09:03:49

标签: java android

我正在使用教程中的以下代码: http://geekonjava.blogspot.in/2014/03/upload-image-on-server-in-android-using.html

每当我运行代码时,它会在log cat上显示以下错误,并在单击Upload Button时强制关闭应用程序。任何人都可以帮我吗?

03-30 09:00:35.026: E/Trace(1086): error opening trace file: No such file or directory (2)
03-30 09:00:35.238: D/libEGL(1086): loaded /system/lib/egl/libEGL_emulation.so
03-30 09:00:35.242: D/(1086): HostConnection::get() New Host Connection established 0xb85a7800, tid 1086
03-30 09:00:35.646: D/libEGL(1086): loaded /system/lib/egl/libGLESv1_CM_emulation.so
03-30 09:00:35.650: D/libEGL(1086): loaded /system/lib/egl/libGLESv2_emulation.so
03-30 09:00:37.062: W/EGL_emulation(1086): eglSurfaceAttrib not implemented
03-30 09:00:37.106: D/OpenGLRenderer(1086): Enabling debug mode 0
03-30 09:00:37.158: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb8550e18): name, size, mSize = 1, 1048576, 1048576
03-30 09:00:38.226: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb8562e40): name, size, mSize = 2, 2304, 1050880
03-30 09:00:38.386: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb85555a0): name, size, mSize = 4, 9216, 1060096
03-30 09:00:38.398: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb858bd48): name, size, mSize = 5, 3328, 1063424
03-30 09:00:38.486: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb8539dd0): name, size, mSize = 7, 1024, 1064448
03-30 09:00:43.450: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb8577238): name, size, mSize = 9, 3328, 1067776
03-30 09:00:43.898: W/dalvikvm(1086): threadid=10: thread exiting with uncaught exception (group=0xa62e3288)
03-30 09:00:43.898: E/AndroidRuntime(1086): FATAL EXCEPTION: Thread-95
03-30 09:00:43.898: E/AndroidRuntime(1086): java.lang.NullPointerException
03-30 09:00:43.898: E/AndroidRuntime(1086):     at java.io.File.fixSlashes(File.java:185)
03-30 09:00:43.898: E/AndroidRuntime(1086):     at java.io.File.<init>(File.java:134)
03-30 09:00:43.898: E/AndroidRuntime(1086):     at com.sunil.upload.MainActivity.uploadFile(MainActivity.java:115)
03-30 09:00:43.898: E/AndroidRuntime(1086):     at com.sunil.upload.MainActivity$1.run(MainActivity.java:72)
03-30 09:00:43.898: E/AndroidRuntime(1086):     at java.lang.Thread.run(Thread.java:856)
03-30 09:00:44.050: W/EGL_emulation(1086): eglSurfaceAttrib not implemented
03-30 09:00:44.230: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb8558c50): name, size, mSize = 12, 15360, 1083136
03-30 09:00:44.242: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb8551420): name, size, mSize = 13, 9216, 1092352
03-30 09:00:44.294: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb8551880): name, size, mSize = 14, 9216, 1101568
03-30 09:00:45.598: D/OpenGLRenderer(1086): TextureCache::flush: target size: 660940
03-30 09:00:45.598: D/OpenGLRenderer(1086): TextureCache::callback: name, removed size, mSize = 9, 3328, 1098240
03-30 09:00:45.598: D/OpenGLRenderer(1086): TextureCache::callback: name, removed size, mSize = 1, 1048576, 49664
03-30 09:00:45.634: E/WindowManager(1086): Activity com.sunil.upload.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@53473594 that was originally added here
03-30 09:00:45.634: E/WindowManager(1086): android.view.WindowLeaked: Activity com.sunil.upload.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@53473594 that was originally added here
03-30 09:00:45.634: E/WindowManager(1086):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374)
03-30 09:00:45.634: E/WindowManager(1086):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292)
03-30 09:00:45.634: E/WindowManager(1086):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
03-30 09:00:45.634: E/WindowManager(1086):  at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
03-30 09:00:45.634: E/WindowManager(1086):  at android.view.Window$LocalWindowManager.addView(Window.java:547)
03-30 09:00:45.634: E/WindowManager(1086):  at android.app.Dialog.show(Dialog.java:277)
03-30 09:00:45.634: E/WindowManager(1086):  at android.app.ProgressDialog.show(ProgressDialog.java:116)
03-30 09:00:45.634: E/WindowManager(1086):  at android.app.ProgressDialog.show(ProgressDialog.java:99)
03-30 09:00:45.634: E/WindowManager(1086):  at com.sunil.upload.MainActivity.onClick(MainActivity.java:67)
03-30 09:00:45.634: E/WindowManager(1086):  at android.view.View.performClick(View.java:4084)
03-30 09:00:45.634: E/WindowManager(1086):  at android.view.View$PerformClick.run(View.java:16966)
03-30 09:00:45.634: E/WindowManager(1086):  at android.os.Handler.handleCallback(Handler.java:615)
03-30 09:00:45.634: E/WindowManager(1086):  at android.os.Handler.dispatchMessage(Handler.java:92)
03-30 09:00:45.634: E/WindowManager(1086):  at android.os.Looper.loop(Looper.java:137)
03-30 09:00:45.634: E/WindowManager(1086):  at android.app.ActivityThread.main(ActivityThread.java:4745)
03-30 09:00:45.634: E/WindowManager(1086):  at java.lang.reflect.Method.invokeNative(Native Method)
03-30 09:00:45.634: E/WindowManager(1086):  at java.lang.reflect.Method.invoke(Method.java:511)
03-30 09:00:45.634: E/WindowManager(1086):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
03-30 09:00:45.634: E/WindowManager(1086):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-30 09:00:45.634: E/WindowManager(1086):  at dalvik.system.NativeStart.main(Native Method)
03-30 09:00:45.906: I/Process(1086): Sending signal. PID: 1086 SIG: 9

代码:

public class MainActivity extends Activity implements OnClickListener{

    private TextView messageText;
    private Button uploadButton, btnselectpic;
    private ImageView imageview;
    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);

        uploadButton = (Button)findViewById(R.id.uploadButton);
        btnselectpic = (Button)findViewById(R.id.button_selectpic);
        messageText  = (TextView)findViewById(R.id.messageText);
        imageview = (ImageView)findViewById(R.id.imageView_pic);

        btnselectpic.setOnClickListener(this);
        uploadButton.setOnClickListener(this);
        upLoadServerUri = "http://localhost/UploadFile.php";
        ImageView img= new ImageView(this);

    }


    @Override
    public void onClick(View arg0) {
        if(arg0==btnselectpic)
        {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
        }
        else if (arg0==uploadButton) {

             dialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true);
             messageText.setText("uploading started.....");
             new Thread(new Runnable() {
                 public void run() {

                      uploadFile(imagepath);

                 }
               }).start();     
        }

    } 

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 1 && resultCode == RESULT_OK) {
            //Bitmap photo = (Bitmap) data.getData().getPath(); 

            Uri selectedImageUri = data.getData();
            imagepath = getPath(selectedImageUri);
            Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
            imageview.setImageBitmap(bitmap);
            messageText.setText("Uploading file path:" +imagepath);

        }
    }
         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);
            }

    public int uploadFile(String sourceFileUri) {


          String fileName = sourceFileUri;

          HttpURLConnection conn = null;
          DataOutputStream dos = null;  
          String lineEnd = "\r\n";
          String twoHyphens = "--";
          String boundary = "*****";
          int bytesRead, bytesAvailable, bufferSize;
          byte[] buffer;
          int maxBufferSize = 1 * 1024 * 1024; 
          File sourceFile = new File(sourceFileUri); 

          if (!sourceFile.isFile()) {

               dialog.dismiss(); 

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

               runOnUiThread(new Runnable() {
                   public void run() {
                       messageText.setText("Source File not exist :"+ imagepath);
                   }
               }); 

               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", fileName); 

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

                   dos.writeBytes(twoHyphens + boundary + lineEnd); 
                   dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                                             + fileName + "\"" + 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();
                   String serverResponseMessage = conn.getResponseMessage();

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

                   if(serverResponseCode == 200){

                       runOnUiThread(new Runnable() {
                            public void run() {
                                String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                      +" F:/wamp/wamp/www/uploads";
                                messageText.setText(msg);
                                Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                            }
                        });                
                   }    

                   //close the streams //
                   fileInputStream.close();
                   dos.flush();
                   dos.close();

              } catch (MalformedURLException ex) {

                  dialog.dismiss();  
                  ex.printStackTrace();

                  runOnUiThread(new Runnable() {
                      public void run() {
                          messageText.setText("MalformedURLException Exception : check script url.");
                          Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                      }
                  });

                  Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
              } catch (Exception e) {

                  dialog.dismiss();  
                  e.printStackTrace();

                  runOnUiThread(new Runnable() {
                      public void run() {
                          messageText.setText("Got Exception : see logcat ");
                          Toast.makeText(MainActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
                      }
                  });
                  Log.e("Upload file to server Exception", "Exception : "  + e.getMessage(), e);  
              }
              dialog.dismiss();       
              return serverResponseCode; 

           } // End else block 
         }


}

UploadFile.php:

<?php

    $file_path = "uploads/";

    $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
        echo "success";
    } else{
        echo "fail";
    }
 ?>

1 个答案:

答案 0 :(得分:0)

检查您的日志:您排队NullPonterException

File sourceFile = new File(sourceFileUri); // your sourceFileUri = null here,

因为您使用null agrument调用uploadFile()