2014-11-17 5 views
1

이미지를 자르고 휴대폰 내부 디렉토리에 저장하는 Android 앱이 있습니다. 그런 다음 저장된 이미지의 경로 이름을 가져 와서 imageView로 설정하면 경로가 있다는 것을 알 수 있습니다. 그러나 함수를 사용하여 파일을 업로드하려고하면 NullPointerException 오류가 발생합니다. 여기 PHP 서버로 파일을 업로드 할 때 NullPointer 수신 - Android

내가

다음
 private Uri mImageCaptureUri; 

    private static final int PICK_FROM_CAMERA = 1; 
    private static final int CROP_FROM_CAMERA = 2; 
    private static final int PICK_FROM_FILE = 3; 

    ImageView imageView1; 
    RoundImage roundedImage; 
    Bitmap bitmap; 
    ProgressDialog prgDialog; 
    String encodedString; 
    RequestParams params = new RequestParams(); 
    String imgPath, fileName; 
    Bitmap bitmap2; 
    TextView tv; 
    String uploadFilePath; 
    String uploadFileName; 
    private static int RESULT_LOAD_IMG = 1; 

    //UPLOAD STUFF 
    int serverResponseCode = 0; 
    ProgressDialog dialog = null; 

    String upLoadServerUri = null; 

내에서 onCreate()

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     imageView1 = (ImageView) findViewById(R.id.imageView1); 
     tv = (TextView) findViewById(R.id.tv); 
     //PHP UPLOAD PATH 
     upLoadServerUri = "http://www.waxjar.com/app_upload.php"; 



     //Camera Stuff 

     final String [] items   = new String [] {"Take from camera", "Select from gallery"};     
     ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items); 
     AlertDialog.Builder builder  = new AlertDialog.Builder(this); 

     builder.setTitle("Select Image"); 
     builder.setAdapter(adapter, new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int item) { //pick from camera 
       if (item == 0) { 
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 

        mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), 
             "tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg")); 

        intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri); 

        try { 
         intent.putExtra("return-data", true); 

         startActivityForResult(intent, PICK_FROM_CAMERA); 
        } catch (ActivityNotFoundException e) { 
         e.printStackTrace(); 
        } 
       } else { //pick from file 
        Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
        startActivityForResult(i, PICK_FROM_FILE); 

       } 
      } 
     }); 

     final AlertDialog dialog = builder.create(); 

     Button button = (Button) findViewById(R.id.btn_crop); 

     button.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       dialog.show(); 
      } 
     }); 

     //END CAMERA STUFF 

     }// End OnCreate 

이 내 onActivityResult를()

@Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     if (resultCode != RESULT_OK) return; 

     switch (requestCode) { 
      case PICK_FROM_CAMERA: 
       doCrop(); 

       break; 

      case PICK_FROM_FILE: 
       mImageCaptureUri = data.getData(); 

       doCrop(); 

       break;   

      case CROP_FROM_CAMERA:   
       Bundle extras = data.getExtras(); 

       if (extras != null) {    
        Bitmap photo = extras.getParcelable("data"); 


       final String croppedfilepath = saveToInternalSorage(photo).toString(); 
       loadImageFromStorage(croppedfilepath); 

       // UPLOAD STUFF 
       new Thread(new Runnable() { 
        public void run() { 
          runOnUiThread(new Runnable() { 
           public void run() { 
            tv.setText("uploading started....."); 
           } 
          });      

          uploadFile(croppedfilepath); 

        } 
        }).start(); 

       } 

       File f = new File(mImageCaptureUri.getPath());    

       if (f.exists()) f.delete(); 

       break; 

     } 
    } 
,691입니다 선언하는 변수이다 여기

363,210이 saveToInternalStorage (를)

private String saveToInternalSorage(Bitmap bitmapImage){ 
     ContextWrapper cw = new ContextWrapper(getApplicationContext()); 
     // path to /data/data/yourapp/app_data/imageDir 
     File directory = cw.getDir("imageDir", Context.MODE_PRIVATE); 
     // Create imageDir 
     File mypath=new File(directory,"profile.png"); 

     FileOutputStream fos = null; 
     try {   

      fos = new FileOutputStream(mypath); 

     // Use the compress method on the BitMap object to write image to the OutputStream 
      bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos); 
      fos.close(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return directory.getAbsolutePath(); 
    } 

이 loadImageFromStorage (를)

private void loadImageFromStorage(String path) 
    { 

     try { 
      File f=new File(path, "profile.png"); 
      Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f)); 
       ImageView img=(ImageView)findViewById(R.id.imageView1); 
      img.setImageBitmap(b); 
     } 
     catch (FileNotFoundException e) 
     { 
      e.printStackTrace(); 
     } 

    } 

