Parcel Data Transfer on onActivityResult - java

I have problem with parcel data transfer. I don't know how to
transfer object parcelable to onActivityResult.
DreamDatabase implements Parcelable.
MyDreams.class
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_addream:
Intent intent = new Intent(getActivity(), AddDreamActivity.class);
startActivityForResult(intent, REQUEST_CODE_CREATE);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CODE_CREATE) {
DreamDatabase dreamDatabase = data.getData()
myDreamAdapter.addDream(dreamDatabase);
Toast.makeText(getActivity(), "Dreamd was added", Toast.LENGTH_SHORT).show();
}
}
}
AddDreams.class
if (!hasError) {
String selectDreamString = selectDreamTextView.getText().toString();
DreamDatabase dreamDatabase = new DreamDatabase(dreamTitleString, dreamDescriptionString, getCurrentDate(), selectDreamString);
Intent intent = new Intent();
intent.putExtra("dream", dreamDatabase);
setResult(RESULT_OK, intent);
super.finish();
}
Any suggestions?

This block:
if (requestCode == REQUEST_CODE_CREATE) {
DreamDatabase dreamDatabase = data.getData()
myDreamAdapter.addDream(dreamDatabase);
Toast.makeText(getActivity(), "Dreamd was added", Toast.LENGTH_SHORT).show();
}
Should be changed to:
DreamDatabase dreamDatabase = data.getParcelableExtra("dream");
...

Related

How to get image uri from camera intent?

i am trying to get the uri of the picture that have been taken from device camera. I just tried some of the advices from online but i could not manage to solve this problem here is the my code parts.
ImageView petImage;
Uri imageData;
petImage = view.findViewById(R.id.imgPetPic);
petImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
startActivityForResult(takePictureIntent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
} catch (ActivityNotFoundException e) {
// display error state to the user
Toast.makeText(getActivity(), "Camera is Not Available", Toast.LENGTH_SHORT).show();
}
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
imageData = data.getData();
Bitmap bp = (Bitmap) data.getExtras().get("data");
petImage.setImageBitmap(bp);
} else if (resultCode == RESULT_CANCELED)
Toast.makeText(getActivity(), "Cancelled", Toast.LENGTH_LONG).show();
}
}
After that code parts worked. ımageData variable is still null. How do i fix this.

How do I pass ArrayLists to another activity, modify it, and return it back to use?

I'm trying to create a login/register part of a project, and I'm having trouble with passing the sign-up information back to the login activity. I initialized username_info, password_info, and name_info in MainActivity, and I want to send it to SignUpActivity through Intent.
Intent i = new Intent(this, SignUpActivity.class);
i.putExtra("username_info", username_info);
i.putExtra("password_info", password_info);
i.putExtra("name_info", name_info);
startActivityForResult(i, 101);
After values are added in the other activity, it's sent back like this (the arraylists have the same name in both activities):
Intent r = new Intent();
r.putExtra("username_info", username_info);
r.putExtra("password_info", password_info);
r.putExtra("name_info", name_info);
setResult(Activity.RESULT_OK, r);
finish();
}
and it's received here:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 101) {
if (resultCode == Activity.RESULT_OK) {
Bundle e = getIntent().getExtras();
username_info = e.getStringArrayList("username_info");
password_info = e.getStringArrayList("password_info");
name_info = e.getStringArrayList("name_info");
}
}
}
But the array lists are unchanged when I get back to the MainActivity. I'm new to Android Studio, so I might just be making a simple mistake.
EDIT:
I'm crashing when the username and password don't match, but it should be returning a toast instead:
#Override
public void onClick(View v) {
username = username_input.getText().toString();
password = password_input.getText().toString();
int index = username_info.indexOf(username);
if (username_info.size() < 1) {
Toast.makeText(MainActivity.this, "You must sign up first", Toast.LENGTH_SHORT).show();
}
else if (password_info.get(index).equals(password)) {
Toast.makeText(MainActivity.this, "make an activity", Toast.LENGTH_SHORT).show();
// open activity
}
else {
Toast.makeText(MainActivity.this, "Incorrect username/password", Toast.LENGTH_SHORT).show();
}
}
});
Don't use getIntent() in onActivityResult, instead use the Intent data:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 101) {
if (resultCode == Activity.RESULT_OK) {
Bundle e = data.getExtras();
username_info = e.getStringArrayList("username_info");
password_info = e.getStringArrayList("password_info");
name_info = e.getStringArrayList("name_info");
}
}
}

how do I get my intent to work with Google Place Autocomplete?

