Passing camera image to another activity, nothing happens - android

What's wrong with my code? I sucessfully take the image, but the second activity is not starting. I want to pass my taken image to the second activity.
public class MainActivity extends Activity {
private static final int CAMERA_REQUEST = 1888;
private Button buttonka;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonka = (Button) findViewById(R.id.button);
{
buttonka.setOnClickListener(new View.OnClickListener() {
public void onClick (View v){
switch (v.getId()) {
case R.id.button:
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
break;
}
}
});
}}
protected void onActivityResult(int requestCode, int resultCode, Intent data, Uri mCapturedImageURI) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap bitmapImage = (Bitmap) getIntent().getExtras().get("data");
Intent camintent = new Intent(MainActivity.this, Main2Activity.class);
camintent.putExtra("bitmap", bitmapImage);
startActivity(camintent);
}
}
}
Receiver activity:
public class Main2Activity extends AppCompatActivity {
private ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
getData();
}
private void getData() {
Bitmap bitImage = getIntent().getParcelableExtra("bitmap");
image.setImageBitmap(bitImage);
}
}
Somehow the application is not reacting, and not starting the second activity, may I missed something? Hope someone can help, thanks!

In your onActivityResult- use data.getExtras().get("data"), not getIntent. You don't want the intent used to launch the app, you want the one returned as a result.

I founded the solution, forget to add the camera and write storage permission in the manifest files. If anyone get in a problem like this, make sure you writing the correct permissions! :) + removed the unused Uri mCapturedImageURI)

Related

Need to know where to correctly place the finish() function to close an activity

I am stuck trying to figure out where exactly to put the finish() function in my code.
I have tried putting it on line 43 of ProfileActivity or lines 39 or 56 of MainActivity. I'm very new at this and have read what the purpose of finish() is but can't figure out where else in my code it should go.
These are just nippets of the code ... there is more (all the Activity lifecycle functions), but I omitted to save space.
public class MainActivity extends AppCompatActivity {
SharedPreferences sp;
EditText email;
public static final String ACTIVITY_NAME = "PROFILE_ACTIVITY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email = (EditText)findViewById(R.id.thisEmailIsPassedToPage2);
sp = getSharedPreferences("Lab3", Context.MODE_PRIVATE);
String savedString = sp.getString("Email", "0");
email.setText(savedString);
Log.e(ACTIVITY_NAME, "In Function onCreate() in MainActivity:");
Button login = (Button)findViewById(R.id.loginButton);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,
ProfileActivity.class);
EditText et =
(EditText)findViewById(R.id.thisEmailIsPassedToPage2);
intent.putExtra("typed", et.getText().toString());
startActivityForResult(intent, 2);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
int i = 0;
i++;
//if request code is 2, then we are coming back from ProfileActivity
if(requestCode == 2){
EditText et =
(EditText)findViewById(R.id.thisEmailIsPassedToPage2);
String fromProfile = data.getStringExtra("typed");
et.setText(fromProfile);
Log.i("Back", "Message");
}
}
public class ProfileActivity extends AppCompatActivity {
private SharedPreferences sp;
private ImageButton mImageButton;
public static final String ACTIVITY_NAME = "PROFILE_ACTIVITY";
public static final int REQUEST_IMAGE_CAPTURE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profileactivity);
Log.e(ACTIVITY_NAME, "In Function onCreate() in ProfileActivity:");
Intent fromPrevious = getIntent();
String previousTyped = fromPrevious.getStringExtra("typed");
EditText enterText = (EditText) findViewById(R.id.editText6);
enterText.setText(previousTyped);
mImageButton = (ImageButton) this.findViewById(R.id.imageButton);
mImageButton.setOnClickListener(bt -> {
dispatchTakePictureIntent();
});
}
private void dispatchTakePictureIntent(){
Intent takePictureIntent = new
Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageButton.setImageBitmap(imageBitmap);
}
}
These are the screenshots:
[MainActivity1stPage][1]
[ProfileActivity2ndPage][2]
[AfterImageButtonPressed][3]
[AfterTakingPictureAndPressingOK][4]
If I'm getting it right, your flow is MainActivity starts ProfileActivity for result, then in ProfileActivity you start the ACTION_IMAGE_CAPTUREfor result, so I'm guessing that with that result you want to trigger your MainActivity onActivityResult. So if that the case you need to setResult and finish at the onActivityResultof your ProfileActivity.

Invoking camera from within my application through button click

