我有一个Android应用程序,可以裁剪图像并将其保存到手机内部目录。然后我获取保存图像的路径名称并将其设置为imageView,因此我知道路径存在。但是当我尝试使用函数上传文件时,我得到错误NullPointerException。
以下是我声明的变量
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;
}
}
这是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
}
这个过程的工作原理是我用相机拍照或从画廊中选择它。然后我裁剪图像(我没有添加裁剪图像功能,因为我认为它不相关)。裁剪后,使用saveToInternalStorage()保存图像,该函数在onActivityResult()函数中调用。 saveToInternalStorage()返回我在uploadFile()中使用的路径目录,因此它将上传文件,但我得到了这个logCat,
logcat的
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 :(得分:2)
我正在使用此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();
}
}