dqxm14187 2013-12-19 00:40
浏览 63
已采纳

Android在将图像上传到Web服务器时抛出零点异常

I am calling uploadFile on item clicked.

gridView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {
            ImageItem item = (ImageItem) parent.getAdapter().getItem(position);
            Toast.makeText(MainActivity.this,item.getAddress(),
                    Toast.LENGTH_LONG).show();
            uploadFile(item.getAddress());
        }
    });

Here is the method UploadFile which does uploading

public void uploadFile(String sourceFileUri) {


          String fileName = sourceFileUri;
        ProgressDialog dialog = null;
            HttpURLConnection conn = null;
            DataOutputStream dos = null;  
            String lineEnd = "
";
            String twoHyphens = "--";
            String boundary = "*****";
            String upLoadServerUri ="http://192.168.79.1:8081/UploadToServer.php";
            int serverResponseCode = 0;
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024; 
            File sourceFile = new File(sourceFileUri); 
            Log.i("uploadFile", sourceFileUri);
            if (!sourceFile.isFile()) {
                Log.i("uploadFile", "FileCheck");
            }
            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.

 See uploaded file here : 

"
                                          +" 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();   
            }
           }

PHP code is

<?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";
    }
 ?>

I am getting a nullPointerException. I did not a way to figure this out, here are LogCat logs

    12-19 05:59:32.582: E/AndroidRuntime(1896): java.lang.NullPointerException
12-19 05:59:32.582: E/AndroidRuntime(1896):     at com.javatechig.gridview.MainActivity.uploadFile(MainActivity.java:217)
12-19 05:59:32.582: E/AndroidRuntime(1896):     at com.javatechig.gridview.MainActivity$1.onItemClick(MainActivity.java:51)
    12-19 05:59:32.582: E/AndroidRuntime(1896):     at android.widget.AdapterView.performItemClick(AdapterView.java:301)
    12-19 05:59:32.582: E/AndroidRuntime(1896):     at android.widget.AbsListView.performItemClick(AbsListView.java:1584)
    12-19 05:59:32.582: E/AndroidRuntime(1896):     at android.widget.AbsListView$PerformClick.run(AbsListView.java:3399)
    12-19 05:59:32.582: E/AndroidRuntime(1896):     at android.widget.AbsListView$1.run(AbsListView.java:4653)
    12-19 05:59:32.582: E/AndroidRuntime(1896):     at android.os.Handler.handleCallback(Handler.java:725)
    12-19 05:59:32.582: E/AndroidRuntime(1896):     at android.os.Handler.dispatchMessage(Handler.java:92)
    12-19 05:59:32.582: E/AndroidRuntime(1896):     at android.os.Looper.loop(Looper.java:175)
    12-19 05:59:32.582: E/AndroidRuntime(1896):     at android.app.ActivityThread.main(ActivityThread.java:5279)
    12-19 05:59:32.582: E/AndroidRuntime(1896):     at java.lang.reflect.Method.invokeNative(Native Method)
    12-19 05:59:32.582: E/AndroidRuntime(1896):     at java.lang.reflect.Method.invoke(Method.java:511)
    12-19 05:59:32.582: E/AndroidRuntime(1896):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
    12-19 05:59:32.582: E/AndroidRuntime(1896):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
    12-19 05:59:32.582: E/AndroidRuntime(1896):     at dalvik.system.NativeStart.main(Native Method)

Thanks in advance!!

  • 写回答

1条回答 默认 最新

  • duanba4942 2013-12-19 00:50
    关注

    You get a NPE because of this line

    ProgressDialog dialog = null;
    

    it seems you never initialize dialog so it throws a NPE when you call dismiss() on it. You need to initialize it before calling a method on it. I guess you probably want to inside runOnUiThread() or somewhere else on the UI Thread.

    Also, I don't see how you are running any code on a background Thread so there wouldn't be a need for the runOnUiThread()s that you have. However, you should be running the network code on a background Thread.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持