Я работаю над модулем, в котором пользователь может загрузить изображение на сервер. Для этого я должен изменить выбранный образ на Base64. После преобразования я должен использовать метод Json POST для загрузки изображения, но каждый раз при сбое приложения и Logcat выдают эту ошибку
Error converting result java.lang.NullPointerException: lock == null
и другая строка ошибки
Error parsing data org.json.JSONException: End of input at character 0 of
это мой код, который я пытаюсь, пожалуйста, посмотрите и позвольте мне, какую ошибку я здесь делаю.
buttonLoadPicture.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent i = new Intent( Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, RESULT_LOAD_IMAGE); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) { Uri selectedImage = data.getData(); String[] filePathColumn = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); ImageView imageView = (ImageView) findViewById(R.id.imgView); imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath)); ss = BitmapFactory.decodeFile(picturePath); Log.d("value", ss.toString()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ss.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] b = baos.toByteArray(); String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT); encodedImage = imageEncoded.toString(); Log.e("LOOK", imageEncoded); // **working proper** Log.e("encodedImage", encodedImage);// **working proper** new PostImage().execute(); } } class PostImage extends AsyncTask<String, String, String>{ @SuppressWarnings("deprecation") @Override protected String doInBackground(String... args) { // TODO Auto-generated method stub String encodedString = encodedImage.toString(); Log.d("stringgggg", encodedString);//**working proper** List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("uploaded_file", encodedString)); String uri = "http://192.168.2.166/uploadimage/upload.php"; JSONObject json = jsonParser.makeHttpRequest(uri,"POST",params); Log.d("valueeeeee", json.toString());// **Crashhhh!!!!!** return json.toString(); } }
}
это мой php-код
<?php $json["success"] = 1; $json["message"] = "YOU ARE HERE... UPLOAD.PHP"; $json['image']=$_FILES['uploaded_file']['name']; $json['tmp_name']=$_FILES['uploaded_file']['tmp_name']; echo json_encode($json); die(); //print_r($_FILES); die(); $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"; $json["success"] = 1; $json["message"] = "Successfully post save"; } else{ // echo "fail"; $json["success"] = 0; $json["message"] = "Fail post save"; } // print_r($json); // var_dump(json_encode($json)); echo json_encode($json); ?>
Я проверил вашу строку ошибок на
JSONObject json = jsonParser.makeHttpRequest(uri,"POST",params);
но не смог найти makeHttpRequest
этот Method.so, дающий вам ссылку ниже. Убедитесь, что вы получили ответ «Успех», а затем вы отправляетесь на парсинг JSONObject
.
Пожалуйста, проверьте Link 1 Link2 download jar file Асинхронный клиент Http и сделайте вызов Api как
public void makeHTTPCall() { prgDialog.setMessage("Invoking Php"); RequestParams params = new RequestParams(); params.put("key", "value"); params.put("more", "data"); AsyncHttpClient client = new AsyncHttpClient(); // Don't forget to change the IP address to your LAN address. Port no as well. client.post("http://192.168.2.5:9000/imgupload/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.hide(); 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 prgDialog.hide(); // 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(); } } }); }
Добавьте httpmime-4.3.6.jar и httpcore-4.3.3.jar в свою папку libs и добавьте в build.gradle и синхронизируйте ее, чем после этого шага;
Эта переменная Вы должны определить;
private static int RESULT_LOAD_IMAGE = 1; private static final int CAMERA_REQUEST = 1; public static final int MEDIA_TYPE_IMAGE = 1; private static final String TAG = MainActivity.class.getSimpleName(); public static final String IMAGE_DIRECTORY_NAME = "Android File Upload"; Uri mImageCaptureUri; private static final int PICK_IMAGE = 1; File sourceFile; ProgressDialog pDialog; ContentBody pic; Bitmap bitmap;
чем открыть gallary code.put в свой Onclick.
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, RESULT_LOAD_IMAGE);
это OnActivityResult
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && null != data) { Uri selectedImage = data.getData(); String[] filePathColumn = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); decodeFile(picturePath); new ImageUploadTask().execute(); }else { Toast.makeText(getApplicationContext(), "User Canceled", Toast.LENGTH_LONG).show(); } }
после этого
public void decodeFile(String filePath) { // Decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, o); // The new size we want to scale to final int REQUIRED_SIZE = 1024; // Find the correct scale value. It should be the power of 2. int width_tmp = o.outWidth, height_tmp = o.outHeight; int scale = 1; while (true) { if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) break; width_tmp /= 2; height_tmp /= 2; scale *= 2; } // Decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; bitmap = BitmapFactory.decodeFile(filePath, o2); sourceFile = new File(filePath); Bitmap bmp = BitmapFactory.decodeFile(filePath); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.JPEG, 80, bos); InputStream in = new ByteArrayInputStream(bos.toByteArray()); pic = new ByteArrayBody(bos.toByteArray(),"filename"); loadimage.setImageBitmap(bitmap); } /** * The class connects with server and uploads the photo * * */ class ImageUploadTask extends AsyncTask<Void, Void, String> { private String webAddressToPost; // private ProgressDialog dialog; private ProgressDialog dialog = new ProgressDialog(Tab1.this); @Override protected void onPreExecute() { dialog.setMessage("Uploading..."); dialog.setCancelable(false); dialog.show(); } @Override protected String doInBackground(Void... params) { try { // HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpPost httpPost = new HttpPost("YOUR URL"); MultipartEntity entity1 = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos); byte[] data = bos.toByteArray(); // String file = com.onepgr.samcom.apicalldemo2.Base64.encodeBytes(data); entity1.addPart("Parameter", pic); // entity.addPart("someOtherStringToSend", new StringBody("your string here")); httpPost.setEntity(entity1); HttpResponse response = httpclient.execute(httpPost, localContext); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String sResponse = reader.readLine(); Log.d("------>>>>",sResponse); return sResponse; } catch (Exception e) { // something went wrong. connection with the server error } return null; } @Override protected void onPostExecute(String result) { dialog.dismiss(); Toast.makeText(getApplicationContext(), "Profile picture change", Toast.LENGTH_LONG).show(); } }
Не забудьте добавить в проект проект httpmime-4.3.6.jar и httpcore-4.3.3.jar.
Назначьте закодированное значение используемым параметрам
encodedString = Base64.encodeToString(b,Base64.DEFAULT); Log.e("LOOK", encodedString); new PostImage().execute(encodedString);