簡體   English   中英

Android在將圖像上傳到Web服務器時拋出空點異常

[英]Android throwing null point exception on uploading a image to web server

我在點擊的項目上調用uploadFile。

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

這是上傳的方法UploadFile

public void uploadFile(String sourceFileUri) {


          String fileName = sourceFileUri;
        ProgressDialog dialog = null;
            HttpURLConnection conn = null;
            DataOutputStream dos = null;  
            String lineEnd = "\r\n";
            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.\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();   
            }
           }

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

我收到一個nullPointerException。 我沒有辦法弄清楚,這是LogCat日志

    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)

提前致謝!!

由於這條線,您獲得了NPE

ProgressDialog dialog = null;

似乎您從未初始化過dialog因此在您對其調用dismiss()時會引發NPE 您需要先對其進行初始化,然后再對其調用方法。 我猜您可能想要在runOnUiThread()UI Thread

另外,我看不到您如何在后台Thread上運行任何代碼,因此不需要您擁有的runOnUiThread() 但是,您應該在后台Thread上運行網絡代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM