My android app has three buttons On click all the button do the same work,
And the code is so long I don't want to copy the code 3 time.
So, how can I do this using a method?
This the code of one button
public void onClick(View v) {
switch (v.getId()) {
case R.id.Btn1:
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1); //Gallery acessing
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
super.setContentView(R.layout.activity_view);
selectedImage = (ImageView) findViewById(R.id.selectedImage); //Onresult redarct to anothr activity
}
Uri photoUri = data.getData();
if (photoUri != null) {
try {
currentImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri);
selectedImage.setImageBitmap(currentImage);
} catch (Exception e) {
e.printStackTrace();
Intent myIntent = new Intent(this, ViewActivity.class);
startActivity(myIntent); //switch activity
}
}}
}
You can try the below code. I have created a public method doSomething() which is called on each button click so it performs the same function whenever it is called.
public void onClick(View v) {
switch (v.getId()) {
case R.id.Btn1:
doSomething();
break;
case R.id.Btn2:
doSomething();
break;
}
}
public void doSomething(){
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1); //Gallery acessing
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
super.setContentView(R.layout.activity_view);
selectedImage = (ImageView) findViewById(R.id.selectedImage); //Onresult redarct to anothr activity
}
Uri photoUri = data.getData();
if (photoUri != null) {
try {
currentImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri);
selectedImage.setImageBitmap(currentImage);
} catch (Exception e) {
e.printStackTrace();
Intent myIntent = new Intent(this, ViewActivity.class);
startActivity(myIntent); //switch activity
}
}}
}
private View.OnClickListener myClickListener = new View.OnClickListener(){
public void onClick(View view){
//do all the work here
}
}
then set it in you Views
view1.setOnClickListener(myClickListener);
view2.setOnClickListener(myClickListener);
//... etc
You can Use performClick of first button in other views click.
Button button1 = findViewById(R.id.Btn1)
case R.id.Btn2:
button1.performClick()
Related
I have a method that takes a picture and then in the onActivityResult passes to another activity for subsequent analysis of the picture. So far so good.
My problem is that when I use a handler to repeat the process every 10 sec, the method is called but it will only take photos automatically without passing to the other activity. My guess is that when the method is called again automatically the onActivityResult is never called. Does anybody have a clue of which could may be be the problem?
takePhotoBtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
TakePhoto();
}
});
private void TakePhoto() {
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File imagepath = new File(getFilesDir(), "images");
File newFile = new File(imagepath, ".jpg");
if (newFile.exists()) {
newFile.delete();
}else {
newFile.getParentFile().mkdir();
}
selectedPhotoPath = getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileprovider", newFile);
startActivityForResult(captureIntent, TAKE_PHOTO_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_REQUEST_CODE && resultCode == RESULT_OK) {
InputStream inputStream;
try {
inputStream = getContentResolver().openInputStream(selectedPhotoPath);
bundle = new Bundle();
bundle.putParcelable(KEY_BITMAP, selectedPhotoPath);
}catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "Unable to open image", Toast.LENGTH_LONG).show();
}
}
Intent intent = new Intent(this, Activity.class);
intent.putExtras(bundle);
startActivity(intent);
handler.postDelayed(new Runnable() {
#Override
public void run() {
TakePhoto();
handler.postDelayed(this, 10000);
}
},10000);
}
Any kind of help will be highly appreciated!!! Thanks
I have a 2 activity A and B .
In activity A I start activity B . On activity B I want to do photo and go back to activity A and do next step.
In activity A I have :
Intent intent1 = new Intent(this, CameraActivity.class);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent1, REQUEST_CAMERA);
In activity B I have
buttonClick.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
camera.autoFocus(new Camera.AutoFocusCallback() {
#Override
public void onAutoFocus(boolean success, Camera camera) {
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
startActivity();
}
});
}
});
private void startActivity(){
Intent output = new Intent();
output.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
setResult(REQUEST_CAMERA, output);
finish();
}
And on Activity A I have :
#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);
}
}
}
I don't know how on Activity B put fileUri and start good method on activity A
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
new ImageTask().execute(data);
clearCamera();
}
};
Intent output = new Intent();
output.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
setResult(RESULT_OK, output);//change this
finish();
I am having problems with a global variable in my Java code. Here is the thing: My Screen has 3 ImageButtons elements for picking 3 images when pressing on them; this works fine. I am using onActiviyResult in order to make it, but I have implemented just one onActiviyResult method for the 3 images, so I am using 3 if(){...} blocks in the method to know the pressed imagebutton, I mean this:
if(current_picture.equals("pic1"))}{
imagebutton1.setImageBitmap(bitmap);
}
if(current_picture.equals("pic2"))}{
imagebutton2.setImageBitmap(bitmap);
}
if(current_picture.equals("pic3"))}{
imagebutton3.setImageBitmap(bitmap);
}
Here, current_picture is a String, and it's declared outside the onCreate method, and its default value is set to: String current_picture = "";
I use this variable to save a value that was set on the setonclicklistener events of the 3 imagebuttons, I mean:
imagebutton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
current_picture = "pic1";
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose a
picture"), SELECT_PICTURE);
}
});
Same thing for imagebutton2 (current_picture = "pic2";) and imagebutton3 (current_picture = "pic3";). All these events are on onCreate method obviously.
So, the problem is that current_picture is losing its value set on the setonclicklistener methods when calling onActivityResult method, I mean, current_user value is still "" and not "pic1", "pic2" or "pic3" depending on the pressed imagebutton. I think its value is destroyed when calling the new activity onActivityResult, then onActivityResul just recognizes: String current_picture = "";
I have done many things to solve this but i am able to find a solution, I attached some code (not all, just important parts) below:
public class Publish_Event extends Activity{
private ImageButton imagebutton1;
private ImageButton imagebutton2;
private ImageButton imagebutton3;
private Bitmap bitmap;
private String current_picture="";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.publicar_eventos);
StrictMode.ThreadPolicy p = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(p);
imagebutton1 = (ImageButton)findViewById(R.id.pic1);
imagebutton2 = (ImageButton)findViewById(R.id.pic2);
imagebutton3 = (ImageButton)findViewById(R.id.pic3);
imagebutton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
current_picture = "pic1";
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose a
picture"), SELECT_PICTURE);
}
});
imagebutton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
current_picture = "pic2";
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose a
picture"), SELECT_PICTURE);
}
});
imagebutton3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
current_picture = "pic3";
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose a
picture"), SELECT_PICTURE);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
imagen_path = getRealPathFromURI(selectedImageUri);
bitmap = BitmapFactory.decodeFile(imagen_path);
if(current_picture.equals("pic1")){
imagebutton1.setImageBitmap(bitmap);
}
if(current_picture.equals("pic2")){
imagebutton2.setImageBitmap(bitmap);
}
if(current_picture.equals("pic3")){
imagebutton3.setImageBitmap(bitmap);
}
}
}
}
#TargetApi(Build.VERSION_CODES.KITKAT)
public String getRealPathFromURI(Uri contentUri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = null;
try {
if (Build.VERSION.SDK_INT > 19) {
// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(contentUri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
cursor = Publish_Event.this.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, sel, new String[] { id }, null);
} else {
cursor =
Publish_Event.this.getContentResolver().query(contentUri,
projection, null, null, null);
}
} catch (Exception e) {
e.printStackTrace();
}
String path = null;
try {
int column_index =
cursor.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index).toString();
cursor.close();
} catch (NullPointerException e) {
e.printStackTrace();
}
return path;
}
}
You can start activity with different request code.
public class Publish_Event extends Activity{
private static final int SELECT_PICTURE_1 = 1;
private static final int SELECT_PICTURE_2 = 2;
private static final int SELECT_PICTURE_3 = 3;
protected void onCreate(Bundle savedInstanceState) {
imagebutton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose a picture"), SELECT_PICTURE_1);
}
});
imagebutton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose a picture"), SELECT_PICTURE_2);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE_1) {
//change imagebutton1
}else if(requestCode == SELECT_PICTURE_2){
//change imagebutton2
}else if(requestCode == SELECT_PICTURE_3){
//change imagebutton3
}
}
}
}
I have an application in which multiple activities are shown in a certain order, which can change based on events in the current activity. I have a "master" activity which manages which activities are shown. Each ativity is started with startActivityForResult() with a requestCode unique to that activity.
When the activity finsishes, I set the resultCode to a value which will have meaning to the master activity. In the master activity's onActivityResult method, I have a switch (requestCode), which will tell me which activity has returned, and in each case block I work with the resultCode to determine which activity to start next.
The problem I'm having, is that at times, seemingly randomly, the application behaves quite erratically, showing activities out of sequence.
I've been unable to replicate the issue while debugging, so all the information I have looks good, but the end users are constantly complaining about the erratic behaviour.
How can I test to see where the problem is?
The code from the master activity's onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case Settings.SCREEN_UPDATE:
ShowActivity(LoginActivity.class, Settings.SCREEN_LOGIN);
break;
case Settings.SCREEN_LOGIN:
if (resultCode == RESULT_OK) {
Settings.CurrentReport = new Report();
Settings.CurrentReport.setUserId(data.getIntExtra("userId", -1));
selectStore();
} else {
finish();
}
break;
case Settings.SCREEN_PRODUCT: // Coming back from the product selection screen
if (resultCode == RESULT_OK) {
ShowActivity(ActionActivity.class, Settings.SCREEN_ACTION);
} else if (resultCode == RESULT_CANCELED){
ShowActivity(OptionsActivity.class, Settings.SCREEN_OPTIONS);
}
break;
case Settings.SCREEN_ACTION: // Coming back from the action screen, regardless of result, show options screen.
ShowActivity(OptionsActivity.class, Settings.SCREEN_OPTIONS);
break;
case Settings.SCREEN_OPTIONS: // All choices return result_ok. Check the "mode" extra
String mode = data.getStringExtra("mode");
processOption(mode);
break;
case Settings.SCREEN_SESSION:
if (resultCode == RESULT_CANCELED) {
ShowActivity(OptionsActivity.class, Settings.SCREEN_OPTIONS);
} else if (resultCode == RESULT_OK ){
ShowActivity(ActionActivity.class, Settings.SCREEN_ACTION);
}
break;
} // switch (requestCode)
} // protected void onActivityResult(int requestCode, int resultCode, Intent data) {
private void processOption(String mode) {
if (mode.equals("select")) {
ShowActivity(ProductActivity.class, Settings.SCREEN_PRODUCT);
} else if (mode.equals("repeat")) {
Settings.CurrentReport.repeatItem();
ShowActivity(ActionActivity.class, Settings.SCREEN_ACTION);
} else if (mode.equals("session")) {
ShowActivity(SessionActivity.class, Settings.SCREEN_SESSION);
} else { // mode equals "end"
confirmFinish();
}
}
private void ShowActivity(Class cls, int requestCode) {
Intent activity = new Intent(this, cls);
startActivityForResult(activity, requestCode);
}
Then, the code from one of the other activities handling the finish() event:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.options);
Button btn;
btn = (Button)findViewById(R.id.btnSelect);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = getIntent();
intent.putExtra("mode", "select");
setResult(RESULT_OK, intent);
finish();
}
});
btn = (Button)findViewById(R.id.btnRepeat);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = getIntent();
intent.putExtra("mode", "repeat");
setResult(RESULT_OK, intent);
finish();
}
});
btn.setEnabled(Settings.CurrentReport.hasPreviousItem());
btn = (Button)findViewById(R.id.btnSession);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = getIntent();
intent.putExtra("mode", "session");
setResult(RESULT_OK, intent);
finish();
}
});
btn = (Button)findViewById(R.id.btnEnd);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = getIntent();
intent.putExtra("mode", "end");
setResult(RESULT_OK, intent);
finish();
}
});
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
Intent i = getIntent();
i.putExtra("mode", "end");
setResult(RESULT_OK, i);
finish();
break;
}
return super.onKeyDown(keyCode, event);
}
Im just guessing, but maybe Intent intent = getIntent(); is causing the problems. You could try to replace it with Intent intent = new Intent();
getIntent() returns the intent that started the current activity and shouldn't be used as a result.
Hi stackoverflow friends,
I need to take a picture using camera and after takin the picture go to next activity without showing the first activity. And display it in an imageview.
Below is the flow of my application
first activity-> there is button for camera intent->go to the next activity(without showing the fist activity) second activity->there i need to show the image in imageview.
I saw a lot of examples of camera intent nobody explains how to go to the next activity without showing the first and display it in imageview of second.
Any outofmemeory problem occurs while displaying images in imageview repeatedly?
Thanks in advance
In First activity :
Button b=(Button)findViewByid(R.id.button);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
doTakePhotoAction();
}
});
private void doTakePhotoAction() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"pic_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, CAMERA_RESULT);
// finish();
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
if (requestCode == CAMERA_RESULT) {
Intent intent = new Intent(this, nextimage.class);
// here you have to pass absolute path to your file
intent.putExtra("image-path", mUri.getPath());
intent.putExtra("scale", true);
startActivity(intent);
finish();
}
}
In nextimage.class you can set one image view and get the imagepath from putExtra and place it in imageview.
String mImagePath = extras.getString("image-path");
Bitmap mBitmap = getBitmap(mImagePath);
private Uri getImageUri(String path) {
return Uri.fromFile(new File(path));
}
private Bitmap getBitmap(String path) {
Uri uri = getImageUri(path);
InputStream in = null;
try {
in = mContentResolver.openInputStream(uri);
return BitmapFactory.decodeStream(in);
} catch (FileNotFoundException e) {
Log.e(TAG, "file " + path + " not found");
}
return null;
}
place the bitmap in the imageview.you have to create imageview in secondActivity.
use a camera intent....here's a simple code
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.ImageView;
public class CameraIntent extends Activity {
final static int CAMERA_RESULT = 0;
ImageView imv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CAMERA_RESULT);
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK)
{
Get Bundle extras = intent.getExtras();
Bitmap bmp = (Bitmap) extras.get("data");
imv = (ImageView) findViewById(R.id.ReturnedImageView);
imv.setImageBitmap(bmp);
}
}
}
Use Following Code for that, it will solve your problem.
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
onActivityResult() Method:-
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_PIC_REQUEST) {
bmpImage = (Bitmap) data.getExtras().get("data");
drawable = new BitmapDrawable(bmpImage);
mImageview.setImageDrawable(drawable);
}
}
}