我正在开发一个模块,用户可以将图像上传到服务器。为此,我必须将所选图像更改为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);
?>
答案 0 :(得分:1)
将 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文件添加到您的项目中。
答案 1 :(得分:1)
我在
检查了您的错误行JSONObject json = jsonParser.makeHttpRequest(uri,"POST",params);
但是找不到makeHttpRequest
这个方法。所以给你下面的链接,
确保获得成功响应,然后进行JSONObject
解析。
请检查Link 1 Link2 下载jar文件异步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();
}
}
});
}
答案 2 :(得分:0)
请将编码值分配给已使用的参数
encodedString = Base64.encodeToString(b,Base64.DEFAULT);
Log.e("LOOK", encodedString);
new PostImage().execute(encodedString);