2015-07-05 3 views
1

Привет ребята из последних 8 дней я искал решение этой ошибкизагрузка изображений отлично работает на эмуляторе, но не работает, когда я использую его на моем телефоне

Позвольте мне объяснить проблему первого

Я создаю приложение, в котором пользователь позволены чтобы загрузить их изображение

до сих пор я проверял все мой код на эмуляторе все работает отлично их

, но когда я установил его на мой мобильный телефон по какой-то причине изображение загружать не похоже на работу

логика которой я использую в следующем коде

public void loadImagefromGallery(View view) { 
    // Create intent to Open Image applications like Gallery, Google Photos 
    Intent galleryIntent = new Intent(Intent.ACTION_PICK, 
      android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
    // Start the Intent 
    startActivityForResult(galleryIntent, RESULT_LOAD_IMG); 


} 


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

    try { 
     // When an Image is picked 
     if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK 
       && null != data) { 
      // Get the Image from data 

      Uri selectedImage = data.getData(); 
      String[] filePathColumn = {MediaStore.Images.Media.DATA}; 

      // Get the cursor 
      Cursor cursor = getContentResolver().query(selectedImage, 
        filePathColumn, null, null, null); 
      // Move to first row 
      cursor.moveToFirst(); 

      int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
      imgDecodableString = cursor.getString(columnIndex); 

      cursor.close(); 

      String fileNameSegments[] = imgDecodableString.split("/"); 
      fileName = fileNameSegments[fileNameSegments.length - 1]; 
      // Put file name in Async Http Post Param which will used in Php web app 
      params.put("filename", fileName); 
      // Set the Image in ImageView after decoding the String 


     } else { 
      Toast.makeText(this, "You haven't picked Image", 
        Toast.LENGTH_LONG).show(); 
     } 
    } catch (Exception e) { 
     Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG) 
       .show(); 

    } 
    uploadImage(); 
} 

public void uploadImage() { 
    // When Image is selected from Gallery 
    if (imgDecodableString != null && !imgDecodableString.isEmpty()) { 
     prgDialog = ProgressDialog.show(this, "", "Loading..."); 
     // Convert image to String using Base64 
     encodeImagetoString(); 
     // When Image is not selected from Gallery 
    } else { 
     Toast.makeText(
       getApplicationContext(), 
       "You must select image from gallery before you try to upload", 
       Toast.LENGTH_LONG).show(); 
    } 
} 

// AsyncTask - To convert Image to String 
public void encodeImagetoString() { 
    new AsyncTask<Void, Void, String>() { 

     protected void onPreExecute() { 

     } 



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

      BitmapFactory.Options options = null; 
      options = new BitmapFactory.Options(); 
      options.inSampleSize = 3; 
      bitmap = BitmapFactory.decodeFile(imgDecodableString, 
        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); 
      return ""; 
     } 

     @Override 
     protected void onPostExecute(String msg) { 

      // Put converted Image string into Async Http Post param 
      params.put("image", encodedString); 
      // Trigger Image upload 
      triggerImageUpload(); 
     } 
    }.execute(null, null, null); 
} 

public void triggerImageUpload() { 
    makeHTTPCall(); 
} 

// Make Http call to upload Image to Php server 
public void makeHTTPCall() { 

    AsyncHttpClient client = new AsyncHttpClient(); 
    // Don't forget to change the IP address to your LAN address. Port no as well. 
    client.post("http://example.com/upload_image.php", 
      params, new AsyncHttpResponseHandler() { 
       // When the response returned by REST has Http 
       // response code '200' 
       @Override 
       public void onSuccess(String response) { 
        // Hide Progress Dialog 
         prgDialog.dismiss(); 
        String str= response.toString(); 
        pp.setText(str); 


        Toast.makeText(getApplicationContext(), response, 
          Toast.LENGTH_LONG).show(); 
       } 

       // When the response returned by REST has Http 
       // response code other than '200' such as '404', 
       // '500' or '403' etc 
       @Override 
       public void onFailure(int statusCode, Throwable error, 
             String content) { 
        // Hide Progress Dialog 

        // When Http response code is '404' 
        if (statusCode == 404) { 
         Toast.makeText(getApplicationContext(), 
           "Requested resource not found", 
           Toast.LENGTH_LONG).show(); 
        } 
        // When Http response code is '500' 
        else if (statusCode == 500) { 
         Toast.makeText(getApplicationContext(), 
           "Something went wrong at server end", 
           Toast.LENGTH_LONG).show(); 
        } 
        // When Http response code other than 404, 500 
        else { 
         Toast.makeText(
           getApplicationContext(), 
           "Error Occured \n Most Common Error: \n1. Device not connected to Internet\n2. Web App is not deployed in App server\n3. App server is not running\n HTTP Status code : " 
             + statusCode, Toast.LENGTH_LONG) 
           .show(); 
        } 
       } 
      }); 

}

И кроме того их нет ошибки в LogCat , если вы, ребята, можете помочь мне с эта проблема, я был бы очень благодарен

и вы можете также указать причину почему это происходит, что приложение отлично работает на эмуляторе, а не на мобильном телефоне

UPDATE

забыл добавить мой PHP код

<?php 

    // Get image string posted from Android App 
    $base=$_REQUEST['image']; 
    // Get file name posted from Android App 
    $filename = $_REQUEST['filename']; 
    $filename = time()."_".$filename; 
    // Decode Image 
    $binary=base64_decode($base); 
    header('Content-Type: bitmap; charset=utf-8'); 
    // Images will be saved under 'www/imgupload/uplodedimages' folder 
    $file = fopen('uploads/'.$filename, 'wb'); 
    // Create File 
    fwrite($file, $binary); 
    fclose($file); 
    function get_file_extension($file_name) { 
    return substr(strrchr($file_name,'.'),1); 
} 
    echo 'my web address/uploads/'.$filename; 
?> 
+0

- это локальный хост, который вы используете в качестве сервера? –

+0

@AhmadAlsanie Нет на самом деле его хостинг Hostinger.com –

+0

часть моего веб-адреса www.example.com/uploads/. $ Filename –

ответ

0

Ничего я нашел ответ

я только что изменил этот

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

      BitmapFactory.Options options = null; 
      options = new BitmapFactory.Options(); 
      options.inSampleSize = 3; 
      bitmap = BitmapFactory.decodeFile(imgDecodableString, 
        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); 
      return ""; 
     } 

к этому

public void encodeImagetoString() { 
     new AsyncTask<Void, Void, String>() { 

      protected void onPreExecute() { 

      }; 

         @Override 
      protected String doInBackground(Void... params) { 
       BitmapFactory.Options options = null; 
       options = new BitmapFactory.Options(); 
       options.inJustDecodeBounds = true; 
       options.inSampleSize = 3; 
       bitmap = BitmapFactory.decodeFile(imgPath, 
         options); 
       final int REQUIRED_SIZE = 1024; 
       int width_tmp = options.outWidth, height_tmp = options.outHeight; 

       int scale = 4; 
       while (true) { 
        if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) 
         break; 
        width_tmp /= 2; 
        height_tmp /= 2; 
        scale *= 2; 
       } 

       BitmapFactory.Options o2 = new BitmapFactory.Options(); 
       o2.inSampleSize = scale; 
       bitmap = BitmapFactory.decodeFile(imgPath, o2); 
       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); 
       return ""; 
      } 

Но я все еще не могу понять, что происходит неправильно, почему он загружается на эмулятор, но не на мобильном телефоне, если у кого-то есть ответ на него. Пожалуйста, дайте мне знать.

Смежные вопросы