当我将所有请求代码初始化时,我不必调用onActivityResult()

时间:2017-03-23 13:27:27

标签: android android-activity

在此代码中,我想从图库和相机中拍摄照片和视频 我可以从相机拍摄照片和视频,但无法从照片库中拍摄照片和视频。

package realtracker.in.cresol.realtracker.Activities;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.FacebookSdk;

import java.io.File;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import realtracker.in.cresol.realtracker.Dialog.CustomBottomSheetDialog;
import realtracker.in.cresol.realtracker.Models.Patient_Report_Details;
import realtracker.in.cresol.realtracker.Models.Patient_Report_Details_Output;
import realtracker.in.cresol.realtracker.Models.TestModel;
import realtracker.in.cresol.realtracker.Models.Upload_Video_Output;
import realtracker.in.cresol.realtracker.Models.User_Detail_Output;
import realtracker.in.cresol.realtracker.Models.User_Login_Model;
import realtracker.in.cresol.realtracker.Network.API;
import realtracker.in.cresol.realtracker.R;
import realtracker.in.cresol.realtracker.Util.GlobalMethods;
import realtracker.in.cresol.realtracker.Util.Upload_Photo_Video;
import realtracker.in.cresol.realtracker.Util.UserSessionManager;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static java.security.AccessController.getContext;

/**
 * Created by yatan on 11/02/17.
 */

public class Activity_Report  extends AppCompatActivity {
    API realtrackerApi;
    UserSessionManager sessionManager;

    boolean itemStatus;
    String itemName;
    Patient_Report_Details patient_details;
    EditText editText_details;
    EditText editText_bottum_items_details;
    String details,bottum_items_details;
    RadioGroup event_type;
    RadioButton selectedType;
    TextView patientNameReport;

    int CAMERA_REQUEST_CODE;
    int GALLERY_REQUEST_CODE;
    int CAMERA_VIDEO_REQUEST;
    int GALLERY_VIDEO_REQUEST;
    Upload_Photo_Video uploadphoto;
    Bitmap imageBitmap;
    String imageFilePath;
    String fileManagerString;
    String selectedImagePath;
    String imagePath;

    String selectedVideoPath;
    String pathtoStoredVideo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        try{
           super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_report);
       Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // Attaching the layout to the toolbar object
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        sessionManager=new UserSessionManager(this);
            realtrackerApi= GlobalMethods.getRealtrackerAPI(getApplicationContext());


        event_type=(RadioGroup)findViewById(R.id.radioEvent);
        patientNameReport=(TextView)findViewById(R.id.patientNameReport);
        patientNameReport.setText(sessionManager.getFirstName());