이 UploadFile로 임() 프로세스가 작동하는 방법

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 :" 
            +uploadFilePath + "" + uploadFileName); 

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

       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="fileName"; 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" 
               +" http://www.waxjar.com/uploadedimages/" 
               +uploadFileName; 

           tv.setText(msg); 
           Toast.makeText(Main.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() { 
          tv.setText("MalformedURLException Exception : check script url."); 
          Toast.makeText(Main.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() { 
          tv.setText("Got Exception : see logcat "); 
          Toast.makeText(Main.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 
     } 

I는 내 카메라로 사진 찍기 갤러리에서 선택하십시오. 그런 다음 이미지를 자릅니다 (관련이 있다고 생각하지 않아 자르기 이미지 기능을 추가하지 않았습니다). 이미지가 잘린 후 onActivityResult() 함수에서 호출 된 saveToInternalStorage()를 사용하여 이미지가 저장됩니다. saveToInternalStorage는() 나는 다음을 UploadFile (에 사용) 그래서 파일을 업로드하지만이 로그 캣를 얻는 경로 디렉토리,

로그 캣

11-17 01:53:26.770: E/AndroidRuntime(26052): FATAL EXCEPTION: Thread-53576 
11-17 01:53:26.770: E/AndroidRuntime(26052): Process: com.goboapp, PID: 26052 
11-17 01:53:26.770: E/AndroidRuntime(26052): java.lang.NullPointerException 
11-17 01:53:26.770: E/AndroidRuntime(26052): at com.goboapp.Main.uploadFile(Main.java:368) 
11-17 01:53:26.770: E/AndroidRuntime(26052): at com.goboapp.Main$3.run(Main.java:222) 
11-17 01:53:26.770: E/AndroidRuntime(26052): at java.lang.Thread.run(Thread.java:841) 

왜 내가 그 오류가 무엇입니까를 반환?

+0

당신은 여기 내 대답을 참조 할 수 있습니다 http://stackoverflow.com/questions/20322528/uploading-images-to-server-android/20322851#20322851 그것은 당신의 경로 이름이 올바른지 꽤 똑바로 앞으로 –

+0

입니다 수표 여부 아니. –

+0

이미지를 업로드 할 때 동일한 경로를 사용하여 이미지를 imageView로 설정하므로 경로가 null이 될 수 없습니다./ –

답변

1

이 AsyncTask를 사용하여 이미지를 업로드합니다.

public class SendFile extends AsyncTask<String, Integer, Integer> { 

    private Context conT; 
    private ProgressDialog dialog; 
    private String SendUrl = ""; 
    private String SendFile = ""; 
    private String Bilgiler = ""; 
    private String result; 
    public File file; 
    private int ProgressGoster=0; 

    SendFile(Context activity, String url, String dosya, String Deger,int boyut,int gosteriyorum) { 
     conT = activity; 
     dialog = new ProgressDialog(conT); 
     SendUrl = url; 
     SendFile = dosya; 
     Bilgiler = Deger; 
     ProgressGoster = gosteriyorum; 
    } 

    @Override 
    protected void onPreExecute() { 
     file = new File(SendFile); 
     if(ProgressGoster==1){ 
      dialog.setMessage("Faks Gönderiliyor. Lütfen Bekleyiniz.."); 
      dialog.setCancelable(false); 
      dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
      dialog.setMax((int) file.length()); 
      dialog.show(); 
     } 
    } 

    @Override 
    protected Integer doInBackground(String... params) { 
     HttpURLConnection connection = null; 
     DataOutputStream outputStream = null; 
     InputStream inputStream = null; 
     String twoHyphens = "--"; 
     String boundary = "*****" 
       + Long.toString(System.currentTimeMillis()) + "*****"; 
     String lineEnd = "\r\n"; 

     int bytesRead, bytesAvailable, bufferSize; 
     byte[] buffer; 
     int maxBufferSize = 1 * 512; 

     String[] q = SendFile.split("/"); 
     int idx = q.length - 1; 
     try { 

      FileInputStream fileInputStream = new FileInputStream(file); 

      URL url = new URL(SendUrl); 
      connection = (HttpURLConnection) url.openConnection(); 
      connection.setDoInput(true); 
      connection.setDoOutput(true); 
      connection.setUseCaches(false); 

      connection.setRequestMethod("POST"); 
      connection.setRequestProperty("Connection", "Keep-Alive"); 
      connection.setRequestProperty("User-Agent", 
        "Android Multipart HTTP Client 1.0"); 
      connection.setRequestProperty("Content-Type", 
        "multipart/form-data; boundary=" + boundary); 

      outputStream = new DataOutputStream(
        connection.getOutputStream()); 
      outputStream.writeBytes(twoHyphens + boundary + lineEnd); 
      outputStream 
        .writeBytes("Content-Disposition: form-data; name=dosya; filename=\"" 
          + q[idx] + "\"" + lineEnd); 
      outputStream.writeBytes("Content-Type: image/jpg" + lineEnd); 
      outputStream.writeBytes("Content-Transfer-Encoding: binary" 
        + lineEnd); 
      outputStream.writeBytes(lineEnd); 

      bytesAvailable = fileInputStream.available(); 
      bufferSize = Math.min(bytesAvailable, maxBufferSize); 
      buffer = new byte[bufferSize]; 

      bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
      int boyut = 0; 
      while (bytesRead > 0) { 
       boyut += bytesRead; 
       outputStream.write(buffer, 0, bufferSize); 
       bytesAvailable = fileInputStream.available(); 
       bufferSize = Math.min(bytesAvailable, maxBufferSize); 
       bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
       if(ProgressGoster==1){ 
        dialog.setProgress(boyut); 
       } 
      } 

      outputStream.writeBytes(lineEnd); 

      String[] posts = Bilgiler.split("&"); 
      int max = posts.length; 
      for (int i = 0; i < max; i++) { 
       outputStream.writeBytes(twoHyphens + boundary + lineEnd); 
       String[] kv = posts[i].split("="); 
       outputStream 
         .writeBytes("Content-Disposition: form-data; name=\"" 
           + kv[0] + "\"" + lineEnd); 
       outputStream.writeBytes("Content-Type: text/plain" 
         + lineEnd); 
       outputStream.writeBytes(lineEnd); 
       outputStream.writeBytes(kv[1]); 
       outputStream.writeBytes(lineEnd); 
      } 

      outputStream.writeBytes(twoHyphens + boundary + twoHyphens 
        + lineEnd); 
      inputStream = connection.getInputStream(); 
      result = this.convertStreamToString(inputStream); 
      fileInputStream.close(); 
      inputStream.close(); 
      outputStream.flush(); 
      outputStream.close(); 
     } catch (Exception e) { 

     } 

     return null; 
    } 

    @Override 
    protected void onProgressUpdate(Integer... progress) { 
     dialog.setProgress(progress[0]); 
    } 

    @Override 
    protected void onPostExecute(Integer result1) { 
     if(ProgressGoster==1){ 
      dialog.dismiss(); 
     } 
    }; 

    private String convertStreamToString(InputStream is) { 
     BufferedReader reader = new BufferedReader(
       new InputStreamReader(is)); 
     StringBuilder sb = new StringBuilder(); 

     String line = null; 
     try { 
      while ((line = reader.readLine()) != null) { 
       sb.append(line); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       is.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     return sb.toString(); 
    } 

} 
+0

호출 할 때 함수에 무엇을 넣을까요? 예제 SendFile (여기에는 어떤 것이 있습니까?) –

+0

ProgressGoster = 1; Dosya = ""; // -> 이것은 이미지 경로입니다. upLoadServerUri = ""; // -> 업로드 url FileSize = ""- 업로드하는 동안 진행률 표시 줄을 사용하려는 경우 이미지 파일 크기. String FormData = "username ="+ Session.getUsername() + "& password ="+ Session.getPassword(); // - 사용자 인증을위한 양식 데이터 SendFile gonder = new SendFile (this, upLoadServerUri, Dosya, FormData, FileSize, ProgressGoster); \t \t \t gonder.execute();' –

관련 문제