Completely new to this and to Android development, looking for a bit of help if possible. I am developing my first application for Android at the moment and have very little coding experience...I basically have an application at the moment that is allowing me to add/delete/update users to and from a sqlite database. I am looking for a way just to add a button on the main homepage that allows me to access the camera and take a picture. The main activity is simply a page with buttons to add/delete etc:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
DatabaseHelper mDatabaseHelper;
private Button btnAdd, btnViewData;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnViewData = (Button) findViewById(R.id.btnView);
mDatabaseHelper = new DatabaseHelper(this);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = editText.getText().toString();
if (editText.length() != 0) {
AddData(newEntry);
editText.setText("");
} else {
toastMessage("Please enter a name!");
}
}
});
btnViewData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListDataActivity.class);
startActivity(intent);
}
});
}
public void AddData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("User Added!");
} else {
toastMessage("Something went wrong");
}
}
/**
* customizable toast
* #param message
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
The code I have for implementing the camera is shown below(it works for invoking the camera and taking a picture but only from the camera outside the application)
Is it possible for me to just a button on the main activity page that allows me to "take picture" from within the application
(code for invoking camera)
public class MainActivity extends AppCompatActivity {
public void getPhoto() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 1);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager. PERMISSION_GRANTED){
getPhoto();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
} else{
getPhoto();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
try {
Uri selectedImage = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Sorry if the question seems stupid, completely new to Android development and new to coding so I am very unsure.
I'm not sure about what you are looking for, but here is code to take a picture :
https://developer.android.com/training/camera/photobasics.html
To add the button, you need to add it in the layout then get the reference in your activity class with the findViewById method
Hope this help

In Multi Image Selector OnActivityResult() method is not getting called in Fragment

I am trying to make image selector for application.For that i am using multi-image-selector library which is perfeclty works when used in activity ,but here i want to use it in fragment.so in fragment OnActivityResult() method is not getting called.Can anyone help me to solve this?
Here's my code:
MainActivity.java:(My Main Activity)
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_IMAGE = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager().beginTransaction().replace(R.id.frame, new Image_Selecter()).commit();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Utilz.printLog("Parentactivity", "onActivityResult");
Log.e("hererererer", "hererererer");
if (requestCode == REQUEST_IMAGE) {
new Image().onActivityResult(requestCode, resultCode, data);
}
}
}
Image:(My Fragment)
public class Image extends Fragment {
private ArrayList<String> mSelectPath;
private static final int REQUEST_IMAGE = 2;
ArrayList<Uri> mMedia = new ArrayList<Uri>();
Uri uri;
ImageView img;
protected static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION = 101;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_image, container, false);
img = (ImageView) view.findViewById(R.id.img);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pickImage();
}
});
return view;
}
public void pickImage() {
MultiImageSelector selector = new MultiImageSelector(getActivity());
selector.showCamera(true);
selector.multi();
selector.count(1);
selector.origin(mSelectPath);
selector.start(getActivity(), REQUEST_IMAGE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE) {
if (resultCode == getActivity().RESULT_OK) {
mSelectPath = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
mMedia.clear();
for (String p : mSelectPath) {
Uri uri = Uri.parse(p);
mMedia.add(uri);
}
uri = mMedia.get(0);
Log.e("uri", " " + uri);
if (!uri.toString().contains("content://")) {
uri = Uri.fromFile(new File(uri.toString()));
Log.e("in if", " uri = " + uri);
}
try {
Glide.with(this)
.load(uri)
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.into(img);
} catch (Exception e) {
Log.e("Exceptionn", " " + e);
}
}
}
}
Try this in your activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("Parentactivity", "onActivityResult");
if (requestCode == REQUEST_IMAGE) { //use request code as REQUEST_IMAGE while starting intent for camera
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.frame);
fragment.onActivityResult(requestCode, resultCode, data);//calling fragments onActivityResult here
}
}
IIRC onActivityResult doesn't get called on a Fragment, it gets called on your parent Activity. You would need to catch this in the Activity and forward the result on to the fragment.
There are two methods which looks same but behaves little bit different.
If method is called by from activity, its not going to give callback to fragment unless called from fragment.
Activity.startActivityForResult()
Fragment.startActivityForResult()
Check out the library if there is way to calling it from fragment.
I dont know the library, just imaging if you can pass fragment to
MultiImageSelector selector = new MultiImageSelector(getActivity()); or selector.start(getActivity(), REQUEST_IMAGE);
Good luck
Emre
you have to call it with intent
public void pickImage() {
Intent intent = new Intent(getContext(), MultiImageSelectorActivity.class);
intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
intent.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, mSelectPath);
startActivityForResult(intent, REQUEST_IMAGE);
}
if you were doing getActivity().startActivityForResult(intent, REQUEST_IMAGE);
the on OnActivityResult() will happen on activity instead of fragment. The way you are using it is like that, so you need to use the intent way.
also that maybe will make your code to work
public void pickImage() {
MultiImageSelector selector = new MultiImageSelector(getContext());
selector.showCamera(true);
selector.multi();
selector.count(1);
selector.origin(mSelectPath);
selector.start(getContext(), REQUEST_IMAGE);
}

Use same instance of Activity

I am making a game, and i want to use the same Activity every time when a user fails the Level and i don't wanna create all the Views every time when the FailedActivity is shown.
For example i have Level1Activity:
public class Level1Activity extends Activity{
private static final int REQUEST_FAIL_ACTIVITY = 10;
private static final int RESULT_RETRY_LEVEL= 11;
public void onCreate(Bundle savedIntanceState){
...
}
public void showFailedActivity(){
Intent intent = new Intent(this, FailedActivity);
intent.putExtra("text1", "You failed! You made only 50 points");
intent.putExtra("text2", "Try again later");
startActivityForResult(intent, REQUEST_FAIL_ACTIVITY );
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_FAIL_ACTIVITY ){
if(resultCode == RESULT_BACK){
finish();
}else if(resultCode == RESULT_RETRY_LEVEL){
retryLevel();
}else{
finish();
}
}
}
}
And class FailedActivity
private RelativeLayout bgLayout;
private TextView text1;
private TextView text2;
private TextView text3;
private TextView text4;
private TextView text5;
private Button buttonRetryLevel;
private Button buttonBack;
public class FailedActivity extends Activity{
public void onCreate(Bundle saved){
super.onCreate(saved)
setContentView(R.layout.activity_failed);
bgLayout = (RelativeLayout)findViewById(R.id.bgLayout);
text1 = (TextView)findViewById(R.id.textView1);
...
buttonBack = (Button)findViewById(R.id.btnBack);
Bundle bundle = getIntent().getExtras();
text1.setText(bundle.getString("text1");
...
text5.setText(bundle.getString("text5);
}
public void buttonRetryClicked(View view){
setResult(Level1Activity.RESULT_RETRY_LEVEL);
finish();
}
...
}
So, i want to call findViewById for all the Views only once, and reuse the Activity because the FailedActivity i use for all my Levels, i need to pass only the Strings that will be shown, maybe the background color, etc.
My question is: can i create the FailedActivity only ones, and then when i call startActivityForResult just to pass the Bundle and the Views to be created only once.
You can use
singleInstance
as launch mode and override onNewIntent() function to bypass the re-creation of the activity UI components.
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
// handle parameters here.
}
Yes, this is possible as noted in the another answer. If you do this though, you are stepping outside of the standard Activity lifecycle. Generally, when an android app starts a new Activity, the old Activity is destroyed and a new instance of the new one is created. This also occurs when you change the device orientation (portrait -> landscape). The Android runtime does this for memory efficiency and because the view dimensions may have changed. Have a look at this if you want to learn more about the activity lifecycle.
Are the bundled values you're putting in an intent from your Level1Activity going to be the same for other levels? If so you could hardcode those strings directly into the xml layout file for FailedActivity. If you need all level activities to have the ability to open the FailedActivity, I'd consider creating a levelActivity superclass. This will simplify the FailedActivity creation code and stop you from having to repeat yourself. Something like this:
public abstract class LevelActivity extends Activity {
public void showFailedActivity(){
Intent intent = new Intent(this, FailedActivity);
intent.putExtra("text1", "You failed! You made only 50 points");
intent.putExtra("text2", "Try again later");
startActivityForResult(intent, REQUEST_FAIL_ACTIVITY );
}
}
public class Level1Activity extends LevelActivity {
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_FAIL_ACTIVITY ){
if(resultCode == RESULT_BACK){
finish();
}else if(resultCode == RESULT_RETRY_LEVEL){
super.retryLevel(); // calls LevelActivity.retryLevel()
}else{
finish();
}
}
}

Get startActivityForResult result in static function

I'm working from Unity and want to get the result of a file picking activity. Since I can't start activities from Unity itself, I created an "intermediant" static class called EclipseIntegration:
package com.Unity3D.EclipseIntegration;
public class EclipseIntegration {
public static String selectedPath = "really ";
public static void Launch(Activity activity) {
Intent target = new Intent(activity, MyActivity.class);
activity.startActivity(target);
}
}
activity is the Activity Unity is currently running in.
MyActivity is meant to start the real activity, because I need something that inherits from Activity to get the onActivityResult event:
package com.Unity3D.EclipseIntegration;
public class MyActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Launch();
}
public void Launch() {
Intent target = FileUtils.createGetContentIntent();
Intent intent = Intent.createChooser(target, "Select a movie");
startActivityForResult(intent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 128:
if (resultCode == RESULT_OK) {
final Uri uri = data.getData();
File file = FileUtils.getFile(uri);
EclipseIntegration.selectedPath = file.getAbsolutePath();
}
else EclipseIntegration.selectedPath = "";
finish();
}
}
}
but nothing happens. If I start the final activity directly in the static class like this :
activity.startActivity(intent); it works though, so I suppose I made some error while setting up the MyActivity? Despite trying this for 2 days now I couldn't find it though, so any nudge in the right direction would be very appreciated :)
Thanks,
kiriri
Try this way
public void Launch() {
Intent target = FileUtils.createGetContentIntent();
Intent intent = Intent.createChooser(target, "Select a movie");
startActivityForResult(intent,128);
}

Categories

Resources