        editText_details=(EditText)findViewById(R.id.details);
            uploadphoto=new Upload_Photo_Video(this);

        }
        catch (Exception e){

        }
        }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.report_menu, menu);//Menu Resource, Menu
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.send:
                sessionManager=new UserSessionManager(getApplicationContext());
                details=editText_details.getText().toString();
                if(itemStatus){
                    RetroCallForAddingUserDetail();
                }else
                {
                    Toast.makeText(getApplicationContext(),"please select from sheet",Toast.LENGTH_LONG).show();
                }

                return true;

            case android.R.id.home:
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }


    //fired when click on layout of log infos
    public void showBottomSheet(View v){
        try{
        CustomBottomSheetDialog bottomSheetDialog = CustomBottomSheetDialog.getInstance();
        bottomSheetDialog.show(getSupportFragmentManager(), "Custom Bottom Sheet");
        }
        catch (Exception e){

        }
    }

    public void RetroCallForAddingUserDetail(){
        try{
        if(GlobalMethods.isConnectedToInternet(getApplicationContext(), false)) {
            int userid=sessionManager.getUserId();
            GlobalMethods.ShowDialog(this);
            String type=selectTypeOfEvent();

            if(itemName.equals("Severity of seizure")){
                patient_details=new Patient_Report_Details("title",details,bottum_items_details,"",type,"","","","",userid);
            }
            else if(itemName.equals("How long it lasted")){
                patient_details=new Patient_Report_Details("title",details,"",bottum_items_details,type,"","","","",userid);
            }
            else if(itemName.equals("Symptoms")){
                patient_details=new Patient_Report_Details("title",details,"","",type,bottum_items_details,"","","",userid);
            }
            else if(itemName.equals("What product")){
                patient_details=new Patient_Report_Details("title",details,"","",type,"",bottum_items_details,"","",userid);
            }
            else if(itemName.equals("Date the does was given")){
                patient_details=new Patient_Report_Details("title",details,"","",type,"","",bottum_items_details,"",userid);
            }
            else if(itemName.equals("How much was given")){
                patient_details=new Patient_Report_Details("title",details,"","",type,"","","",bottum_items_details,userid);
            }

            File videoFile = new File(pathtoStoredVideo);
            RequestBody videoBody = RequestBody.create(MediaType.parse("video/*"), videoFile);
            MultipartBody.Part vFile = MultipartBody.Part.createFormData("video", videoFile.getName(), videoBody);

            Call<Patient_Report_Details_Output> patient_details_outputCall= realtrackerApi.AddEvents(vFile,patient_details);

            patient_details_outputCall.enqueue(new Callback<Patient_Report_Details_Output>() {
                @Override
                public void onResponse(Call<Patient_Report_Details_Output> call, Response<Patient_Report_Details_Output> response) {
                    if(response.isSuccessful()&&response.body()!=null){
                        if(response.body().isStatus()) {

                            Toast.makeText(getApplicationContext(), "Details Added successfully", Toast.LENGTH_SHORT).show();


                            Intent i=new Intent(getApplicationContext(),Activity_Dashboard.class);
                            startActivity(i);
                                }
                        else {
                            Toast.makeText(getApplicationContext(),"Details no added",Toast.LENGTH_SHORT).show();
                        }
                    }
                    GlobalMethods.hideDialog();
                }


                @Override
                public void onFailure(Call<Patient_Report_Details_Output> call, Throwable t) {
                    GlobalMethods.hideDialog();
                }
            });
        }
        }
        catch (Exception e){

        }
    }
    public void getDialogItem(String itemname,String itemText){
        try{
        itemStatus=true;
        itemName=itemname;
            bottum_items_details=itemText;
        }
        catch (Exception e){

        }
    }

    public String selectTypeOfEvent(){

        int selectedId = event_type.getCheckedRadioButtonId();
        selectedType=(RadioButton)findViewById(selectedId);
        String type=selectedType.getText().toString();

        return type;
    }

    public void takeVideo(){
        showDiloagVideo();
    }

    public void takePhoto(){

        showDiloagPhoto();

    }

    public void showDiloagPhoto() {
        Dialog dialog = new Dialog(this);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Choose Image");
        builder.setItems(new CharSequence[]{"Camera", "Gallery"}, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        try {
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            startActivityForResult(intent, CAMERA_REQUEST_CODE);
                        } catch (Exception e) {
                            Toast.makeText(getApplicationContext(),""+e,Toast.LENGTH_LONG).show();
                        }
                        break;
                    case 1:
                        pickGalleryImage();
                        break;
                    default:
                        break;
                }
            }
        });
        builder.show();
        dialog.dismiss();
    }

    public void showDiloagVideo() {
        Dialog dialog = new Dialog(this);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Choose Image");
        builder.setItems(new CharSequence[]{"Camera", "Gallery"}, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        try {
                            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                            startActivityForResult(intent, CAMERA_VIDEO_REQUEST);
                        } catch (Exception e) {
                            Toast.makeText(getApplicationContext(),""+e,Toast.LENGTH_LONG).show();
                        }
                        break;
                    case 1:
                        pickGalleryVideo();
                        break;
                    default:
                        break;
                }
            }
        });
        builder.show();
        dialog.dismiss();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CAMERA_REQUEST_CODE && requestCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            imageBitmap = (Bitmap) extras.get("data");
            // setImage.setImageBitmap(imageBitmap);
        }
        else if (requestCode == CAMERA_VIDEO_REQUEST && requestCode == RESULT_OK) {
            Uri videoUri = data.getData();
            //imageBitmap = (Bitmap) extras.get("data");
        }
        else if (resultCode == RESULT_OK) {
            if (requestCode == GALLERY_REQUEST_CODE) {
                Uri selectedImageUri = data.getData();
                fileManagerString = selectedImageUri.getPath();
                selectedImagePath = uploadphoto.getPath(this, selectedImageUri);
                imagePath = selectedImagePath;

                if (selectedImagePath != null) {
                    try {
                        //This line is used for solving out of memory problem
                        final BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inSampleSize = 8;
                        imageBitmap = BitmapFactory.decodeFile(selectedImagePath, options);

                        Bitmap bm = BitmapFactory.decodeFile(selectedImagePath, options);

                        imageFilePath = uploadphoto.getimageString(bm);

                        Toast.makeText(getApplicationContext(), "" + imageFilePath, Toast.LENGTH_LONG).show();

                        //setImage.setImageBitmap(bm);
                    } catch (Exception e) {
                        e.getMessage();

                    }
                } else {
                    Toast.makeText(getApplicationContext(), "selectedImagePath is null", Toast.LENGTH_SHORT).show();
                }

                if (fileManagerString != null) {
                    //   System.out.println(filemanagerstring);
                    //  CaptureImage.setImageBitmap(BitmapFactory.decodeFile(filemanagerstring));
                } else {
                    Toast.makeText(getApplicationContext(), "filemanagerstring is null", Toast.LENGTH_SHORT).show();
                }
            }
            if (requestCode == GALLERY_VIDEO_REQUEST) {

                Uri selectedVideoUri=data.getData();

                pathtoStoredVideo=getRealPathFromURIPath(selectedVideoUri,this);
                //uploadVideoToServer(pathtoStoredVideo);

                fileManagerString=selectedVideoUri.getPath();
                selectedVideoPath=uploadphoto.getPath(this,selectedVideoUri);

                if(selectedVideoPath != null){
                    try{


                    }catch (Exception e){

                    }
                }

                if (fileManagerString != null) {
                    //   System.out.println(filemanagerstring);
                    //  CaptureImage.setImageBitmap(BitmapFactory.decodeFile(filemanagerstring));
                } else {
                    Toast.makeText(getApplicationContext(), "filemanagerstring is null", Toast.LENGTH_SHORT).show();
                }


            }
        }

        /*else if (resultCode == RESULT_OK) {

        }*/

    }
    public void pickGalleryImage() {
        try {
            if (Build.VERSION.SDK_INT < 19) {
                Intent intent = new Intent();
                intent.setType("image/jpeg");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), GALLERY_REQUEST_CODE);
            } else {
                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/jpeg");
                startActivityForResult(intent, GALLERY_REQUEST_CODE);
            }
        } catch (Exception e) {

        }
    }

    public void pickGalleryVideo() {
        try {
            if (Build.VERSION.SDK_INT < 19) {
                Intent intent = new Intent();
                intent.setType("video/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select Video"), GALLERY_VIDEO_REQUEST);
            } else {
                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("video/*");
                startActivityForResult(intent, GALLERY_VIDEO_REQUEST);
            }
        } catch (Exception e) {

        }
    }


    private String getRealPathFromURIPath(Uri contentURI, Activity activity) {
        Cursor cursor = activity.getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) {
            return contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            return cursor.getString(idx);
        }
    }

    public void uploadVideoToServer(String pathToVideoFile){

        try {
            if (GlobalMethods.isConnectedToInternet(getApplicationContext(), false)) {
                int userid=sessionManager.getUserId();
                GlobalMethods.ShowDialog(this);

                File videoFile = new File(pathToVideoFile);
                RequestBody videoBody = RequestBody.create(MediaType.parse("video/*"), videoFile);
                MultipartBody.Part vFile = MultipartBody.Part.createFormData("video", videoFile.getName(), videoBody);
                //RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), videoFile.getName());

                Call<Upload_Video_Output> upload_video_outputCall= realtrackerApi.uploadVideo(vFile,new TestModel("hello"));
                upload_video_outputCall.enqueue(new Callback<Upload_Video_Output>() {
                    @Override
                    public void onResponse(Call<Upload_Video_Output> call, Response<Upload_Video_Output> response) {
                        if(response.isSuccessful()&&response.body()!=null) {
                            if (response.body().getstatus()) {

                                Toast.makeText(getApplicationContext(),"video uploaded"+response.body().getMessage(),Toast.LENGTH_SHORT).show();
                            }
                        }else
                        {
                            Toast.makeText(getApplicationContext(),"video not uploaded"+response.body().getMessage(),Toast.LENGTH_SHORT).show();
                        }
                        GlobalMethods.hideDialog();
                    }
                    @Override
                    public void onFailure(Call<Upload_Video_Output> call, Throwable t) {
                        Toast.makeText(getApplicationContext(),"failed to video uploaded",Toast.LENGTH_SHORT).show();
                        GlobalMethods.hideDialog();
                    }
                });
            }
        }catch (Exception e){

        }
    }
}

1 个答案:

答案 0 :(得分:0)

我在这里可以看到的主要问题是:将requestCode == RESULT_OK替换为resultCode == RESULT_OK

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {}
    else if (requestCode == CAMERA_VIDEO_REQUEST && resultCode == RESULT_OK){}
    else if (resultCode == RESULT_OK) {}
}