我正在使用android自拍应用程序,用户将拍摄自拍图像或自拍视频并上传到服务器。
相同的代码适用于Selfie-video,但应用程序已经崩溃为自拍图像。当我点击" ok"按钮,应用会崩溃并在NullPointerException
方法中获得startActivityResult()
。据我所知,我没有从Intent获得绝对文件路径。
package com.pawras.selfi;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final int PICK_FILE_REQUEST = 1;
private static final String TAG = MainActivity.class.getSimpleName();
private String selectedFilePath;
ImageView bimage,bvideo;
ArrayList imageList;
TextView bimage_gallery,bvideo_gallery;
//ProgressDialog dialog;
PowerManager.WakeLock wakeLock;
String flag_value,thumbnail,email;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
SharedPreferences mSharedPreferences=getSharedPreferences("filter",MODE_PRIVATE);
email= mSharedPreferences.getString("isRegistered","no");
if (email.equals("no")) {
Intent intent=new Intent(MainActivity.this,SignUp.class);
startActivity(intent);
finish();
}
setContentView(R.layout.home_screen);
bimage = (ImageView) findViewById(R.id.camera);
bvideo = (ImageView) findViewById(R.id.videos);
bimage_gallery = (TextView) findViewById(R.id.img_gallery);
bvideo_gallery = (TextView) findViewById(R.id.videos_gallery);
bimage.setOnClickListener(this);
bimage_gallery.setOnClickListener(this);
bvideo_gallery.setOnClickListener(this);
bvideo.setOnClickListener(this);
imageList = new ArrayList<>();
}
@Override
public void onClick(View v) {
if (v == bimage) {
//on attachment icon click
imagecapture();
}
if (v == bvideo) {
//on attachment icon click
videocapture();
}
if (v == bimage_gallery) {
Intent intent = new Intent(MainActivity.this, Gallery_images.class);
startActivity(intent);
}
if (v == bvideo_gallery) {
Intent intent = new Intent(MainActivity.this, Gallery_videos.class);
startActivity(intent);
}
}
private void imagecapture() {
flag_value="1";
Intent intent = new Intent();
//allows to select data and return it
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
intent.putExtra("android.intent.extras.LENS_FACING_FRONT", 1);
}
else {
intent.putExtra("android.intent.extras.CAMERA_FACING", 1);
}
//starts new activity to select file and return data
startActivityForResult(intent, PICK_FILE_REQUEST);
}
private void videocapture() {
flag_value="2";
Intent intent = new Intent();
//allows to select data and return it
intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT,10);
//starts new activity to select file and return data
startActivityForResult(intent, PICK_FILE_REQUEST);
}
String selectedImagePath;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_FILE_REQUEST) {
if (data == null) {
//no data present
return;
}
final Uri selectedFileUri = data.getData();
selectedImagePath = getPath(selectedFileUri);
Toast.makeText(MainActivity.this, "file path is"+selectedImagePath, Toast.LENGTH_SHORT).show();
Log.d("absolute",selectedFilePath);
if(flag_value=="2")
{
Bitmap thumb =ThumbnailUtils.createVideoThumbnail(selectedFilePath,
MediaStore.Images.Thumbnails.MICRO_KIND);
flag_value=getStringImage(thumb);
// byte[] decodedString = Base64.decode(flag_value, Base64.DEFAULT);
// Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
} else{
flag_value="1";
}
// Log.i(TAG, "tuumb nail string:" + thumbnail);
Log.i(TAG, "Selected File Path:" + selectedFilePath);
if (selectedFilePath != null) {
// dialog = ProgressDialog.show(MainActivity.this, "", "Uploading File...", true);
new Thread(new Runnable() {
@Override
public void run() {
try {
uploadFile(selectedImagePath);
} catch (OutOfMemoryError e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "Insufficient Memory!", Toast.LENGTH_SHORT).show();
}
});
}
}
}).start();
} else {
Toast.makeText(MainActivity.this, "Please choose a File First", Toast.LENGTH_SHORT).show();
}
}
}
}
private String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null,null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public int uploadFile(final String selectedFilePath) {
int serverResponseCode = 0;
HttpURLConnection connection;
DataOutputStream dataOutputStream;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File selectedFile = new File(selectedFilePath);
String[] parts = selectedFilePath.split("/");
final String fileName = parts[parts.length - 1];
if (!selectedFile.isFile()) {
// dialog.dismiss();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "suurce file does not exist", Toast.LENGTH_SHORT).show();
}
});
return 0;
} else {
try {
FileInputStream fileInputStream = new FileInputStream(selectedFile);
URL url = new URL(Constant.SERVER_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);//Allow Inputs
connection.setDoOutput(true);//Allow Outputs
connection.setUseCaches(false);//Don't use a cached Copy
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty(
"Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("uploaded_file",selectedFilePath);
//creating new dataoutputstream
dataOutputStream = new DataOutputStream(connection.getOutputStream());
//writing bytes to data outputstream
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ selectedFilePath + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
//returns no. of bytes present in fileInputStream
bytesAvailable = fileInputStream.available();
//selecting the buffer size as minimum of available bytes or 1 MB
bufferSize = Math.min(bytesAvailable, maxBufferSize);
//setting the buffer as byte array of size of bufferSize
buffer = new byte[bufferSize];
//reads bytes from FileInputStream(from 0th index of buffer to buffersize)
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
//loop repeats till bytesRead = -1, i.e., no bytes are left to read
while (bytesRead > 0) {
try {
//write the bytes read from inputstream
dataOutputStream.write(buffer, 0, bufferSize);
} catch (OutOfMemoryError e) {
Toast.makeText(MainActivity.this, "Insufficient Memory!", Toast.LENGTH_SHORT).show();
}
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"email\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(email);
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"flag\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(flag_value);
dataOutputStream.writeBytes(lineEnd);
// get server ok responce
try{
serverResponseCode = connection.getResponseCode();
}catch (OutOfMemoryError e){
Toast.makeText(MainActivity.this, "Memory Insufficient!", Toast.LENGTH_SHORT).show();
}
String serverResponseMessage = connection.getResponseMessage();
Log.i(TAG, "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);
//response code of 200 indicates the server status OK
if (serverResponseCode == 200) {
// imageList.add(selectedFilePath);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "uploaded", Toast.LENGTH_SHORT).show();
}
});
}
//reading server echo responce
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
final String stringResponse = sb.toString();
Log.d("response string:", stringResponse);
//Toast.makeText(MainActivity.this, "response string:"+stringResponse , Toast.LENGTH_SHORT).show();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "response string:"+stringResponse , Toast.LENGTH_SHORT).show();
}
});
//closing the input and output streams
fileInputStream.close();
dataOutputStream.flush();
dataOutputStream.close();
if (wakeLock.isHeld()) {
wakeLock.release();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "File Not Found", Toast.LENGTH_SHORT).show();
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "URL Error!", Toast.LENGTH_SHORT).show();
}
});
} catch (IOException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "Cannot Read/Write File", Toast.LENGTH_SHORT).show();
}
});
}
//dialog.dismiss();
return serverResponseCode;
}
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
}