在我的应用中,用户可以按相机或图库上传图像。 应用程式在Nox Player(4.4.2)中执行,没有错误。 但是如果我是通过模拟器android studio(Nexus 6 API 23 Android 6.0)运行应用程序,则当上传图片崩溃时,应用程序会崩溃。 还有应用程序捕获使用相机和从用户读取,写入存储的权限。
android监视器中的错误:
10-03 01:00:46.258 3549-3549/com.google.android.apps.photos E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.google.android.apps.photos, PID: 3549
java.lang.RuntimeException: Unable to resume activity {com.google.android.apps.photos/com.google.android.apps.photos.photoeditor.intents.EditActivity}: java.lang.UnsupportedOperationException: No 'output' extra specified and can not save to specified inputUri: content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F37/ACTUAL/1435618852
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3103)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3134)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1388)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.UnsupportedOperationException: No 'output' extra specified and can not save to specified inputUri: content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F37/ACTUAL/1435618852
at com.google.android.apps.photos.photoeditor.intents.EditActivity.a(PG:11301)
at ggt.a(PG:87)
at lhy.a(PG:219)
at lhy.O_(PG:189)
at ngn.a(PG:188)
at ngk.a(PG:92)
at ngk.l(PG:184)
at nhi.onResume(PG:64)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1258)
at android.app.Activity.performResume(Activity.java:6312)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3092)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3134)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1388)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
build.gradle代码:
android {
compileSdkVersion 27
buildToolsVersion "27.0.3"
defaultConfig {
applicationId "ir.mosayebtorabi.sapp"
minSdkVersion 17
targetSdkVersion 27
versionCode 1
versionName "1.0"
multiDexEnabled true
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
}
活动代码:
package ir.mosayebtorabi.sapp.Register_Pack;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import de.hdodenhof.circleimageview.CircleImageView;
import ir.mosayebtorabi.sapp.Global_Class.Global;
import ir.mosayebtorabi.sapp.Global_Class.Request_Permissions;
import ir.mosayebtorabi.sapp.R;
import ir.mosayebtorabi.sapp.Register_Pack.Load_Last_Project.List_Of_Last_Project;
import ir.mosayebtorabi.sapp.Global_Class.Roozh;
public class Get_Info_New_Admin extends AppCompatActivity {
Request_Permissions Request_Permissions;
static Get_Info_New_Admin Get_Info_New_Admin;
Add_New_ProjectControl Add_New_ProjectControl;
Get_Last_CompanyCode Get_Last_CompanyCode;
ir.mosayebtorabi.sapp.Register_Pack.Delete_Pic_From_Server Delete_Pic_From_Server;
CircleImageView fab;
ImageView imageView;
Button buttonCamera, buttonGallery ;
File file;
Uri uri;
Intent CamIntent, GalIntent, CropIntent ;
public static final int RequestPermissionCode = 1 ;
DisplayMetrics displayMetrics ;
int width, height;
ProgressBar progressBar;
ProgressBar prog1;
Button uploadButton;
//upload
int serverResponseCode = 0;
final String uploadFilePath = Environment.getExternalStorageDirectory().getPath() +"/Sapp/.Profile/";
final String uploadFileName = Global.Send_telephone_TelePhone + ".jpg";
String upLoadServerUri = null;
String Picture1="";
private Bitmap bitmap;
//upload
Intent i = new Intent(
Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get__info__new__admin);
Get_Info_New_Admin = this;
final TextView name=(TextView)findViewById(R.id.name);
final TextView family=(TextView)findViewById(R.id.family);
final TextView companyname=(TextView)findViewById(R.id.companyname);
final TextView projectname=(TextView)findViewById(R.id.projectname);
final Button send=(Button)findViewById(R.id.send);
final Button back=(Button)findViewById(R.id.back);
fab=(CircleImageView)findViewById(R.id.fab);
progressBar =(ProgressBar)findViewById(R.id.progressBar33);
prog1 =(ProgressBar)findViewById(R.id.prog1);
upLoadServerUri = "http://"+ Global.url_connection+"/Sapp/UploadToServer.php";
File file2= new File(android.os.Environment.getExternalStorageDirectory()+ "/Sapp/.Profile/"+
Global.Send_telephone_TelePhone + ".jpg");
if(file2.exists())
{
Bitmap bmp = BitmapFactory.decodeFile(String.valueOf(file2));
fab.setImageBitmap(bmp);
}else{
if (!Global.C0_adapter_ProfilePic.equals("")) {
Glide.with(Get_Info_New_Admin.this).load("http://"+ Global.url_connection+"/Sapp/profile_pic/" +
Global.C0_adapter_ProfilePic).into(fab);
}else{
Glide.with(Get_Info_New_Admin.this).load(R.drawable.blankimageforshoe).into(fab);
}
}
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectImage();
}
});
if (!Global.C0_apiservis_Name.equals("")){
name.setText(Global.C0_apiservis_Name);
family.setText(Global.C0_apiservis_Family);
name.setEnabled(false);
family.setEnabled(false);
}
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent aaaaa=new Intent(Get_Info_New_Admin.this,List_Of_Last_Project.class);
Get_Info_New_Admin.this.startActivity(aaaaa);
((Activity) Get_Info_New_Admin.this).finish();
}
});
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String list="";
if (name.getText().toString().equals("")){
name.setError("نام خود را وارد کنید");
name.requestFocus();
list="notok";
}
if (family.getText().toString().equals("") && !list.equals("notok")){
family.setError("نام خانوادگی خود را وارد کنید");
family.requestFocus();
list="notok";
}
if (companyname.getText().toString().equals("") && !list.equals("notok")){
companyname.setError("نام شرکت را وارد کنید");
companyname.requestFocus();
list="notok";
}
if (projectname.getText().toString().equals("") && !list.equals("notok")){
projectname.setError("موضوع فعالیت شرکت را وارد کنید");
projectname.requestFocus();
list="notok";
}
if (!list.equals("notok")){
//get last companycode
name.setEnabled(false);
family.setEnabled(false);
companyname.setEnabled(false);
projectname.setEnabled(false);
prog1.setVisibility(View.VISIBLE);
int CompanyCode11=Integer.parseInt(Global.Get_Last_CompanyCode_CompanyCode)+1;
String CompanyCode1=String.valueOf(CompanyCode11);
String companyname1=companyname.getText().toString();
String projectname1=projectname.getText().toString();
String Designation1="مسئول کنترل پروژه";
String name1=name.getText().toString();
String family1=family.getText().toString();
String TelePhone1=Global.Send_telephone_TelePhone;
String StatueUpLevel1="3";
Roozh jCal = new Roozh();
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int mo = calendar.get(Calendar.MONTH);
mo++;
int da = calendar.get(Calendar.DAY_OF_MONTH);
jCal.GregorianToPersian(year, mo, da);
String Data_Accept1=jCal.toString();
String Staute1="3";
String Access1="3";
String Picture1=Global.Send_telephone_TelePhone+".jpg";
String Invited1=name.getText().toString() + " " + family.getText().toString();
Add_New_ProjectControl=new Add_New_ProjectControl(Get_Info_New_Admin.this);
Add_New_ProjectControl.Add_New_ProjectControl(CompanyCode1,companyname1,projectname1,Designation1,name1,family1
,TelePhone1,StatueUpLevel1,Data_Accept1,Staute1,Access1,Picture1,Invited1,"online");
}
}
});
}
public void selectImage() {
final CharSequence[] options = { "دوربین", "انتخاب عکس از گالری","حذف عکس","انصراف" };
AlertDialog.Builder builder = new AlertDialog.Builder(Get_Info_New_Admin.this);
builder.setTitle("انتخاب تصویر پروفایل");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("دوربین"))
{
ClickImageFromCamera() ;
}
else if (options[item].equals("انتخاب عکس از گالری"))
{
GetImageFromGallery();
}
else if (options[item].equals("حذف عکس")) {
Drawable myDrawable = getResources().getDrawable(R.drawable.blankimageforshoe);
fab.setImageDrawable(myDrawable);
Picture1="";
Global.Get_Info_New_Admin_SelectImage="";
//deleto from sdcard
File file= new File(android.os.Environment.getExternalStorageDirectory()+ "/Sapp/.Profile/"+
Global.Send_telephone_TelePhone + ".jpg");
if(file.exists())
{
file.delete();
}
//
ProgressBar progressBar33=(ProgressBar)findViewById(R.id.progressBar33);
progressBar33.setVisibility(View.VISIBLE);
Global.What_Page="Get_Info_New_Admin";
Delete_Pic_From_Server=new Delete_Pic_From_Server(Get_Info_New_Admin.this);
Delete_Pic_From_Server.Delete_Pic_From_Server( Global.Send_telephone_TelePhone,Global.Send_telephone_TelePhone + ".jpg");
}
else if (options[item].equals("انصراف")) {
dialog.dismiss();
}
}
});
builder.show();
}
//SAVE IMAGE
private void save() {
FileOutputStream out = null;
Bitmap bitmap = ((BitmapDrawable) fab.getDrawable()).getBitmap();
try {
out = new FileOutputStream(getFilename());
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Get_Info_New_Admin.this, "در حال بارگزاری", Toast.LENGTH_SHORT).show();
}
});
uploadFile(uploadFilePath + "" + uploadFileName);
}
}).start();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "خطای نامشخص", Toast.LENGTH_SHORT).show();
}
}
private String getFilename() {
File file = new File(Environment.getExternalStorageDirectory()+"/Sapp", ".Profile");
if (!file.exists()) {
file.mkdirs();
}
String uriSting = (file.getAbsolutePath() + "/" + Global.Send_telephone_TelePhone + ".jpg");
return uriSting;
}
//SAVE IMAGE
public void ClickImageFromCamera() {
CamIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
file = new File(Environment.getExternalStorageDirectory(),
"file" + String.valueOf(System.currentTimeMillis()) + ".jpg");
uri = Uri.fromFile(file);
CamIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, uri);
CamIntent.putExtra("return-data", true);
startActivityForResult(CamIntent, 0);
}
public void GetImageFromGallery(){
GalIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(GalIntent, "Select Image From Gallery"), 2);
}
public void ImageCropFunction() {
// Image Crop Code
try {
CropIntent = new Intent("com.android.camera.action.CROP");
CropIntent.setDataAndType(uri, "image/*");
CropIntent.putExtra("crop", "true");
CropIntent.putExtra("outputX", 1600);
CropIntent.putExtra("outputY", 1600);
CropIntent.putExtra("aspectX", 10);
CropIntent.putExtra("aspectY", 10);
CropIntent.putExtra("scaleUpIfNeeded", true);
CropIntent.putExtra("return-data", true);
startActivityForResult(CropIntent, 1);
} catch (ActivityNotFoundException e) {
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0 && resultCode == RESULT_OK) {
ImageCropFunction();
}
else if (requestCode == 2) {
if (data != null) {
uri = data.getData();
ImageCropFunction();
}
}
else if (requestCode == 1) {
if (data != null) {
Bundle bundle = data.getExtras();
try{
Bitmap bitmap = bundle.getParcelable("data");
fab.setImageBitmap(bitmap);
save();
progressBar.setVisibility(View.VISIBLE);
}catch (Exception e){
}
}
}
}
public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {
switch (RC) {
case RequestPermissionCode:
if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(Get_Info_New_Admin.this,"Permission Granted, Now your application can access CAMERA.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(Get_Info_New_Admin.this,"Permission Canceled, Now your application cannot access CAMERA.", Toast.LENGTH_LONG).show();
}
break;
}
}
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 =30000 * 30000;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File not exist :"
+uploadFilePath + "" + uploadFileName);
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Get_Info_New_Admin.this, "خطای دستیابی به فابل", Toast.LENGTH_SHORT).show();
}
});
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=\"uploaded_file\";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() {
Toast.makeText(Get_Info_New_Admin.this, "آپلود فایل کامل شد.", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Get_Info_New_Admin.this, "اتصال برقرار نشد.", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Get_Info_New_Admin.this, "خطا.مجددا امتحان کنید.", Toast.LENGTH_SHORT).show();
}
});
}
return serverResponseCode;
} // End else block
}
public static Get_Info_New_Admin getInstance(){
return Get_Info_New_Admin;
}
}
PHP代码(UploadToServer):
<?php
$file_path = "profile_pic/";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
?>
答案 0 :(得分:0)
没有额外指定“输出”,并且无法保存到指定的inputUri
在您使用EditActivity
保存(或其他任何内容)的URI
中,您没有指定输出路径,这就是为什么会出现错误的原因。
例如,添加第二个参数作为output
路径,然后它将起作用。