在android中按钮点击从一个类调用另一个类函数

时间:2017-04-13 19:28:59

标签: android

我正在制作一个包含各种活动的应用程序,每个活动都使用另一个类中定义的相机功能。我想在每个活动中单击相机按钮时调用相机类。

这是我的主要课程: -

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();
    }
   }
  }; 

.....这是相机类......: -

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 个答案:

答案 0 :(得分:0)

这可以通过定期的活动间通信机制来实现,例如传递意图或使用广播接收器。我建议使用意图 - 请参阅Android doc中的基本示例:https://developer.android.com/training/basics/firstapp/starting-activity.html

修改

在评论中回答OP的问题 -

您必须将图像文件保存到Camera Class中的FS,并将文件名作为Extra传递给您的Crime类。由于您正在处理存储,因此现在应用程序的清单需要其他权限。我建议你通过这个帖子:Camera is not saving after taking picture