Can you tell me what I need to do to make my intent work please? When the user clicks mEditInit, the Places drop down menu appears.
When the user clicks the place in the menu, I want to send this back to mEditInit
I've used intents before but not working in this case.
public class MyActivity extends AppCompatActivity {
String stuff;
private EditText mEditInit;
public static final int AUTOCOMPLETE_REQUEST_CODE = 1;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
mEditInit = (EditText) findViewById(R.id.edit_message);
mEditInit.setX(0);
mEditInit.setY(250);
//Get the bundle
Bundle bundle = getIntent().getExtras();
if (stuff != null && !stuff.isEmpty())
//Extract the data…
{ stuff = bundle.getString("stuff");
mEditInit.setText(stuff);
}
Places.initialize(this, getString(R.string.places_api_key));
mEditInit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MyActivity.this, "bowwow", Toast.LENGTH_SHORT).show();
List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME);
// Start the autocomplete intent.
Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.OVERLAY, fields).build(MyActivity.this);
startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);
//setResult(RESULT_OK, intent);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Place place = Autocomplete.getPlaceFromIntent(data);
//Toast.makeText(MyActivity.this, place.getName(), Toast.LENGTH_SHORT).show();
Toast.makeText(MyActivity.this, place.getName(), Toast.LENGTH_SHORT).show();
Intent i = new Intent(this, MyActivity.class);
String getrec= place.getName();
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString("stuff", getrec);
//Add the bundle to the intent
i.putExtras(bundle);
// Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
} else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
// TODO: Handle the error.
Status status = Autocomplete.getStatusFromIntent(data);
// Log.i(TAG, status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
// super.onActivityResult(requestCode, resultCode, data);
}
}
}
In your onActivityResult method, you do not need any extra.
Just call the method setText() on your EditText:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Place place = Autocomplete.getPlaceFromIntent(data);
//Toast.makeText(MyActivity.this, place.getName(), Toast.LENGTH_SHORT).show();
mEditInit.setText(place.getName());
} else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
// TODO: Handle the error.
Status status = Autocomplete.getStatusFromIntent(data);
// Log.i(TAG, status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
// super.onActivityResult(requestCode, resultCode, data);
}
}

Return URI to other class

So I want this class, which chooses images out of the gallery and saves the data in the URI to pass this to my imageadapter.class and then display it on the Gridview. How can I do this ?
Thanks,
Code:
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.addimage:
Toast.makeText(getApplicationContext(), "Image added", Toast.LENGTH_SHORT).show();
openGallery();
break;
case R.id.loggout:
Toast.makeText(getApplicationContext(), "logged out", Toast.LENGTH_SHORT).show();
Intent i = new Intent(nav.this, MainActivity.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
private void openGallery(){
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, IMAGE_PICK);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == IMAGE_PICK){
imageuri = data.getData();
System.out.println("success");
}
}
and the adapter's array of images:
public static Integer[] images ={
R.drawable.test, R.drawable.test2, R.drawable.test3, R.drawable.test4, R.drawable.test5, R.drawable.test6, R.drawable.test7, R.drawable.test8
};
If you are asking about sending the result you can do something like so upon successful retrieval of the data,
if(resultCode == RESULT_OK && requestCode == IMAGE_PICK){
Uri imageuri = data.getData();
processImageData(imageuri);
System.out.println("success");
}
Create a setter method at your adapter like
public void setImages(Integer[] images){
this.images = images;
notifyDataSetChanged();
}
and in onActivityResult() method however method you handle uri with create an array of images and call your adapter variable + setter
if(resultCode == RESULT_OK && requestCode == IMAGE_PICK){
//handling and create array list of uri
Integer[] imagesArrayResult = {//......//}
imageadapter.setImages(imagesArrayResult);
}

How to pass default image to previous activity if no image is selected

In my app, I have a camera function. User can capture image or pick from gallery.
Activity B
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK & null != data) {
selectedImage = data.getData();
imageView.setImageURI(selectedImage);
}
break;
case REQUEST_IMAGE_CAPTURE:
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
imageView.setImageURI(null);
imageView.setImageURI(imageUri);
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
}
}
}
}
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent returnIntent = new Intent();
if(selectedImage!=null) {
returnIntent.putExtra("img_uri", selectedImage.toString());
}
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
When submit button is clicked, it will return to previous activity.
Activity A
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == PROJECT_REQUEST_CODE) {
imgURI = Uri.parse(data.getStringExtra("img_uri"));
if (mClickedPosition == -1) {
if (obj != null)
obj.addNewItem(imgURI);
} else {
if (obj != null)
obj.changeItem(mClickedPosition, imgURI);
}
}
}
}
My question now is how to pass a default image to Activity A If
user didn't select any image ?
This is the xml imageView in Activity B
<ImageView
android:paddingTop="30dp"
android:layout_gravity="center"
android:layout_width="330dp"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:src="#mipmap/no_image"
android:scaleType="fitXY"
android:id="#+id/imageView"
android:layout_weight="0.50" />
If no image selected, I want #mipmap/no_image return to Activity B. Is it possible ? Thanks.
You can pass an Uri of your image stored in resources by the next way:
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent returnIntent = new Intent();
if(selectedImage!=null) {
returnIntent.putExtra("img_uri", selectedImage.toString());
} else {
returnIntent.putExtra("img_uri", Uri.parse("android.resource://your.package.name/mipmap/no_image").toString());
}
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
Then you can use it as usual Uri to show the image in ImageView.
ByDefault set value of selectedImage to "default".
Now in your addNewItem() and changeItem() check value passed in imageUri
if(imageUri.equalsIgnoreCase("default"))
// set your default image that is #mipmap/no_image
else
// set image you are getting from imageUri
Code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK & null != data) {
selectedImage = data.getData();
imageView.setImageURI(selectedImage);
}else{
//set default
}
break;
case REQUEST_IMAGE_CAPTURE:
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
imageView.setImageURI(null);
imageView.setImageURI(imageUri);
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
}
}else{
//set default
}
default{
//set default
}
}
You don't need to return a default image to Activity A. Like others wrote, you just have to prepare for the condition when the user doesn't select any image.
Modify your onActivityResult for Activity A like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(data!=null){
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK) {
selectedImage = data.getData();
imageView.setImageURI(selectedImage);
}
break;
case REQUEST_IMAGE_CAPTURE:
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
imageView.setImageURI(imageUri);
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show();
}
}
break;
default:
//Your default image goes here, when the user doesn't select either of the two options
imageView.setImageResource(R.drawable.<default_image>);
break;
}
}

Categories