I have an android app that crops an image and saves it to the phones internal directory. I then get the path name of the saved image and set it as an imageView so I know the path exists. But when I try to upload the file using a function I get the error NullPointerException.
Here are the variables that I declare
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;
Here is my 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
This is my 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;
}
}
Here is 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();
}
Here is 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();
}
}
Here is 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
}
How the process works is I take a picture with my camera or select it from the gallery. I then crop the image (I did not add the crop image function because I didn't think it was relevant). After it is cropped the image is saved using saveToInternalStorage() which is called in the function onActivityResult(). saveToInternalStorage() returns the path directory which I then used in the uploadFile() so it will upload the file but I get this 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)
Why am I getting that error?