0

I am making an app with various activities and each activity uses the camera function which is defined in another class. I want that in each activity when the camera button is clicked the camera class is called.

This is my main class:-

package com.example.ishan.complainbox;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.lang.String;

public class Crime extends MainActivity implements View.OnClickListener
{
camera cam=new camera();
EditText str,city,pn,det;
Button save,pic;
crimeDBHandler dbHandler;
@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_crime);

    // Get References of Views
    str = (EditText) findViewById(R.id.str);
    city = (EditText) findViewById(R.id.city);
    pn = (EditText) findViewById(R.id.pin);
    det = (EditText) findViewById(R.id.detail);
    save = (Button) findViewById(R.id.save);
    pic=(Button) findViewById(R.id.uploadpic);
    dbHandler = new crimeDBHandler(this, null, null, 1);
  }

  public void onClick(View view) {
    String street = str.getText().toString();
    String cty = city.getText().toString();
    String pin = pn.getText().toString();
    String detail = det.getText().toString();

     // check if any of the fields are vaccant
    if(str.equals("")||city.equals("")||pn.equals("")||det.equals(""))
    {
        Toast.makeText(getApplicationContext(), "Field Vacant", 
   Toast.LENGTH_LONG).show();
        return;
    }
    // check if both passwords match

    else
    {
        // Save the Data in Database
        dbHandler.insertEntry(street,cty,pin,detail);
        Toast.makeText(getApplicationContext(), "Complaint Successfully 
    Filed ", Toast.LENGTH_LONG).show();
    }
   }
  }; 

.....and this is the camera class..:-

package com.example.ishan.complainbox;

/**
 * Created by ishan on 13/04/2017.
 */

import java.io.ByteArrayOutputStream;
import java.io.File; 
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class camera extends MainActivity{


private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private Button btnSelect;
private ImageView ivImage;
private String userChosenTask;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_crime);
    btnSelect = (Button) findViewById(R.id.uploadpic);
    btnSelect.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            selectImage();
        }

    });

    ivImage = (ImageView) findViewById(R.id.imgView);
 }


  @Override
  public void onRequestPermissionsResult(int requestCode, String[] 
  permissions, int[] grantResults) {
    switch (requestCode) {
        case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
            if (grantResults.length > 0 && grantResults[0] == 
  PackageManager.PERMISSION_GRANTED)
            {
                if(userChosenTask.equals("Take Photo"))
                    cameraIntent();
                else if(userChosenTask.equals("Choose from Library"))
                    galleryIntent();
            } else {
            }
           break;
    }
  }
  private void selectImage() {
    final CharSequence[] items = { "Take Photo", "Choose from Library",
            "Cancel" };
    AlertDialog.Builder builder = new AlertDialog.Builder(camera.this);
    builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            boolean result=Utility.checkPermission(camera.this);
            if (items[item].equals("Take Photo")) {
                userChosenTask ="Take Photo";
                if(result)
                    cameraIntent();
            } else if (items[item].equals("Choose from Library")) {
                userChosenTask ="Choose from Library";
                if(result)
                    galleryIntent();
           } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
       }

    });

    builder.show();

  } 


  private void galleryIntent()
  {

    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select  
   File"),SELECT_FILE);
   }

   private void cameraIntent()
   {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, REQUEST_CAMERA);
   }


   @Override
   public void onActivityResult(int requestCode, int resultCode, Intent 
    data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == SELECT_FILE)
            onSelectFromGalleryResult(data);
        else if (requestCode == REQUEST_CAMERA)
            onCaptureImageResult(data);
    }
  }

    private void onCaptureImageResult(Intent data) {
    Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
    File destination = new 

 File(Environment.getExternalStorageDirectory(),System.currentTimeMillis() + 
  ".jpg");
    FileOutputStream fo;
    try {
        destination.createNewFile();
        fo = new FileOutputStream(destination);
        fo.write(bytes.toByteArray());
        fo.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }


    ivImage.setImageBitmap(thumbnail);

   }


   @SuppressWarnings("deprecation")

   private void onSelectFromGalleryResult(Intent data) {
    Bitmap bm=null;
    if (data != null) {
        try {
            bm = 

 MediaStore.Images.Media.getBitmap(getApplicationContext().
   getContentResolver(), 
 data.getData());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    ivImage.setImageBitmap(bm);
   }

}

1 Answers1

0

This can be achieved through regular inter-activity communication mechanisms like passing intents or using broadcast receivers. I would suggest using intents - Refer this basic example from Android doc: https://developer.android.com/training/basics/firstapp/starting-activity.html

EDIT

Response to OP's question in comment-

You have to save the image file to FS in your Camera Class and pass the file name as an Extra with the intent to your Crime class. Since you are dealing with storage your Apps's manifest now would need additional permissions. I would recommend you go through this thread: Camera is not saving after taking picture

Community
  • 1
  • 1
Zakir
  • 2,222
  • 21
  • 31
  • I have another query in the same code....once the camera functions are done, I want to save the photo in the database the same way as the other data are saved....how can I get the selected/clicked picture in the Crime class ? – Ishani Sinha Apr 13 '17 at 20:04