I am working on camera related app in android. What I want is when user takes photo he should be immediately take to previous activity where he was before. Right now what my code does is when user takes a photo then two button appear at the bottom of the screen i.e. Save and Discard. So I do not want that. When the picture is taken user should be directly navigate to previous activity. How can acheive this?
Here is my code
public class CameraActivity extends Activity implements View.OnClickListener {
ImageView iv;
Button bCapture, bSetWall;
Intent i;
int CameraResult = 0;
Bitmap bmp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initialize();
InputStream is = getResources().openRawResource(R.drawable.ic_launcher);
bmp = BitmapFactory.decodeStream(is);
}
private void initialize() {
iv = (ImageView)findViewById(R.id.ivCamera);
bCapture = (Button)findViewById(R.id.bCapture);
bSetWall = (Button)findViewById(R.id.bSetWall);
bCapture.setOnClickListener(this);
bSetWall.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()) {
case R.id.bCapture:
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CameraResult);
break;
case R.id.bSetWall:
try {
getApplicationContext().setWallpaper(bmp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
iv.setImageBitmap(bmp);
}
}
}
The code you have right now will capture photos using an existing camera application. That is, it is making use of an already existing Activity that belongs to some camera application that is installed on your device.
That said, there is no way to manipulate Activitys that belong to other applications. You'll have to implement your own Camera Activity instead.
Related
This question already has answers here:
How to manage startActivityForResult on Android
(14 answers)
Closed 3 years ago.
I am using both an ImagePicker and a barcode reader in a single activity. The main problem is that both of these require onActivityResult() to display the result. As we know a single activity can only have a single onActivityResult() method in it. How can I display both of them?
I have tried using switch cases to assign multiple requestCodes in the onActivityResult() but can't seem to figure out the solution.
Here's the method I tried.
public class MainActivity extends AppCompatActivity{
private TextView mIdentificationNumber;
private IntentIntegrator scanQR;
//Authentication For Firebase.
private FirebaseAuth mAuth;
//Toolbar
private Toolbar mToolBar;
private DatabaseReference mUserRef;
private ImageView mAssetImg;
private EditText massetName, massetModel, massetBarcode, massetArea, massetDescription;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting the Present instance of the FireBase Authentication
mAuth = FirebaseAuth.getInstance();
//Finding The Toolbar with it's unique Id.
mToolBar = (Toolbar) findViewById(R.id.main_page_toolbar);
//Setting Up the ToolBar in The ActionBar.
setSupportActionBar(mToolBar);
if (mAuth.getCurrentUser() != null){
mUserRef = FirebaseDatabase.getInstance().getReference().child("Users")
.child(mAuth.getCurrentUser().getUid());
mUserRef.keepSynced(true);
}
massetBarcode = (EditText) findViewById(R.id.BarcodeAsset);
scanQR = new IntentIntegrator(this);
massetBarcode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanQR.initiateScan();
}
});
mAssetImg = (ImageView) findViewById(R.id.asset_img);
mAssetImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getImage();
}
});
}
//OnStart Method is started when the Authentication Starts.
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null).
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null){
startUser();
} else {
mUserRef.child("online").setValue("true");
Log.d("STARTING THE ACTIVITY" , "TRUE");
}
}
#Override
protected void onPause() {
super.onPause();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser != null){
mUserRef.child("online").setValue(ServerValue.TIMESTAMP);
Log.d("STOPPING THE ACTIVITY" , "TRUE");
}
}
private void startUser() {
//Sending the user in the StartActivity If the User Is Not Logged In.
Intent startIntent = new Intent(MainActivity.this , AuthenticationActivity.class);
startActivity(startIntent);
//Finishing Up The Intent So the User Can't Go Back To MainActivity Without LoggingIn.
finish();
}
//Setting The Menu Options In The AppBarLayout.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//Inflating the Menu with the Unique R.menu.Id.
getMenuInflater().inflate(R.menu.main_menu , menu);
return true;
}
//Setting the Individual Item In The Menu.(Logout Button)
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.main_logout_btn){
FirebaseAuth.getInstance().signOut();
startUser();
}
return true;
}
private void getImage() {
ImagePicker.Companion.with(this)
.crop() //Crop image(Optional), Check Customization for more option
.compress(1024) //Final image size will be less than 1 MB(Optional)
.maxResultSize(1080, 1080) //Final image resolution will be less than 1080 x 1080(Optional)
.start();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 0:
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (result.getContents() == null) {
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
massetBarcode.setText(result.getContents());
Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
}
}
break;
case 1:
if (resultCode == Activity.RESULT_OK) {
assert data != null;
Uri imageURI = data.getData();
mAssetImg.setImageURI(imageURI);
}
break;
}
}
}
The rest of the answers told to use startActivityForResult() but that method requires Intent to go from one activity to another but I don't want to do this.
In both cases, the libraries you're using provide a way to specify a request code so you can distinguish the results in onActivityResult.
Your scanQR object should set a request code, per the source code:
massetBarcode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanQR.setRequestCode(123).initiateScan();
}
});
You getImage() method should also specify a request code, again, per the library's source code.
private void getImage() {
ImagePicker.Companion.with(this)
.crop() //Crop image(Optional), Check Customization for more option
.compress(1024) //Final image size will be less than 1 MB(Optional)
.maxResultSize(1080, 1080) //Final image resolution will be less than 1080 x 1080(Optional)
.start(456); // Start with request code
}
Now, you can handle each request code as needed:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 123:
// HANDLE BARCODE
break;
case 456:
// HANDLE IMAGE
break;
}
}
Closing thought: I've never used either library. I found the solution by 1) assuming any library that provides an Activity you're supposed to invoke for a result would allow you to specify a request code for it and 2) looking through their documentation and source code for how to do that.
I'd encourage you to thoroughly study the documentation and source code for any open source library you intend to use since as soon as you do their code become your code and their bugs become your bugs, so you better know how to fix or workaround them.
Hope that helps!
In order to get results from fragments to your Activity, you can use an Interface to enable communication between them.
StartActivityForResult is used to start an activity and get a result back from it.
Please read more about it from here.
The startActivityForResult methos can use a second argument, a number so you can distinguish the resul
startActivityForResul(intent, 8)
You dont need to set the code back in the other activity, that is handled under the hood. So you probabbly want to add the number as a contant
private static final CAMERA_INTENT = 2
And then use it like this
startActivityForResul(intent, CAMERA_INTENT)
Finally in the onActivityResult implements the case basis
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
if (CAMERA_INTENT == requestCode) {
//DO PHOTO STUFF
}
}
The argument you need to eval is requestCode
Hello fellow programmers,
I'm experiencing some issues regarding my Android App, i'm currently
working on. For this purpose, I only need to mention that I have two
Activities (One is called MainActivity.class and the second is called
FilterActivity.class).
The purpose of my MainActiviy class is to display a movie (Genres,
year, rating etc) + a trailer of the specifik video.
In the OnCreate method for MainActiviy, im initializing the
YouTubePlayerView (since I want a random movie to pop up as soon as
you open the application).
The purpose of my FilterActivity class is to choose some specfik
search criterias for a movie.
I'm opening FilterActivity from MainActivity like this:
public void openFilter(){
Intent askIntent = new Intent(this, FilterActivity.class);
startActivityForResult(askIntent, 1); }
And in my FilterActivity im sending the information from a newly
created movie like this:
movieIntent.putExtra("url", a.getUrl());
movieIntent.putExtra("title", a.getTitle());
movieIntent.putExtra("rating", (String.valueOf(a.getRating())));
movieIntent.putExtra("plot", a.getDesc());
movieIntent.putExtra("year", (String.valueOf(a.getYear())));
movieIntent.putExtra("genre", a.getGenres());
setResult(RESULT_OK, movieIntent);
finish();
And this is how I fetch data from MainActivity:
protected void onActivityResult(int requestCode, int resultCode, final Intent data){
if(resultCode == RESULT_OK){
titleView.setText(data.getStringExtra("title"));
ratingView.setText(data.getStringExtra("rating"));
plotView.setText(data.getStringExtra("plot"));
yearView.setText(data.getStringExtra("year"));
genreView.setText(data.getStringExtra("genre"));
url = data.getStringExtra("url"); }
This is basically what I need to show. (This is all works by the way):
I'm getting a newly created movie and the criterias match.
However, in the OnActivityResult, I can't get my YoutubePlayerView to
re-load the video with the specific URL. The old video is still there,
and playable. I have checked and I am indeed getting a new URL from
the FilterActivity.
The only way I'm coming around this issue is by basically reloading
the activity, and then (since im creating a random movie in my
OnCreate method), the criteria don't match.
Any suggestions would be appreciated!
Sincerely
In onActivityResult, release current player and re-initialize YoutubePlayerView :
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
if (resultCode == RESULT_OK) {
mVideoId = getVideoId(data.getStringExtra("url"));
mPlayer.release();
mYoutubeplayerView.initialize(mApiKey, this);
}
}
A complete example of MainActivity is :
public class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
String mVideoId = "5xVh-7ywKpE";
String mApiKey = "YOUR_API_KEY";
YouTubePlayerView mYoutubeplayerView;
YouTubePlayer mPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mYoutubeplayerView = (YouTubePlayerView) findViewById(R.id.player);
mYoutubeplayerView.initialize(mApiKey, this);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFilter();
}
});
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
YouTubePlayer youTubePlayer, boolean b) {
mPlayer = youTubePlayer;
mPlayer.loadVideo(mVideoId);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult youTubeInitializationResult) {
}
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
if (resultCode == RESULT_OK) {
mVideoId = getVideoId(data.getStringExtra("url"));
mPlayer.release();
mYoutubeplayerView.initialize(mApiKey, this);
}
}
private String getVideoId(String url) {
String pattern = "(?<=watch\\?v=|/videos/|embed\\/)[^#\\&\\?]*";
Pattern compiledPattern = Pattern.compile(pattern);
Matcher matcher = compiledPattern.matcher(url);
if (matcher.find()) {
return matcher.group();
}
return "";
}
public void openFilter() {
Intent askIntent = new Intent(this, FilterActivity.class);
startActivityForResult(askIntent, 1);
}
}
Note that I've used this post to extract Youtube videoId from url path
I have 2 activities ,activity A is having webview and activity B is having button with transparent layout. I want close the activity B and refresh or do something in activity A when I press button from activity B.
I tried shared preferences but that not working without restarting activity A.
Have a look at the docs for Getting a Result from an Activity
Updated to include example
static final int PICK_CONTACT_REQUEST = 1; // The request code
...
private void pickContact() {
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a contact.
// The Intent's data Uri identifies which contact was selected.
// Do something with the contact here (bigger example below)
}
}
}
create a method as refreshmethod in Activity A and call it from Activity B something like this:
ActivityA activitya:
//stuff
activitya = new ActivityA();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
activitya.refreshmethod();
}
});
hope it helps.
I have a problem with my camera app, which is that when I take a photo I can see it in the imageview, but when I turn my phone or close the app and reopen it, the image disappears.
My code->
public class semana1 extends Activity {
Button btnfoto1;
ImageView imgs1;
static final int CAM_REQUEST=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.semana1);
btnfoto1= (Button) findViewById(R.id.btnfoto1);
imgs1= (ImageView) findViewById(R.id.imgs1);
btnfoto1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent int1=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file=getfile();
int1.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(int1,CAM_REQUEST);
}
});
}
private File getFile()
{
File folder=new File("sdcard/Progress");
if(!folder.exists())
{
folder.mkdir();
}
File image_file=new File(folder,"image1.jpg");
return image_file;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String path = "sdcard/Progress/image1.jpg";
imgs1.setImageDrawable(Drawable.createFromPath(path));
}
}
Read up on the activity lifecycle of an app.
Now to point you in somewhat the right direction. When you close your app, the system stops the app and might later kill it. The reason why your image disappears is because you haven implemented a way for your app to save the state it was in before hand.
Therefore, you should probably implement:
public void onStop() {
super.onStop();
// code where you tell the app to save the image
}
public void onDestroy() {
super.onDestroy();
// code where you tell the app to save the image
}
hey every one i am sorry but i have to ask this question, it seems like a very easy issue but i just stuck! i have spent the last 2 hours going through the form and android developer resource site and i cant find the problem with my code.
first of all the startActivityForResult() will not send me the text back.
second every time i click on the Implicit Activation button the app crashes.
here is the main activity file:
public class ActivityLoaderActivity extends Activity {
static private final int GET_TEXT_REQUEST_CODE = 1;
static private final String URL = "http://www.google.com";
static private final String TAG = "Lab-Intents";
// For use with app chooser
static private final String CHOOSER_TEXT = "Load " + URL + " with:";
// TextView that displays user-entered text from ExplicitlyLoadedActivity runs
private TextView mUserTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loader_activity);
// Get reference to the textView
mUserTextView = (TextView) findViewById(R.id.textView1);
// Declare and setup Explicit Activation button
Button explicitActivationButton = (Button) findViewById(R.id.explicit_activation_button);
explicitActivationButton.setOnClickListener(new OnClickListener() {
// Call startExplicitActivation() when pressed
#Override
public void onClick(View v) {
startExplicitActivation();
}
});
// Declare and setup Implicit Activation button
Button implicitActivationButton = (Button) findViewById(R.id.implicit_activation_button);
implicitActivationButton.setOnClickListener(new OnClickListener() {
// Call startImplicitActivation() when pressed
#Override
public void onClick(View v) {
startImplicitActivation();
}
});
}
// Start the ExplicitlyLoadedActivity
private void startExplicitActivation() {
Log.i(TAG,"Entered startExplicitActivation()");
// TODO - Create a new intent to launch the ExplicitlyLoadedActivity class
Intent explicitIntent = new Intent (ActivityLoaderActivity.this, ExplicitlyLoadedActivity.class);
// TODO - Start an Activity using that intent and the request code defined above
startActivityForResult(explicitIntent, GET_TEXT_REQUEST_CODE);
}
// Start a Browser Activity to view a web page or its URL
private void startImplicitActivation() {
Log.i(TAG, "Entered startImplicitActivation()");
// TODO - Create a base intent for viewing a URL
// (HINT: second parameter uses Uri.parse())
Intent baseIntent = new Intent (Intent.ACTION_VIEW, Uri.parse(URL));
// TODO - Create a chooser intent, for choosing which Activity
// will carry out the baseIntent
// (HINT: Use the Intent class' createChooser() method)
Intent chooserIntent = null;
chooserIntent.createChooser(baseIntent, CHOOSER_TEXT);
Log.i(TAG,"Chooser Intent Action:" + chooserIntent.getAction());
// TODO - Start the chooser Activity, using the chooser intent
startActivity(chooserIntent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "Entered onActivityResult()");
// TODO - Process the result only if this method received both a
// RESULT_OK result code and a recognized request code
// If so, update the Textview showing the user-entered text.
if (resultCode == RESULT_OK){
mUserTextView.setText(data.getStringExtra("resulttext"));
}}}
and here is the explicit intent file:
public class ExplicitlyLoadedActivity extends Activity {
static private final String TAG = "Lab-Intents";
private EditText mEditText;
String resulttext="still waiting";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.explicitly_loaded_activity);
// Get a reference to the EditText field
mEditText = (EditText) findViewById(R.id.editText);
// Declare and setup "Enter" button
Button enterButton = (Button) findViewById(R.id.enter_button);
enterButton.setOnClickListener(new OnClickListener() {
// Call enterClicked() when pressed
#Override
public void onClick(View v) {
enterClicked();
}
});
}
// Sets result to send back to calling Activity and finishes
private void enterClicked() {
Log.i(TAG,"Entered enterClicked()");
// TODO - Save user provided input from the EditText field
resulttext= mEditText.getText().toString();
// TODO - Create a new intent and save the input from the EditText field as an extra
Intent returntrip = new Intent ();
returntrip.putExtra("wayback", resulttext);
// TODO - Set Activity's result with result code RESULT_OK
setResult(RESULT_OK, returntrip);
// TODO - Finish the Activity
finish();
}
}
thank you guys so much i know i am a bother!
You are sending an extra data called "wayback" not "resulttext"
returntrip.putExtra("wayback", resulttext);
this will fix your code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "Entered onActivityResult()");
if (resultCode == RESULT_OK){
mUserTextView.setText(data.getStringExtra("wayback"));
}
Well, you won't get the result back correct from your onActivityResult because you are not using the correct key. You look inside for data.getStringExtra("resulttext") but you originally set the key as "wayback". You need to grab with that key.