이미지를 자르고 휴대폰 내부 디렉토리에 저장하는 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)
왜 내가 그 오류가 무엇입니까를 반환?
당신은 여기 내 대답을 참조 할 수 있습니다 http://stackoverflow.com/questions/20322528/uploading-images-to-server-android/20322851#20322851 그것은 당신의 경로 이름이 올바른지 꽤 똑바로 앞으로 –
입니다 수표 여부 아니. –
이미지를 업로드 할 때 동일한 경로를 사용하여 이미지를 imageView로 설정하므로 경로가 null이 될 수 없습니다./ –